<commit_before>/* ========================================================================
 * Chart.js: Chart.Doughnut.js [Version: 1.0.2]
 * http://chartjs.org/
 *
 * ZUI: The file has been changed in ZUI. It will not keep update with the
 * official version in the future.
 * http://zui.sexy
 * ========================================================================
 * Copyright 2015 Nick Downie, Released under the MIT license
 * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
 * ======================================================================== */

/// ----- ZUI change begin -----
/// Add jquery object to namespace

/// (function(){ // Old code
(function($) {

    /// ----- ZUI change end -----
    "use strict";

    /// ----- ZUI change begin -----
    /// Change root to zui shared object
    ///
    ///   var root = this, // old code
    var root = $ && $.zui ? $.zui : this,
        /// ----- ZUI change end -----
        Chart = root.Chart,
        //Cache a local reference to Chart.helpers
        helpers = Chart.helpers;

    var defaultConfig = {
        //Boolean - Whether we should show a stroke on each segment
        segmentShowStroke: true,

        //String - The colour of each segment stroke
        segmentStrokeColor: "#fff",

        //Number - The width of each segment stroke
        /// ZUI change begin
        ///        segmentStrokeWidth: 2, // old code
        segmentStrokeWidth: 1,
        /// ZUI change end

        //The percentage of the chart that we cut out of the middle.
        percentageInnerCutout: 50,

        /// ZUI change begin
        // Boolean - Whether to show labels on the scale
        scaleShowLabels: false,

        // Interpolated JS string - can access value
        scaleLabel: "<%=value%>",

        // String - Scale label position
        scaleLabelPlacement: 'auto',

        ///        Number - Amount of animation steps // old code
        ///        animationSteps: 100, // old code
        animationSteps: 60,
        /// ZUI change end

        //String - Animation easing effect
        animationEasing: "easeOutBounce",

        //Boolean - Whether we animate the rotation of the Doughnut
        animateRotate: true,

        //Boolean - Whether we animate scaling the Doughnut from the centre
        animateScale: false,

        //String - A legend template
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%>
<span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%>
<%}%>
"

    };

    Chart.Type.extend({
        //Passing in a name registers this chart in the Chart namespace
        name: "Doughnut",
        //Providing a defaults will also register the deafults in the chart namespace
        defaults: defaultConfig,
        //Initialize is fired when the chart is initialized - Data is passed in as a parameter
        //Config is automatically merged by the core of Chart.js, and is available at this.options
        initialize: function(data) {

            //Declare segments as a static property to prevent inheriting across the Chart type prototype
            this.segments = [];
            this.outerRadius = (helpers.min([this.chart.width, this.chart.height]) - this.options.segmentStrokeWidth / 2) / 2;

            this.SegmentArc = Chart.Arc.extend({
                ctx: this.chart.ctx,
                x: this.chart.width / 2,
                y: this.chart.height / 2
            });

            //Set up tooltip events on the chart
            if(this.options.showTooltips) {
                helpers.bindEvents(this, this.options.tooltipEvents, function(evt) {
                    var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];

                    helpers.each(this.segments, function(segment) {
                        segment.restore(["fillColor"]);
                    });
                    helpers.each(activeSegments, function(activeSegment) {
                        activeSegment.fillColor = activeSegment.highlightColor;
                    });
                    this.showTooltip(activeSegments);
                });
            }
            this.calculateTotal(data);

            helpers.each(data, function(datapoint, index) {
                this.addData(datapoint, index, true);
            }, this);

            this.render();
        },
        getSegmentsAtEvent: function(e) {
            var segmentsArray = [];

            var location = helpers.getRelativePosition(e);

            helpers.each(this.segments, function(segment) {
                if(segment.inRange(location.x, location.y)) segmentsArray.push(segment);
            }, this);
            return segmentsArray;
        },
        addData: function(segment, atIndex, silent) {
            /// ----- ZUI change begin -----
            /// Init segment color
            if($.zui && $.zui.Color && $.zui.Color.get) {
                var color = new $.zui.Color.get(segment.color);
                segment.color = color.toCssStr();
                if(!segment.highlight) segment.highlight = color.lighten(5).toCssStr();
            }
            /// ----- ZUI change end -----
            var index = atIndex || this.segments.length;
            this.segments.splice(index, 0, new this.SegmentArc({
                id: typeof segment.id === 'undefined' ? index : segment.id,
                value: segment.value,
                outerRadius: (this.options.animateScale) ? 0 : this.outerRadius,
                innerRadius: (this.options.animateScale) ? 0 : (this.outerRadius / 100) * this.options.percentageInnerCutout,
                fillColor: segment.color,
                highlightColor: segment.highlight || segment.color,
                showStroke: this.options.segmentShowStroke,
                strokeWidth: this.options.segmentStrokeWidth,
                strokeColor: this.options.segmentStrokeColor,
                startAngle: Math.PI * 1.5,
                circumference: (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
                /// ----- ZUI change begin -----
                showLabel: segment.showLabel !== false,
                /// ----- ZUI change end -----
                label: segment.label
            }));
            if(!silent) {
                this.reflow();
                this.update();
            }
        },
        calculateCircumference: function(value) {
            return(Math.PI * 2) * (Math.abs(value) / this.total);
        },
        calculateTotal: function(data) {
            this.total = 0;
            helpers.each(data, function(segment) {
                this.total += Math.abs(segment.value);
            }, this);
        },
        update: function() {
            this.calculateTotal(this.segments);

            // Reset any highlight colours before updating.
            helpers.each(this.activeElements, function(activeElement) {
                activeElement.restore(['fillColor']);
            });

            helpers.each(this.segments, function(segment) {
                segment.save();
            });
            this.render();
        },

        removeData: function(atIndex) {
            var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length - 1;
            this.segments.splice(indexToDelete, 1);
            this.reflow();
            this.update();
        },

        reflow: function() {
            helpers.extend(this.SegmentArc.prototype, {
                x: this.chart.width / 2,
                y: this.chart.height / 2
            });
            this.outerRadius = (helpers.min([this.chart.width, this.chart.height]) - this.options.segmentStrokeWidth / 2) / 2;
            helpers.each(this.segments, function(segment) {
                segment.update({
                    outerRadius: this.outerRadius,
                    innerRadius: (this.outerRadius / 100) * this.options.percentageInnerCutout
                });
            }, this);
        },
        /// ZUI change begin
        drawLabel: function(segment, easeDecimal, labelPosMap) {
            var options = this.options;
            var middleAngle = (segment.endAngle + segment.startAngle) / 2;
            var placement = options.scaleLabelPlacement;
            if(placement !== 'inside' && placement !== 'outside') {
                if((this.chart.width - this.chart.height) > 50) {
                    if(segment.circumference < (Math.PI / 36)) {
                        placement = 'outside';
                    }
                }
            }

            var x = Math.cos(middleAngle) * segment.outerRadius,
                y = Math.sin(middleAngle) * segment.outerRadius,
                text = helpers.template(options.scaleLabel, {
                    value: typeof easeDecimal === 'undefined' ? segment.value : Math.round(easeDecimal * segment.value),
                    label: segment.label
                });

            var ctx = this.chart.ctx;
            ctx.font = helpers.fontString(options.scaleFontSize, options.scaleFontStyle, options.scaleFontFamily);
            ctx.textBaseline = "middle";
            ctx.textAlign = "center";

            var textWidth = ctx.measureText(text).width;
            var chartWidthHalf = this.chart.width / 2;
            var chartHeightHalf = this.chart.height / 2;

            if(placement === 'outside') { // outside
                var isRight = x >= 0;
                var lineX = x + chartWidthHalf;
                var lineY = y + chartHeightHalf;
                ctx.textAlign = isRight ? 'left' : 'right';
                ctx.measureText(text).width;
                if(isRight) {
                    x = Math.max(chartWidthHalf + segment.outerRadius + 10, x + 30 + chartWidthHalf);
                } else {
                    x = Math.min(chartWidthHalf - segment.outerRadius - 10, x - 30 + chartWidthHalf);
                }

                var textHeight = options.scaleFontSize;
                var labelPos = Math.round((y * 0.8 + chartHeightHalf) / textHeight) + 1;
                var maxPos = Math.floor(this.chart.width / textHeight) + 1;
                if(labelPosMap[isRight ? labelPos : (-labelPos)]) {
                    if(labelPos > 1) labelPos--;
                    else labelPos++;
                }
                while(labelPosMap[isRight ? labelPos : (-labelPos)] && labelPos < maxPos) labelPos++;

                if(labelPosMap[isRight ? labelPos : (-labelPos)]) return;
                y = (labelPos - 1) * textHeight + options.scaleFontSize / 2;
                labelPosMap[labelPos] = true;

                ctx.beginPath();
                ctx.moveTo(lineX, lineY);
                ctx.lineTo(x, y);
                x = isRight ? (x + 5) : (x - 5);
                ctx.lineTo(x, y);
                ctx.strokeStyle = ($.zui && $.zui.Color) ? (new $.zui.Color(segment.fillColor).fade(40).toCssStr()) : segment.fillColor;
                ctx.strokeWidth = options.scaleLineWidth;
                ctx.stroke();
                ctx.fillStyle = segment.fillColor;
            } else { // inside
                x = x * 0.6 + chartWidthHalf;
                y = y * 0.6 + chartHeightHalf;
                ctx.fillStyle = ($.zui && $.zui.Color) ? (new $.zui.Color(segment.fillColor).contrast().toCssStr()) : '#fff';
            }
            ctx.fillText(text, x, y);
        },
        // ZUI change end
        draw: function(easeDecimal) {
            var animDecimal = (easeDecimal) ? easeDecimal : 1;
            this.clear();
            // ZUI change begin
            var labelPositionMap;
            // ZUI change end
            helpers.each(this.segments, function(segment, index) {
                segment.transition({
                    circumference: this.calculateCircumference(segment.value),
                    outerRadius: this.outerRadius,
                    innerRadius: (this.outerRadius / 100) * this.options.percentageInnerCutout
                }, animDecimal);

                segment.endAngle = segment.startAngle + segment.circumference;

                segment.draw();
                if(index === 0) {
                    segment.startAngle = Math.PI * 1.5;
                }
                //Check to see if it's the last segment, if not get the next and update the start angle
                if(index < this.segments.length - 1) {
                    this.segments[index + 1].startAngle = segment.endAngle;
                }

                /// ZUI change begin
                if(this.options.scaleShowLabels && segment.showLabel) {
                    if(!labelPositionMap) labelPositionMap = {};
                    this.drawLabel(segment, easeDecimal, labelPositionMap);
                }
                /// ZUI change end
            }, this);
        }
    });

    Chart.types.Doughnut.extend({
        name: "Pie",
        defaults: helpers.merge(defaultConfig, {
            percentageInnerCutout: 0
        })
    });

    /// ----- ZUI change begin -----
    /// Use jquery object to create Chart object
    $.fn.pieChart = function(data, options) {
        var pieCharts = [];
        this.each(function() {
            var $this = $(this);
            pieCharts.push(new Chart(this.getContext("2d")).Pie(data, $.extend($this.data(), options)));
        });
        return pieCharts.length === 1 ? pieCharts[0] : pieCharts;
    }

    $.fn.doughnutChart = function(data, options) {
        var doughnutCharts = [];
        this.each(function() {
            var $this = $(this);
            doughnutCharts.push(new Chart(this.getContext("2d")).Doughnut(data, $.extend($this.data(), options)));
        });
        return doughnutCharts.length === 1 ? doughnutCharts[0] : doughnutCharts;
    }

    /// ----- ZUI change end -----

    /// ----- ZUI change begin -----
    /// Add jquery object to namespace

    /// }).call(this); // Old code
}).call(this, jQuery);

/// ----- ZUI change end -----

<commit_msg> * improve doughnut labels drawing method.<commit_after>/* ========================================================================
 * Chart.js: Chart.Doughnut.js [Version: 1.0.2]
 * http://chartjs.org/
 *
 * ZUI: The file has been changed in ZUI. It will not keep update with the
 * official version in the future.
 * http://zui.sexy
 * ========================================================================
 * Copyright 2015 Nick Downie, Released under the MIT license
 * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
 * ======================================================================== */

/// ----- ZUI change begin -----
/// Add jquery object to namespace

/// (function(){ // Old code
(function($) {

    /// ----- ZUI change end -----
    "use strict";

    /// ----- ZUI change begin -----
    /// Change root to zui shared object
    ///
    ///   var root = this, // old code
    var root = $ && $.zui ? $.zui : this,
        /// ----- ZUI change end -----
        Chart = root.Chart,
        //Cache a local reference to Chart.helpers
        helpers = Chart.helpers;

    var defaultConfig = {
        //Boolean - Whether we should show a stroke on each segment
        segmentShowStroke: true,

        //String - The colour of each segment stroke
        segmentStrokeColor: "#fff",

        //Number - The width of each segment stroke
        /// ZUI change begin
        ///        segmentStrokeWidth: 2, // old code
        segmentStrokeWidth: 1,
        /// ZUI change end

        //The percentage of the chart that we cut out of the middle.
        percentageInnerCutout: 50,

        /// ZUI change begin
        // Boolean - Whether to show labels on the scale
        scaleShowLabels: false,

        // Interpolated JS string - can access value
        scaleLabel: "<%=value%>",

        // String - Scale label position
        scaleLabelPlacement: 'auto',

        ///        Number - Amount of animation steps // old code
        ///        animationSteps: 100, // old code
        animationSteps: 60,
        /// ZUI change end

        //String - Animation easing effect
        animationEasing: "easeOutBounce",

        //Boolean - Whether we animate the rotation of the Doughnut
        animateRotate: true,

        //Boolean - Whether we animate scaling the Doughnut from the centre
        animateScale: false,

        //String - A legend template
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%>
<span style=\"background-color:<%=segments[i].fillColor%>\"><%if(segments[i].label){%><%=segments[i].label%><%}%>
<%}%>
"

    };

    Chart.Type.extend({
        //Passing in a name registers this chart in the Chart namespace
        name: "Doughnut",
        //Providing a defaults will also register the deafults in the chart namespace
        defaults: defaultConfig,
        //Initialize is fired when the chart is initialized - Data is passed in as a parameter
        //Config is automatically merged by the core of Chart.js, and is available at this.options
        initialize: function(data) {

            //Declare segments as a static property to prevent inheriting across the Chart type prototype
            this.segments = [];
            this.outerRadius = (helpers.min([this.chart.width, this.chart.height]) - this.options.segmentStrokeWidth / 2) / 2;

            this.SegmentArc = Chart.Arc.extend({
                ctx: this.chart.ctx,
                x: this.chart.width / 2,
                y: this.chart.height / 2
            });

            //Set up tooltip events on the chart
            if(this.options.showTooltips) {
                helpers.bindEvents(this, this.options.tooltipEvents, function(evt) {
                    var activeSegments = (evt.type !== 'mouseout') ? this.getSegmentsAtEvent(evt) : [];

                    helpers.each(this.segments, function(segment) {
                        segment.restore(["fillColor"]);
                    });
                    helpers.each(activeSegments, function(activeSegment) {
                        activeSegment.fillColor = activeSegment.highlightColor;
                    });
                    this.showTooltip(activeSegments);
                });
            }
            this.calculateTotal(data);

            helpers.each(data, function(datapoint, index) {
                this.addData(datapoint, index, true);
            }, this);

            this.render();
        },
        getSegmentsAtEvent: function(e) {
            var segmentsArray = [];

            var location = helpers.getRelativePosition(e);

            helpers.each(this.segments, function(segment) {
                if(segment.inRange(location.x, location.y)) segmentsArray.push(segment);
            }, this);
            return segmentsArray;
        },
        addData: function(segment, atIndex, silent) {
            /// ----- ZUI change begin -----
            /// Init segment color
            if($.zui && $.zui.Color && $.zui.Color.get) {
                var color = new $.zui.Color.get(segment.color);
                segment.color = color.toCssStr();
                if(!segment.highlight) segment.highlight = color.lighten(5).toCssStr();
            }
            /// ----- ZUI change end -----
            var index = atIndex || this.segments.length;
            this.segments.splice(index, 0, new this.SegmentArc({
                id: typeof segment.id === 'undefined' ? index : segment.id,
                value: segment.value,
                outerRadius: (this.options.animateScale) ? 0 : this.outerRadius,
                innerRadius: (this.options.animateScale) ? 0 : (this.outerRadius / 100) * this.options.percentageInnerCutout,
                fillColor: segment.color,
                highlightColor: segment.highlight || segment.color,
                showStroke: this.options.segmentShowStroke,
                strokeWidth: this.options.segmentStrokeWidth,
                strokeColor: this.options.segmentStrokeColor,
                startAngle: Math.PI * 1.5,
                circumference: (this.options.animateRotate) ? 0 : this.calculateCircumference(segment.value),
                /// ----- ZUI change begin -----
                showLabel: segment.showLabel !== false,
                /// ----- ZUI change end -----
                label: segment.label
            }));
            if(!silent) {
                this.reflow();
                this.update();
            }
        },
        calculateCircumference: function(value) {
            return(Math.PI * 2) * (Math.abs(value) / this.total);
        },
        calculateTotal: function(data) {
            this.total = 0;
            helpers.each(data, function(segment) {
                this.total += Math.abs(segment.value);
            }, this);
        },
        update: function() {
            this.calculateTotal(this.segments);

            // Reset any highlight colours before updating.
            helpers.each(this.activeElements, function(activeElement) {
                activeElement.restore(['fillColor']);
            });

            helpers.each(this.segments, function(segment) {
                segment.save();
            });
            this.render();
        },

        removeData: function(atIndex) {
            var indexToDelete = (helpers.isNumber(atIndex)) ? atIndex : this.segments.length - 1;
            this.segments.splice(indexToDelete, 1);
            this.reflow();
            this.update();
        },

        reflow: function() {
            helpers.extend(this.SegmentArc.prototype, {
                x: this.chart.width / 2,
                y: this.chart.height / 2
            });
            this.outerRadius = (helpers.min([this.chart.width, this.chart.height]) - this.options.segmentStrokeWidth / 2) / 2;
            helpers.each(this.segments, function(segment) {
                segment.update({
                    outerRadius: this.outerRadius,
                    innerRadius: (this.outerRadius / 100) * this.options.percentageInnerCutout
                });
            }, this);
        },
        /// ZUI change begin
        drawLabel: function(segment, easeDecimal, labelPosMap) {
            var options = this.options;
            var middleAngle = (segment.endAngle + segment.startAngle) / 2;
            var placement = options.scaleLabelPlacement;
            if(placement !== 'inside' && placement !== 'outside') {
                if((this.chart.width - this.chart.height) > 50) {
                    if(segment.circumference < (Math.PI / 18)) {
                        placement = 'outside';
                    }
                }
            }

            var x = Math.cos(middleAngle) * segment.outerRadius,
                y = Math.sin(middleAngle) * segment.outerRadius,
                text = helpers.template(options.scaleLabel, {
                    value: typeof easeDecimal === 'undefined' ? segment.value : Math.round(easeDecimal * segment.value),
                    label: segment.label
                });

            var ctx = this.chart.ctx;
            ctx.font = helpers.fontString(options.scaleFontSize, options.scaleFontStyle, options.scaleFontFamily);
            ctx.textBaseline = "middle";
            ctx.textAlign = "center";

            var textWidth = ctx.measureText(text).width;
            var chartWidthHalf = this.chart.width / 2;
            var chartHeightHalf = this.chart.height / 2;

            if(placement === 'outside') { // outside
                var isRight = x >= 0;
                var lineX = x + chartWidthHalf;
                var lineY = y + chartHeightHalf;
                ctx.textAlign = isRight ? 'left' : 'right';
                ctx.measureText(text).width;
                if(isRight) {
                    x = Math.max(chartWidthHalf + segment.outerRadius + 10, x + 30 + chartWidthHalf);
                } else {
                    x = Math.min(chartWidthHalf - segment.outerRadius - 10, x - 30 + chartWidthHalf);
                }

                var textHeight = options.scaleFontSize;
                var labelPos = Math.round((y * 0.8 + chartHeightHalf) / textHeight) + 1;
                var maxPos = Math.floor(this.chart.width / textHeight) + 1;
                var labelPosDirection = isRight ? 1 : (-1);
                if(labelPosMap[labelPos*labelPosDirection]) {
                    if(labelPos > 1) labelPos--;
                    else labelPos++;
                }
                // while(labelPosMap[labelPos*labelPosDirection] && labelPos < maxPos) labelPos++;

                if(labelPosMap[labelPos*labelPosDirection]) return;
                y = (labelPos - 1) * textHeight + options.scaleFontSize / 2;
                labelPosMap[labelPos*labelPosDirection] = true;

                ctx.beginPath();
                ctx.moveTo(lineX, lineY);
                ctx.lineTo(x, y);
                x = isRight ? (x + 5) : (x - 5);
                ctx.lineTo(x, y);
                ctx.strokeStyle = ($.zui && $.zui.Color) ? (new $.zui.Color(segment.fillColor).fade(40).toCssStr()) : segment.fillColor;
                ctx.strokeWidth = options.scaleLineWidth;
                ctx.stroke();
                ctx.fillStyle = segment.fillColor;
            } else { // inside
                x = x * 0.7 + chartWidthHalf;
                y = y * 0.7 + chartHeightHalf;
                ctx.fillStyle = ($.zui && $.zui.Color) ? (new $.zui.Color(segment.fillColor).contrast().toCssStr()) : '#fff';
            }
            ctx.fillText(text, x, y);
        },
        // ZUI change end
        draw: function(easeDecimal) {
            var animDecimal = (easeDecimal) ? easeDecimal : 1;
            this.clear();
            // ZUI change begin
            var labelPositionMap;
            // ZUI change end
            helpers.each(this.segments, function(segment, index) {
                segment.transition({
                    circumference: this.calculateCircumference(segment.value),
                    outerRadius: this.outerRadius,
                    innerRadius: (this.outerRadius / 100) * this.options.percentageInnerCutout
                }, animDecimal);

                segment.endAngle = segment.startAngle + segment.circumference;

                segment.draw();
                if(index === 0) {
                    segment.startAngle = Math.PI * 1.5;
                }
                //Check to see if it's the last segment, if not get the next and update the start angle
                if(index < this.segments.length - 1) {
                    this.segments[index + 1].startAngle = segment.endAngle;
                }
            }, this);

            /// ZUI change begin
            if(this.options.scaleShowLabels) {
                var segmentsArray = this.segments.slice().sort(function(a,b){return b.value - a.value;});
                var labelPositionMap = {};
                helpers.each(segmentsArray, function(segment, index) {
                    if(segment.showLabel) this.drawLabel(segment, easeDecimal, labelPositionMap);
                }, this);
            }
            /// ZUI change end
        }
    });

    Chart.types.Doughnut.extend({
        name: "Pie",
        defaults: helpers.merge(defaultConfig, {
            percentageInnerCutout: 0
        })
    });

    /// ----- ZUI change begin -----
    /// Use jquery object to create Chart object
    $.fn.pieChart = function(data, options) {
        var pieCharts = [];
        this.each(function() {
            var $this = $(this);
            pieCharts.push(new Chart(this.getContext("2d")).Pie(data, $.extend($this.data(), options)));
        });
        return pieCharts.length === 1 ? pieCharts[0] : pieCharts;
    }

    $.fn.doughnutChart = function(data, options) {
        var doughnutCharts = [];
        this.each(function() {
            var $this = $(this);
            doughnutCharts.push(new Chart(this.getContext("2d")).Doughnut(data, $.extend($this.data(), options)));
        });
        return doughnutCharts.length === 1 ? doughnutCharts[0] : doughnutCharts;
    }

    /// ----- ZUI change end -----

    /// ----- ZUI change begin -----
    /// Add jquery object to namespace

    /// }).call(this); // Old code
}).call(this, jQuery);

/// ----- ZUI change end -----

<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack');
var Webpack_isomorphic_tools_plugin = require('webpack-isomorphic-tools/plugin')

var webpack_isomorphic_tools_plugin =
    new Webpack_isomorphic_tools_plugin(require('./webpack-isomorphic-tools-config'))
        .development();

module.exports = {
  entry: [
        'webpack-dev-server/client?http://127.0.0.1:8080/',
        'webpack/hot/only-dev-server',
        './src/index'
  ],

  output: {
        path: path.resolve(__dirname, 'assets'),
        filename: 'bundle.js',
        publicPath: '/assets/'
  },

  plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        webpack_isomorphic_tools_plugin
  ],

  module: {
        loaders: [
            {
                test: /\.js$/,
                loaders: ['babel'],
                exclude: /node_modules/
            },

            {
                test: /\.scss$/,
                loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]---[local]---[hash:base64:5]!sass-loader'
            },

            {
                test: webpack_isomorphic_tools_plugin.regular_expression('images'),
                loader: 'file-loader'
            }
        ]
  }
};<commit_msg>fix double HMR<commit_after>var path = require('path');
var webpack = require('webpack');
var Webpack_isomorphic_tools_plugin = require('webpack-isomorphic-tools/plugin')

var webpack_isomorphic_tools_plugin =
    new Webpack_isomorphic_tools_plugin(require('./webpack-isomorphic-tools-config'))
        .development();

module.exports = {
  entry: [
        'webpack-dev-server/client?http://127.0.0.1:8080/',
        './src/index'
  ],

  output: {
        path: path.resolve(__dirname, 'assets'),
        filename: 'bundle.js',
        publicPath: '/assets/'
  },

  plugins: [
        new webpack.NoErrorsPlugin(),
        webpack_isomorphic_tools_plugin
  ],

  module: {
        loaders: [
            {
                test: /\.js$/,
                loaders: ['babel'],
                exclude: /node_modules/
            },

            {
                test: webpack_isomorphic_tools_plugin.regular_expression('style_modules'),
                loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[name]---[local]---[hash:base64:5]!sass-loader'
            },

            {
                test: webpack_isomorphic_tools_plugin.regular_expression('images'),
                loader: 'file-loader'
            }
        ]
  }
};<|endoftext|>


<commit_before>describe('directive: pikaday', function() {
  var element, scope;

  beforeEach(module('pikaday'));

  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();

    element = '<input pikaday="myPickerObject">';

    element = $compile(element)(scope);
    scope.$digest();

  }));

  describe('with the first given value', function() {
    it("should compute the size to create other values", function() {
      var isolated = element.isolateScope();
      assert.equal(-1, [1,2,3].indexOf(5));
    });
  });
});
<commit_msg>added first test :)<commit_after>describe('directive: pikaday', function() {
  var element, scope;

  beforeEach(module('pikaday'));

  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();

    element = '<input pikaday="myPickerObject" number-of-months="2" >';

    element = $compile(element)(scope);
    scope.$digest();

  }));

  describe('inline attribute', function() {

    it("number-of-months should be applied", function() {
      assert.equal(scope.myPickerObject._o.numberOfMonths, 2);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

require('dotenv').config({path: `${__dirname}/../.test.env`});
const superagent = require('superagent');
const expect = require('expect');

const server = require('../lib/server.js');
const cleanDB = require('./lib/clean-db.js');
const mockIncident = require('./lib/mock-incident.js');
const mockUser = require('./lib/mock-user.js');

// const mockComment = require('./lib/mock-comment.js');
const mockResidence = require('./lib/mock-residence.js');

const API_URL = process.env.API_URL;

describe('Testing Incident Model (TJay) :', () => {
  before(server.start);
  after(server.stop);
  afterEach(cleanDB);

  describe('Testing POST', () => {
    it('should return 201 - blah blah', () => {
      return mockUser.createOne()
        .then(mockUserData => {
          return mockResidence.createOne()
            .then(mockResidenceData => {
              return superagent.post(`${API_URL}/api/incidents`)
                .set('Authorization', `Bearer ${mockUserData.token}`)
                .send({
                  userId: mockUserData.user._id,
                  type: 'HOA',
                  description: 'Turd On lawn',
                  residenceId: mockResidenceData.id,
                })
                .then(res => {
                  expect(res.status).toEqual(201);
                });
            });
        });
    });

    it('should return 400 - blah blah', () => {
      return mockUser.createOne()
        .then(mockUserData => {
          return superagent.post(`${API_URL}/api/incidents`)
            .set('Authorization', `Bearer ${mockUserData.token}`)
            .send({})
            .catch(res => {
              expect(res.status).toEqual(400);
            });
        });
    });

    it('should return 401 - blah blah', () => {
      return mockUser.createOne()
        .then(mockUserData => {
          return mockResidence.createOne()
            .then(mockResidenceData => {
              return superagent.post(`${API_URL}/api/incidents`)
                .send({
                  userId: mockUserData.user._id,
                  type: 'HOA',
                  description: 'Turd On lawn',
                  residenceId: mockResidenceData.id,
                })
                .catch(res => {
                  expect(res.status).toEqual(401);
                });
            });
        });
    });

    it('should return with 404 - invalid body :', () => {
      return superagent
        .post(`${API_URL}/api/incidents/chunk`)
        .send({
          number: '30 Billion'
        })
        .then(res => {
          throw res;
        })
        .catch(res => {
          expect(res.status).toEqual(404);
        });
    });
  });

  describe('Testing GET - Incident Array', () => {
    it('should return 200 - blah blah', () => {
      return mockIncident.createOne().then(() => {
        return superagent
          .get(`${API_URL}/api/incidents/`)
          .then(res => {
            expect(res.body).toBeAn('array');
            expect(res.status).toBe(200);
          });
      });
    });
  });

  describe('Testing GET - Single Incident', () => {
    it('should return 200 - blah blah', () => {
      return mockIncident.createOne().then(mockIncidentData => {
        return superagent
          .get(`${API_URL}/api/incidents/${mockIncidentData.id}`)
          .then(res => {
            expect(res.status).toEqual(200);
            expect(res.body._id).toExist();
            expect(res.body.userId).toEqual(mockIncidentData.userId);
            expect(res.body.timeStamp).toExist();
            expect(res.body.type).toEqual(mockIncidentData.type);
            expect(res.body.description).toEqual(mockIncidentData.description);
            expect(res.body.residenceId).toEqual(mockIncidentData.residenceId);
          });
      });
    });

    it('Should return 404', () => {
      return superagent.get(`${API_URL}/api/incidents/chunks`)
        .then(res => {
          throw res;
        })
        .catch(res => {
          expect(res.status).toEqual(404);
        });
    });
  });
});
<commit_msg>Pull for whatever reason<commit_after>'use strict';

require('dotenv').config({path: `${__dirname}/../.test.env`});
const superagent = require('superagent');
const expect = require('expect');

const server = require('../lib/server.js');
const cleanDB = require('./lib/clean-db.js');
const mockIncident = require('./lib/mock-incident.js');
const mockUser = require('./lib/mock-user.js');

// const mockComment = require('./lib/mock-comment.js');
const mockResidence = require('./lib/mock-residence.js');

const API_URL = process.env.API_URL;

describe('Testing Incident Model (TJay) :', () => {
  before(server.start);
  after(server.stop);
  afterEach(cleanDB);

  describe('Testing POST', () => {
    it('should return 201 - blah blah', () => {
      return mockUser.createOne()
        .then(mockUserData => {
          return mockResidence.createOne()
            .then(mockResidenceData => {
              return superagent.post(`${API_URL}/api/incidents`)
                .set('Authorization', `Bearer ${mockUserData.token}`)
                .send({
                  userId: mockUserData.user._id,
                  type: 'HOA',
                  description: 'Turd On lawn',
                  residenceId: mockResidenceData.id,
                })
                .then(res => {
                  expect(res.status).toEqual(201);
                });
            });
        });
    });

    it('should return 400 - Invalid Body', () => {
      return mockUser.createOne()
        .then(mockUserData => {
          return superagent.post(`${API_URL}/api/incidents`)
            .set('Authorization', `Bearer ${mockUserData.token}`)
            .send({})
            .catch(res => {
              expect(res.status).toEqual(400);
            });
        });
    });

    it('should return 401 - Unauthorized Access', () => {
      return mockUser.createOne()
        .then(mockUserData => {
          return mockResidence.createOne()
            .then(mockResidenceData => {
              return superagent.post(`${API_URL}/api/incidents`)
                .send({
                  userId: mockUserData.user._id,
                  type: 'HOA',
                  description: 'Turd On lawn',
                  residenceId: mockResidenceData.id,
                })
                .catch(res => {
                  expect(res.status).toEqual(401);
                });
            });
        });
    });

    it('should return with 404 - invalid body :', () => {
      return superagent
        .post(`${API_URL}/api/incidents/chunks`)
        .send({
          number: '30 Billion'
        })
        .then(res => {
          throw res;
        })
        .catch(res => {
          expect(res.status).toEqual(404);
        });
    });
  });

  describe('Testing GET - Incident Array', () => {
    it('should return 200 - Array of Incidents', () => {
      return mockIncident.createOne().then(() => {
        return superagent
          .get(`${API_URL}/api/incidents/`)
          .then(res => {
            expect(res.body).toBeAn('array');
            expect(res.status).toBe(200);
          });
      });
    });
  });

  describe('Testing GET - Single Incident', () => {
    it('should return 200 - Single Incidenrt Report', () => {
      return mockIncident.createOne().then(mockIncidentData => {
        return superagent
          .get(`${API_URL}/api/incidents/${mockIncidentData.id}`)
          .then(res => {
            expect(res.status).toEqual(200);
            expect(res.body._id).toExist();
            expect(res.body.userId).toEqual(mockIncidentData.userId);
            expect(res.body.timeStamp).toExist();
            expect(res.body.type).toEqual(mockIncidentData.type);
            expect(res.body.description).toEqual(mockIncidentData.description);
            expect(res.body.residenceId).toEqual(mockIncidentData.residenceId);
          });
      });
    });

    it('Should return 404', () => {
      return superagent.get(`${API_URL}/api/incidents/chunks`)
        .then(res => {
          throw res;
        })
        .catch(res => {
          expect(res.status).toEqual(404);
        });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

import $ from 'jquery';

import Modal from './modal';
import Backend from '../backend';
import { baseUrl } from '../lib/utils';

import support from '../lib/support';
import { notify } from './notification';
import { version } from '../../../../package.json';

const contents = `\

\

Landmarker.io
\

v${version}
\

\

\

Connect to Dropbox
\

\

\
            \

Connect to a landmarker server
\

\

\
            See a demo\

\

\
    \
        \
        More info on Github\
    \

\
`;

const lsWarning = `\

\
    Your browser doesn't support LocalStorage, so Dropbox login has been\
    disabled.\

`;

const httpsWarning = `\

\
    You are currently on an non-https connection. For security reasons Dropbox integration has been disabled.

`;

const mixedContentWarning = `

Your are currently trying to connect to a non secured server from a secure (https) connection. This is  unadvisable and thus we do not allow it.

You can visit insecure.landmarker.io to disable this warning.

`;

const Intro = Modal.extend({

    closable: false,
    modifiers: ['Small'],

    events: {
        'click .IntroItem--Dropbox': 'startDropbox',
        'click .IntroItem--Server': 'startServer',
        'click .IntroItem--Demo': 'startDemo'
    },

    init: function ({cfg}) {
        this._cfg = cfg;
    },

    content: function () {
        const $contents = $(contents);

        if (!support.localstorage) {
            $contents.find('.IntroItem--Dropbox').remove();
            $contents.find('.IntroItems').append($(lsWarning));
        }

        if (
            !support.https &&
            window.location.origin !== "http://localhost:4000"
        ) {
            $contents.find('.IntroItem--Dropbox').remove();
            $contents.find('.IntroItems').append($(httpsWarning));
        }

        return $contents;
    },

    _restart: function (serverUrl) {
        this._cfg.clear();
        const restartUrl = (
            baseUrl() + (serverUrl ? `?server=${serverUrl}` : '')
        );
        window.location.replace(restartUrl);
    },

    startDropbox: function () {
        this._cfg.clear();
        const [dropUrl, state] = Backend.Dropbox.authorize();
        this._cfg.set({
            'OAUTH_STATE': state,
            'BACKEND_TYPE': Backend.Dropbox.Type
        }, true);
        window.location.replace(dropUrl);
    },

    startDemo: function () {
        this._restart('demo');
    },

    startServer: function () {
        Modal.prompt('Where is your server located ?', (value) => {
            if (support.https && value.indexOf('https://') !== 0) {
                notify({
                    type: 'error',
                    msg: $(mixedContentWarning),
                    actions: [['Retry', this.open]]
                });
            } else {
                this._restart(value);
            }
        }, () => {
            this.open();
        });
    }
});

let instance;
export default {
    init: function (opts) { instance = new Intro(opts); },

    open: function () {
        instance._cfg.clear();
        history.replaceState(null, null, baseUrl());
        instance.open();
    },

    close: function () { instance.close(); },
    initialized: function () { return !!instance; }
};
<commit_msg>Fix insecure.landmarker.io url<commit_after>'use strict';

import $ from 'jquery';

import Modal from './modal';
import Backend from '../backend';
import { baseUrl } from '../lib/utils';

import support from '../lib/support';
import { notify } from './notification';
import { version } from '../../../../package.json';

const contents = `\

\

Landmarker.io
\

v${version}
\

\

\

Connect to Dropbox
\

\

\
            \

Connect to a landmarker server
\

\

\
            See a demo\

\

\
    \
        \
        More info on Github\
    \

\
`;

const lsWarning = `\

\
    Your browser doesn't support LocalStorage, so Dropbox login has been\
    disabled.\

`;

const httpsWarning = `\

\
    You are currently on an non-https connection. For security reasons Dropbox integration has been disabled.

`;

const mixedContentWarning = `

Your are currently trying to connect to a non secured server from a secure (https) connection. This is  unadvisable and thus we do not allow it.

You can visit insecure.landmarker.io to disable this warning.

`;

const Intro = Modal.extend({

    closable: false,
    modifiers: ['Small'],

    events: {
        'click .IntroItem--Dropbox': 'startDropbox',
        'click .IntroItem--Server': 'startServer',
        'click .IntroItem--Demo': 'startDemo'
    },

    init: function ({cfg}) {
        this._cfg = cfg;
    },

    content: function () {
        const $contents = $(contents);

        if (!support.localstorage) {
            $contents.find('.IntroItem--Dropbox').remove();
            $contents.find('.IntroItems').append($(lsWarning));
        }

        if (
            !support.https &&
            window.location.origin !== "http://localhost:4000"
        ) {
            $contents.find('.IntroItem--Dropbox').remove();
            $contents.find('.IntroItems').append($(httpsWarning));
        }

        return $contents;
    },

    _restart: function (serverUrl) {
        this._cfg.clear();
        const restartUrl = (
            baseUrl() + (serverUrl ? `?server=${serverUrl}` : '')
        );
        window.location.replace(restartUrl);
    },

    startDropbox: function () {
        this._cfg.clear();
        const [dropUrl, state] = Backend.Dropbox.authorize();
        this._cfg.set({
            'OAUTH_STATE': state,
            'BACKEND_TYPE': Backend.Dropbox.Type
        }, true);
        window.location.replace(dropUrl);
    },

    startDemo: function () {
        this._restart('demo');
    },

    startServer: function () {
        Modal.prompt('Where is your server located ?', (value) => {
            if (support.https && value.indexOf('https://') !== 0) {
                notify({
                    type: 'error',
                    msg: $(mixedContentWarning),
                    actions: [['Retry', this.open]]
                });
            } else {
                this._restart(value);
            }
        }, () => {
            this.open();
        });
    }
});

let instance;
export default {
    init: function (opts) { instance = new Intro(opts); },

    open: function () {
        instance._cfg.clear();
        history.replaceState(null, null, baseUrl());
        instance.open();
    },

    close: function () { instance.close(); },
    initialized: function () { return !!instance; }
};
<|endoftext|>


<commit_before>function __export(m) {
    for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
__export(require('./node_modules/ionic-angular/config/bootstrap'));
__export(require('./node_modules/ionic-angular/config/config'));
__export(require('./node_modules/ionic-angular/config/directives'));
__export(require('./node_modules/ionic-angular/decorators/app'));
__export(require('./node_modules/ionic-angular/decorators/page'));
__export(require('./node_modules/ionic-angular/components'));
__export(require('./node_modules/ionic-angular/platform/platform'));
__export(require('./node_modules/ionic-angular/platform/storage'));
__export(require('./node_modules/ionic-angular/util/click-block'));
__export(require('./node_modules/ionic-angular/util/events'));
__export(require('./node_modules/ionic-angular/util/keyboard'));
__export(require('./node_modules/ionic-angular/util/form'));
__export(require('./node_modules/ionic-angular/animations/animation'));
__export(require('./node_modules/ionic-angular/transitions/transition'));
__export(require('./node_modules/ionic-angular/translation/translate'));
__export(require('./node_modules/ionic-angular/translation/translate_pipe'));
// these modules don't export anything
require('./node_modules/ionic-angular/config/modes');
require('./node_modules/ionic-angular/platform/registry');
require('./node_modules/ionic-angular/animations/builtins');
require('./node_modules/ionic-angular/transitions/transition-ios');
require('./node_modules/ionic-angular/transitions/transition-md');
require('./node_modules/ionic-angular/transitions/transition-wp');
<commit_msg>Remove ionic-angular.js<commit_after><|endoftext|>


<commit_before>module.exports = function(env = {}) {
  /* eslint no-var:0, import/no-extraneous-dependencies:0 */
  var webpack = require("webpack");
  var ExtractTextPlugin = require("extract-text-webpack-plugin");
  var fs = require("fs");
  var path = require("path");
  const UglifyJsPlugin = require("uglifyjs-webpack-plugin");

  var srcPath = path.resolve(__dirname, "app/assets/javascripts/");
  var nodePath = path.join(__dirname, "node_modules/");

  fs.writeFileSync(path.join(__dirname, "target", "webpack.pid"), process.pid, "utf8");

  const plugins = [
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": env.production ? '"production"' : '"development"',
    }),
    new ExtractTextPlugin("main.css"),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery",
      _: "lodash",
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.optimize.CommonsChunkPlugin({
      name: "vendor",
      minChunks: function(module) {
        // this assumes your vendor imports exist in the node_modules directory
        return module.context && module.context.indexOf("node_modules") !== -1;
      },
    }),
    //CommonChunksPlugin will now extract all the common modules from vendor and main bundles
    new webpack.optimize.CommonsChunkPlugin({
      name: "manifest", //But since there are no more common modules between them we end up with just the runtime code included in the manifest file
    }),
  ];

  if (env.production) {
    plugins.push(
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: true,
        uglifyOptions: {
          compress: false,
        },
      }),
    );
  }

  return {
    entry: {
      main: "main.js",
    },
    output: {
      path: `${__dirname}/public/bundle`,
      filename: "[name].js",
      sourceMapFilename: "[file].map",
      publicPath: "/assets/bundle/",
      chunkFilename: env.production ? "[chunkhash].js" : "[name].js",
    },
    module: {
      // Reduce compilation time by telling webpack to not parse these libraries.
      // Only add libraries that have no dependencies eg. no require, define or similar calls.
      noParse: [/\/jquery\//],
      rules: [
        {
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: "babel-loader",
        },
        {
          test: /\.less$/,
          // This needs to be `loader` until `extract-text-webpack-plugin` is fixed
          // Ref: https://github.com/webpack/extract-text-webpack-plugin/issues/250
          use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: "css-loader!less-loader",
          }),
        },
        {
          test: /\.css$/,
          // This needs to be `loader` until `extract-text-webpack-plugin` is fixed
          // Ref: https://github.com/webpack/extract-text-webpack-plugin/issues/250
          use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: "css-loader!less-loader",
          }),
        },
        {
          test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          use: {
            loader: "url-loader",
            options: {
              limit: 10000,
              mimetype: "application/font-woff",
            },
          },
        },
        {
          test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          use: "file-loader",
        },
        { test: /\.png$/, use: { loader: "url-loader", options: { limit: 100000 } } },
        { test: /\.jpg$/, use: "file-loader" },
      ],
    },
    resolve: {
      modules: [srcPath, nodePath],
    },
    externals: [{ routes: "var jsRoutes" }],
    // See https://webpack.js.org/configuration/devtool/
    devtool: env.production ? "source-map" : "eval-source-map",
    plugins,
  };
};
<commit_msg>removed erronous comma from webpack config<commit_after>module.exports = function(env = {}) {
  /* eslint no-var:0, import/no-extraneous-dependencies:0 */
  var webpack = require("webpack");
  var ExtractTextPlugin = require("extract-text-webpack-plugin");
  var fs = require("fs");
  var path = require("path");
  const UglifyJsPlugin = require("uglifyjs-webpack-plugin");

  var srcPath = path.resolve(__dirname, "app/assets/javascripts/");
  var nodePath = path.join(__dirname, "node_modules/");

  fs.writeFileSync(path.join(__dirname, "target", "webpack.pid"), process.pid, "utf8");

  const plugins = [
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": env.production ? '"production"' : '"development"',
    }),
    new ExtractTextPlugin("main.css"),
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      "window.jQuery": "jquery",
      _: "lodash",
    }),
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
    new webpack.optimize.CommonsChunkPlugin({
      name: "vendor",
      minChunks: function(module) {
        // this assumes your vendor imports exist in the node_modules directory
        return module.context && module.context.indexOf("node_modules") !== -1;
      },
    }),
    // CommonChunksPlugin will now extract all the common modules from vendor and main bundles
    new webpack.optimize.CommonsChunkPlugin({
      name: "manifest", // But since there are no more common modules between them we end up with just the runtime code included in the manifest file
    }),
  ];

  if (env.production) {
    plugins.push(
      new UglifyJsPlugin({
        cache: true,
        parallel: true,
        sourceMap: true,
        uglifyOptions: {
          compress: false,
        },
      }),
    );
  }

  return {
    entry: {
      main: "main.js",
    },
    output: {
      path: `${__dirname}/public/bundle`,
      filename: "[name].js",
      sourceMapFilename: "[file].map",
      publicPath: "/assets/bundle/",
      chunkFilename: env.production ? "[chunkhash].js" : "[name].js",
    },
    module: {
      // Reduce compilation time by telling webpack to not parse these libraries.
      // Only add libraries that have no dependencies eg. no require, define or similar calls.
      noParse: [/\/jquery\//],
      rules: [
        {
          test: /\.js$/,
          exclude: /(node_modules|bower_components)/,
          use: "babel-loader",
        },
        {
          test: /\.less$/,
          // This needs to be `loader` until `extract-text-webpack-plugin` is fixed
          // Ref: https://github.com/webpack/extract-text-webpack-plugin/issues/250
          use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: "css-loader!less-loader",
          }),
        },
        {
          test: /\.css$/,
          // This needs to be `loader` until `extract-text-webpack-plugin` is fixed
          // Ref: https://github.com/webpack/extract-text-webpack-plugin/issues/250
          use: ExtractTextPlugin.extract({
            fallback: "style-loader",
            use: "css-loader!less-loader",
          }),
        },
        {
          test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          use: {
            loader: "url-loader",
            options: {
              limit: 10000,
              mimetype: "application/font-woff",
            },
          },
        },
        {
          test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
          use: "file-loader",
        },
        { test: /\.png$/, use: { loader: "url-loader", options: { limit: 100000 } } },
        { test: /\.jpg$/, use: "file-loader" },
      ],
    },
    resolve: {
      modules: [srcPath, nodePath],
    },
    externals: [{ routes: "var jsRoutes" }],
    // See https://webpack.js.org/configuration/devtool/
    devtool: env.production ? "source-map" : "eval-source-map",
    plugins,
  };
};
<|endoftext|>


<commit_before>(function(){
	"use strict";

	KC3StrategyTabs.shipdrop = new KC3StrategyTab("shipdrop");

	var exexe = {
		show_all : false ,
		world  :  0 ,
		subMap :  0 ,
		exe : function(){
				console.log("exexe" , this.world , this.subMap);
				let contentRoot = $(".tab_shipdrop .content_root");
				let factory = $(".tab_shipdrop .factory");
				let hq = PlayerManager.hq.id;
				let sorties37_1 = KC3Database.con.sortie.where("world").equals(this.world).and( data => data.mapnum === this.subMap && data.hq === hq);
				let dropTable = {};
				let pList = [];
				var self = this;
				sorties37_1.each( function(sortie) {
					let p = KC3Database.con.battle.where("sortie_id").equals(sortie.id).each( function(battle) {
						if (typeof dropTable[battle.node] === "undefined"){
							dropTable[battle.node] = {};
						}
						let tbl = dropTable[battle.node];
						if (typeof tbl[battle.drop] === "undefined") {
							tbl[battle.drop] = 0;
						}
						++ tbl[battle.drop];
					});
					pList.push(p);
				}).then( function() {
					Promise.all(pList).then( function() {
					let node_tot = {};
					$.each( dropTable, function(nodeNum, dropInfo) {
						let node = KC3Meta.nodeLetter(self.world,self.subMap,nodeNum);
						if(typeof node_tot[node] === "undefined") node_tot[node] = {};

						let keys = Object.keys( dropInfo );
						keys.sort( (ka,kb) => dropInfo[kb] - dropInfo[ka] );
						//handle the drop info
						$.each( keys, function(ind,mstId) {
							let count = dropInfo[mstId];
							let shipPanel = $(".ship", factory).clone();
							let name = KC3Master.ship(mstId).api_name || "<nothing>";
							if(mstId !== "0" && name != "<nothing>") {
								if(typeof node_tot[node][mstId] == "undefined") node_tot[node][mstId] = 0;
								node_tot[node][mstId] += count;
							}
							else {
								if(typeof node_tot[node][0] === "undefined") node_tot[node][0] = 0;
								node_tot[node][0] += count;
							}
						});
					});

					let keys_node = Object.keys( node_tot );
					keys_node.sort( (ka,kb) => ka - kb );
					$.each(keys_node , function(i , node) {
						var shipClickFunc = function(e){
							KC3StrategyTabs.gotoTab("mstship", $(this).attr("alt"));
						};
						console.log("Node: " + node);
						let nodeDrop = $(".node_drop", factory).clone();
						$(".node_name", nodeDrop).text( "Node: " + node);
						let keys_ship = Object.keys( node_tot[node] );
						keys_ship.sort( (ka,kb) => ka - kb );
						$.each(keys_ship , function(i , ship_id){
							console.log( ship_id , node_tot[node][ship_id]);
							let shipPanel = $(".ship", factory).clone();
							if (ship_id !== "0") {
								$("img", shipPanel).attr("src", KC3Meta.getIcon( ship_id ));
								$("img", shipPanel).addClass("hover");
								$("img", shipPanel).click(shipClickFunc);

							} else {
								$("img", shipPanel).attr("src", "../../assets/img/ui/dark_shipdrop-x.png");
							}
							$(".drop_times", shipPanel).text( "x" + node_tot[node][ship_id] );
							shipPanel.appendTo( nodeDrop );
						});
						nodeDrop.append( $('

') );
						nodeDrop.appendTo( contentRoot );
					});
				});
			});
		}
	}

	KC3StrategyTabs.shipdrop.definition = new KC3SortieLogs("shipdrop" , exexe);
})();
<commit_msg>add event map at drop_record in SR and add ship img link to ship information page<commit_after>(function(){
	"use strict";

	KC3StrategyTabs.shipdrop = new KC3StrategyTab("shipdrop");

	var exexe = {
		show_all : false ,
		world  :  0 ,
		subMap :  0 ,
		exe : function(){
				console.log("exexe" , this.world , this.subMap);
				let contentRoot = $(".tab_shipdrop .content_root");
				let factory = $(".tab_shipdrop .factory");
				let hq = PlayerManager.hq.id;
				let sorties37_1 = KC3Database.con.sortie.where("world").equals(this.world).and( data => data.mapnum === this.subMap && data.hq === hq);
				let dropTable = {};
				let pList = [];
				var self = this;
				sorties37_1.each( function(sortie) {
					let p = KC3Database.con.battle.where("sortie_id").equals(sortie.id).each( function(battle) {
						if (typeof dropTable[battle.node] === "undefined"){
							dropTable[battle.node] = {};
						}
						let tbl = dropTable[battle.node];
						if (typeof tbl[battle.drop] === "undefined") {
							tbl[battle.drop] = 0;
						}
						++ tbl[battle.drop];
					});
					pList.push(p);
				}).then( function() {
					Promise.all(pList).then( function() {
					let node_tot = {};
					$.each( dropTable, function(nodeNum, dropInfo) {
						let node = KC3Meta.nodeLetter(self.world,self.subMap,nodeNum);
						if(typeof node_tot[node] === "undefined") node_tot[node] = {};

						let keys = Object.keys( dropInfo );
						keys.sort( (ka,kb) => dropInfo[kb] - dropInfo[ka] );
						//handle the drop info
						$.each( keys, function(ind,mstId) {
							let count = dropInfo[mstId];
							let shipPanel = $(".ship", factory).clone();
							let name = KC3Master.ship(mstId).api_name || "<nothing>";
							if(mstId !== "0" && name != "<nothing>") {
								if(typeof node_tot[node][mstId] == "undefined") node_tot[node][mstId] = 0;
								node_tot[node][mstId] += count;
							}
							else {
								if(typeof node_tot[node][0] === "undefined") node_tot[node][0] = 0;
								node_tot[node][0] += count;
							}
						});
					});

					let keys_node = Object.keys( node_tot );
					keys_node.sort( (ka,kb) => ka - kb );
					$.each(keys_node , function(i , node) {
						var shipClickFunc = function(e){
							KC3StrategyTabs.gotoTab("mstship", $(this).attr("alt"));
						};
						console.log("Node: " + node);
						let nodeDrop = $(".node_drop", factory).clone();
						$(".node_name", nodeDrop).text( "Node: " + node);
						let keys_ship = Object.keys( node_tot[node] );
						keys_ship.sort( (ka,kb) => ka - kb );
						$.each(keys_ship , function(i , ship_id){
							console.log( ship_id , node_tot[node][ship_id]);
							let shipPanel = $(".ship", factory).clone();
							if (ship_id !== "0") {
								$("img", shipPanel).attr("src", KC3Meta.getIcon( ship_id ));
								$("img", shipPanel).addClass("hover");
								$("img", shipPanel).click(shipClickFunc);

							} else {
								$("img", shipPanel).attr("src", "../../assets/img/ui/dark_shipdrop-x.png");
							}
							$(".drop_times", shipPanel).text( "x" + node_tot[node][ship_id] );
							shipPanel.appendTo( nodeDrop );
						});
						nodeDrop.append( $('

') );
						nodeDrop.appendTo( contentRoot );
					});
				});
			});
		}
	};

	KC3StrategyTabs.shipdrop.definition = new KC3SortieLogs("shipdrop" , exexe);
})();
<|endoftext|>


<commit_before>( function() {
    "use strict";

    var app = angular.module('entityReferenceApp', ['sky', 'ui.bootstrap', 'LocalStorageModule']);

    app.controller('EntityReferenceCtrl', ['$window', '$http', '$sce', '$timeout', 'bbWait', 'localStorageService', '$rootScope', EntityReferenceCtrl]);

    app.component('bbEntityReference', {
        templateUrl: '/assets/views/entities.html',
        controller: 'EntityReferenceCtrl as ctrl',
        bindings: {
            apiTitle: '@',
            lastUpdatedDate: '@',
            getStartedUrl: '@',
            swaggerUrl: '@',
            swaggerUrlDev: '@',
            whiteList: '@',
            blackList: '@',
            showDescriptions: '@'
        }
    });

    function EntityReferenceCtrl($window, $http, $sce, $timeout, bbWait, localStorageService, $rootScope) {
        var self = this;
        this.showErrorMessage = false;

        if (this.showDescriptions == null)
        {
            // default showDescriptions to false, since not all APIs have user friendly descriptions
            this.showDescriptions = false;
        }
        this.$onInit = onInit;

        function onInit() {
            var isDev = window.location.search.toString().toLowerCase().indexOf('ENV=DEV') >= 0 && self.swaggerUrlDev;
            this.swaggerCacheName = 'swaggerResponseCache-' + (isDev ? 'DEV-' : '') + this.apiTitle;
            var swaggerResponseCache = localStorageService.get(self.swaggerCacheName);
            bbWait.beginPageWait({});

            // Get a new swagger response if one is not cached or the cache has expired
            if (!swaggerResponseCache || Date.now() >= swaggerResponseCache.expirationDate) {
              $http.get(isDev ? self.swaggerUrlDev : self.swaggerUrl)
                  .then(handleSuccess, handleError)
                  .finally(function() { bbWait.endPageWait(); });
            }
            else {
              handleSwaggerResponseData(swaggerResponseCache.swaggerResponseData);
              bbWait.endPageWait();
            }
        }

        function handleSuccess(response) {
            // Represents the number of hours until the cache expires
            var swaggerCacheHourLimit = 12;

            localStorageService.set(self.swaggerCacheName, {
              'swaggerResponseData': response.data,
              'expirationDate': Date.now() + (swaggerCacheHourLimit * 36e5)
            });
            handleSwaggerResponseData(response.data);
        }

        function handleSwaggerResponseData(swagger) {
            self.swagger = swagger;
            var whiteList = self.whiteList ? self.whiteList.split(',') : [];
            var blackList = self.blackList ? self.blackList.split(',') : [];
            self.entities = getEntitiesFromSwagger(swagger, whiteList, blackList);

            // Need to delay allowing digest cycle to run and additionally
            // give a little extra time to prevent rescrolling back to top due to
            // angular loading sequence.
            return $timeout(function() {
              scrollToHash();
            });
        }

        $rootScope.$on('$locationChangeSuccess', function (event, newUrl, oldUrl) {
            scrollToHash();
        });

        function handleError(response) {
            self.showErrorMessage = true;
        }

        function getEntitiesFromSwagger(swagger, whiteList, blackList) {
            return Object.keys(swagger.definitions)
                .sort(function(a, b) {
                    var keyA = getRefDisplayName(a, swagger.definitions);
                    var keyB = getRefDisplayName(b, swagger.definitions);

                    if (keyA < keyB) {
                        return -1;
                    }

                    if (keyA > keyB) {
                        return 1;
                    }

                    // keys are equal (shouldn't happen in our swagger)
                    return 0;
                })
                .map(function(name) {
                    var definition = swagger.definitions[name];
                    return {
                        name: name,
                        displayName: definition['x-display-name'] || name,
                        displayId: definition['x-display-id'] || name,
                        details: definition,
                        description: self.showDescriptions ? definition.description : null,
                        additionalInfoHtml: $sce.trustAsHtml(definition['x-additional-info'])
                    };
                })
                .filter(function(entity) {
                    if (whiteList.length > 0) {
                        return whiteList.find(function(name) {
                            return entity.name == name;
                        });
                    }
                    if (blackList.length > 0) {
                        return !blackList.find(function(name) {
                            return entity.name == name;
                        });
                    }
                    return !!entity.details.properties && !entity.details['x-hidden'];
                })
                .map(function(entity)
                {
                    return setDisplayTypesOnEntity(entity, swagger.definitions);
                });
        }

        function setDisplayTypesOnEntity(entity, definitions) {
            Object.keys(entity.details.properties).forEach(function(propertyName) {
                var property = entity.details.properties[propertyName];
                property.isArray = (property.type === "array");

                if (property.isArray) {
                    property.ref = (property.items.$ref && property.items.$ref.replace("#/definitions/", ""));
                    property.displayType = getRefDisplayName(property.ref, definitions) || getTypeFormattedName(property);
                    property.displayId = getRefDisplayId(property.ref, definitions) || getTypeFormattedName(property);
                } else {
                    property.ref = property.$ref && property.$ref.replace("#/definitions/", "");
                    property.displayType = getRefDisplayName(property.ref, definitions) || getTypeFormattedName(property);
                    property.displayId = getRefDisplayId(property.ref, definitions) || getTypeFormattedName(property);
                }

                property.descriptionHtml = $sce.trustAsHtml(property.description);
            });
            return entity;
        }

        function getRefDisplayName(ref, definitions) {
            if (ref) {
                return (definitions[ref]['x-display-name'] || ref).toLowerCase();
            }
        }

        function getRefDisplayId(ref, definitions) {
            if (ref) {
                return (definitions[ref]['x-display-id'] || ref);
            }
        }

        function getTypeFormattedName(property) {

            // Conversion table for swagger format to display text.
            var formatDisplayNames = {
                'date-time': 'dateTime'
            };

            if (property.format) {
                return formatDisplayNames[property.format] || property.type;
            } else {
                return property.type;
            }
        }

        function scrollToHash() {
            // Cannot use $location with anchors or links will be broken without html5Mode.
            // Cannot $autoScroll due to it requiring $location without html5Mode.
            // Cannot enable html5Mode or external links will be broken.

            // Unfortunately, this means we need to manually scroll window to element.
            // See https://github.com/angular/angular.js/issues/114

            var document = $window.document;
            var hash = getHash($window.location);

            var elem = document.getElementsByName(hash)[0];

            if (elem) {
                elem.scrollIntoView();
            } else {
                $window.scrollTo(0, 0);
            }
        }

        function getHash(location) {
            var hash = location.hash || '';
            var index = hash.indexOf('#!#'); // This was indexOf('#') before the angular 1.6 upgrade.
            return index === -1 ? hash : hash.substr(index+3); // This was +1 before 1.6. If we do something to remove the #! prefix, change this back
        }
    }
})();
<commit_msg>fixed the loading of dev swagger when flag supplied<commit_after>( function() {
    "use strict";

    var app = angular.module('entityReferenceApp', ['sky', 'ui.bootstrap', 'LocalStorageModule']);

    app.controller('EntityReferenceCtrl', ['$window', '$http', '$sce', '$timeout', 'bbWait', 'localStorageService', '$rootScope', EntityReferenceCtrl]);

    app.component('bbEntityReference', {
        templateUrl: '/assets/views/entities.html',
        controller: 'EntityReferenceCtrl as ctrl',
        bindings: {
            apiTitle: '@',
            lastUpdatedDate: '@',
            getStartedUrl: '@',
            swaggerUrl: '@',
            swaggerUrlDev: '@',
            whiteList: '@',
            blackList: '@',
            showDescriptions: '@'
        }
    });

    function EntityReferenceCtrl($window, $http, $sce, $timeout, bbWait, localStorageService, $rootScope) {
        var self = this;
        this.showErrorMessage = false;

        if (this.showDescriptions == null)
        {
            // default showDescriptions to false, since not all APIs have user friendly descriptions
            this.showDescriptions = false;
        }
        this.$onInit = onInit;

        function onInit() {
            var isDev = window.location.search.toString().toLowerCase().indexOf('env=dev') >= 0 && self.swaggerUrlDev;
            this.swaggerCacheName = 'swaggerResponseCache-' + (isDev ? 'DEV-' : '') + this.apiTitle;
            var swaggerResponseCache = localStorageService.get(self.swaggerCacheName);
            bbWait.beginPageWait({});

            // Get a new swagger response if one is not cached or the cache has expired
            if (!swaggerResponseCache || Date.now() >= swaggerResponseCache.expirationDate) {
              $http.get(isDev ? self.swaggerUrlDev : self.swaggerUrl)
                  .then(handleSuccess, handleError)
                  .finally(function() { bbWait.endPageWait(); });
            }
            else {
              handleSwaggerResponseData(swaggerResponseCache.swaggerResponseData);
              bbWait.endPageWait();
            }
        }

        function handleSuccess(response) {
            // Represents the number of hours until the cache expires
            var swaggerCacheHourLimit = 12;

            localStorageService.set(self.swaggerCacheName, {
              'swaggerResponseData': response.data,
              'expirationDate': Date.now() + (swaggerCacheHourLimit * 36e5)
            });
            handleSwaggerResponseData(response.data);
        }

        function handleSwaggerResponseData(swagger) {
            self.swagger = swagger;
            var whiteList = self.whiteList ? self.whiteList.split(',') : [];
            var blackList = self.blackList ? self.blackList.split(',') : [];
            self.entities = getEntitiesFromSwagger(swagger, whiteList, blackList);

            // Need to delay allowing digest cycle to run and additionally
            // give a little extra time to prevent rescrolling back to top due to
            // angular loading sequence.
            return $timeout(function() {
              scrollToHash();
            });
        }

        $rootScope.$on('$locationChangeSuccess', function (event, newUrl, oldUrl) {
            scrollToHash();
        });

        function handleError(response) {
            self.showErrorMessage = true;
        }

        function getEntitiesFromSwagger(swagger, whiteList, blackList) {
            return Object.keys(swagger.definitions)
                .sort(function(a, b) {
                    var keyA = getRefDisplayName(a, swagger.definitions);
                    var keyB = getRefDisplayName(b, swagger.definitions);

                    if (keyA < keyB) {
                        return -1;
                    }

                    if (keyA > keyB) {
                        return 1;
                    }

                    // keys are equal (shouldn't happen in our swagger)
                    return 0;
                })
                .map(function(name) {
                    var definition = swagger.definitions[name];
                    return {
                        name: name,
                        displayName: definition['x-display-name'] || name,
                        displayId: definition['x-display-id'] || name,
                        details: definition,
                        description: self.showDescriptions ? definition.description : null,
                        additionalInfoHtml: $sce.trustAsHtml(definition['x-additional-info'])
                    };
                })
                .filter(function(entity) {
                    if (whiteList.length > 0) {
                        return whiteList.find(function(name) {
                            return entity.name == name;
                        });
                    }
                    if (blackList.length > 0) {
                        return !blackList.find(function(name) {
                            return entity.name == name;
                        });
                    }
                    return !!entity.details.properties && !entity.details['x-hidden'];
                })
                .map(function(entity)
                {
                    return setDisplayTypesOnEntity(entity, swagger.definitions);
                });
        }

        function setDisplayTypesOnEntity(entity, definitions) {
            Object.keys(entity.details.properties).forEach(function(propertyName) {
                var property = entity.details.properties[propertyName];
                property.isArray = (property.type === "array");

                if (property.isArray) {
                    property.ref = (property.items.$ref && property.items.$ref.replace("#/definitions/", ""));
                    property.displayType = getRefDisplayName(property.ref, definitions) || getTypeFormattedName(property);
                    property.displayId = getRefDisplayId(property.ref, definitions) || getTypeFormattedName(property);
                } else {
                    property.ref = property.$ref && property.$ref.replace("#/definitions/", "");
                    property.displayType = getRefDisplayName(property.ref, definitions) || getTypeFormattedName(property);
                    property.displayId = getRefDisplayId(property.ref, definitions) || getTypeFormattedName(property);
                }

                property.descriptionHtml = $sce.trustAsHtml(property.description);
            });
            return entity;
        }

        function getRefDisplayName(ref, definitions) {
            if (ref) {
                return (definitions[ref]['x-display-name'] || ref).toLowerCase();
            }
        }

        function getRefDisplayId(ref, definitions) {
            if (ref) {
                return (definitions[ref]['x-display-id'] || ref);
            }
        }

        function getTypeFormattedName(property) {

            // Conversion table for swagger format to display text.
            var formatDisplayNames = {
                'date-time': 'dateTime'
            };

            if (property.format) {
                return formatDisplayNames[property.format] || property.type;
            } else {
                return property.type;
            }
        }

        function scrollToHash() {
            // Cannot use $location with anchors or links will be broken without html5Mode.
            // Cannot $autoScroll due to it requiring $location without html5Mode.
            // Cannot enable html5Mode or external links will be broken.

            // Unfortunately, this means we need to manually scroll window to element.
            // See https://github.com/angular/angular.js/issues/114

            var document = $window.document;
            var hash = getHash($window.location);

            var elem = document.getElementsByName(hash)[0];

            if (elem) {
                elem.scrollIntoView();
            } else {
                $window.scrollTo(0, 0);
            }
        }

        function getHash(location) {
            var hash = location.hash || '';
            var index = hash.indexOf('#!#'); // This was indexOf('#') before the angular 1.6 upgrade.
            return index === -1 ? hash : hash.substr(index+3); // This was +1 before 1.6. If we do something to remove the #! prefix, change this back
        }
    }
})();
<|endoftext|>


<commit_before>'use strict';

// this module

module.exports = {
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel' }
    ]
  },
  output: {
    library: 'isDOM4Supported',
    libraryTarget: 'umd'
  }
};
<commit_msg>webpack: minify output<commit_after>'use strict';

// foreign modules

var webpack = require('webpack');

// this module

module.exports = {
  module: {
    loaders: [
      { test: /\.js$/, loader: 'babel' }
    ]
  },
  output: {
    library: 'isDOM4Supported',
    libraryTarget: 'umd'
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({minimize: true})
  ]
};
<|endoftext|>


<commit_before>(function(UI) {

    "use strict";

    var scrollpos = {x: window.scrollX, y: window.scrollY},
        $win      = UI.$win,
        $doc      = UI.$doc,
        $html     = UI.$html,
        Offcanvas = {

        show: function(element) {

            element = UI.$(element);

            if (!element.length) return;

            var $body     = UI.$('body'),
                bar       = element.find(".uk-offcanvas-bar:first"),
                rtl       = (UI.langdirection == "right"),
                flip      = bar.hasClass("uk-offcanvas-bar-flip") ? -1:1,
                dir       = flip * (rtl ? -1 : 1);

            scrollpos = {x: window.pageXOffset, y: window.pageYOffset};

            element.addClass("uk-active");

            $body.css({"width": window.innerWidth, "height": window.innerHeight}).addClass("uk-offcanvas-page");
            $body.css((rtl ? "margin-right" : "margin-left"), (rtl ? -1 : 1) * (bar.outerWidth() * dir)).width(); // .width() - force redraw

            $html.css('margin-top', scrollpos.y * -1);

            bar.addClass("uk-offcanvas-bar-show");

            this._initElement(element);

            $doc.trigger('show.uk.offcanvas', [element, bar]);

            // Update ARIA
            element.attr('aria-hidden', 'false');
        },

        hide: function(force) {

            var $body = UI.$('body'),
                panel = UI.$(".uk-offcanvas.uk-active"),
                rtl   = (UI.langdirection == "right"),
                bar   = panel.find(".uk-offcanvas-bar:first"),
                finalize = function() {
                    $body.removeClass("uk-offcanvas-page").css({"width": "", "height": "", "margin-left": "", "margin-right": ""});
                    panel.removeClass("uk-active");

                    bar.removeClass("uk-offcanvas-bar-show");
                    $html.css('margin-top', '');
                    window.scrollTo(scrollpos.x, scrollpos.y);
                    UI.$doc.trigger('hide.uk.offcanvas', [panel, bar]);

                    // Update ARIA
                    panel.attr('aria-hidden', 'true');
                };

            if (!panel.length) return;

            if (UI.support.transition && !force) {

                $body.one(UI.support.transition.end, function() {
                    finalize();
                }).css((rtl ? "margin-right" : "margin-left"), "");

                setTimeout(function(){
                    bar.removeClass("uk-offcanvas-bar-show");
                }, 0);

            } else {
                finalize();
            }
        },

        _initElement: function(element) {

            if (element.data("OffcanvasInit")) return;

            element.on("click.uk.offcanvas swipeRight.uk.offcanvas swipeLeft.uk.offcanvas", function(e) {

                var target = UI.$(e.target);

                if (!e.type.match(/swipe/)) {

                    if (!target.hasClass("uk-offcanvas-close")) {
                        if (target.hasClass("uk-offcanvas-bar")) return;
                        if (target.parents(".uk-offcanvas-bar:first").length) return;
                    }
                }

                e.stopImmediatePropagation();
                Offcanvas.hide();
            });

            element.on("click", "a[href^='#']", function(e){

                var element = UI.$(this),
                    href = element.attr("href");

                if (href == "#") {
                    return;
                }

                UI.$doc.one('hide.uk.offcanvas', function() {

                    var target = UI.$(href);

                    if (!target.length) {
                        target = UI.$('[name="'+href.replace('#','')+'"]');
                    }

                    if (UI.Utils.scrollToElement && target.length) {
                        UI.Utils.scrollToElement(target);
                    } else {
                        window.location.href = href;
                    }
                });

                Offcanvas.hide();
            });

            element.data("OffcanvasInit", true);
        }
    };

    UI.component('offcanvasTrigger', {

        boot: function() {

            // init code
            $html.on("click.offcanvas.uikit", "[data-uk-offcanvas]", function(e) {

                e.preventDefault();

                var ele = UI.$(this);

                if (!ele.data("offcanvasTrigger")) {
                    var obj = UI.offcanvasTrigger(ele, UI.Utils.options(ele.attr("data-uk-offcanvas")));
                    ele.trigger("click");
                }
            });

            $html.on('keydown.uk.offcanvas', function(e) {

                if (e.keyCode === 27) { // ESC
                    Offcanvas.hide();
                }
            });
        },

        init: function() {

            var $this = this;

            this.options = UI.$.extend({
                "target": $this.element.is("a") ? $this.element.attr("href") : false
            }, this.options);

            this.on("click", function(e) {
                e.preventDefault();
                Offcanvas.show($this.options.target);
            });
        }
    });

    UI.offcanvas = Offcanvas;

})(UIkit);
<commit_msg>cleanup<commit_after>(function(UI) {

    "use strict";

    var scrollpos = {x: window.scrollX, y: window.scrollY},
        $win      = UI.$win,
        $doc      = UI.$doc,
        $html     = UI.$html,
        Offcanvas = {

        show: function(element) {

            element = UI.$(element);

            if (!element.length) return;

            var $body     = UI.$('body'),
                bar       = element.find(".uk-offcanvas-bar:first"),
                rtl       = (UI.langdirection == "right"),
                flip      = bar.hasClass("uk-offcanvas-bar-flip") ? -1:1,
                dir       = flip * (rtl ? -1 : 1);

            scrollpos = {x: window.pageXOffset, y: window.pageYOffset};

            element.addClass("uk-active");

            $body.css({"width": window.innerWidth, "height": window.innerHeight}).addClass("uk-offcanvas-page");
            $body.css((rtl ? "margin-right" : "margin-left"), (rtl ? -1 : 1) * (bar.outerWidth() * dir)).width(); // .width() - force redraw

            $html.css('margin-top', scrollpos.y * -1);

            bar.addClass("uk-offcanvas-bar-show");

            this._initElement(element);

            $doc.trigger('show.uk.offcanvas', [element, bar]);

            // Update ARIA
            element.attr('aria-hidden', 'false');
        },

        hide: function(force) {

            var $body = UI.$('body'),
                panel = UI.$(".uk-offcanvas.uk-active"),
                rtl   = (UI.langdirection == "right"),
                bar   = panel.find(".uk-offcanvas-bar:first"),
                finalize = function() {
                    $body.removeClass("uk-offcanvas-page").css({"width": "", "height": "", "margin-left": "", "margin-right": ""});
                    panel.removeClass("uk-active");

                    bar.removeClass("uk-offcanvas-bar-show");
                    $html.css('margin-top', '');
                    window.scrollTo(scrollpos.x, scrollpos.y);
                    UI.$doc.trigger('hide.uk.offcanvas', [panel, bar]);

                    // Update ARIA
                    panel.attr('aria-hidden', 'true');
                };

            if (!panel.length) return;

            if (UI.support.transition && !force) {

                $body.one(UI.support.transition.end, function() {
                    finalize();
                }).css((rtl ? "margin-right" : "margin-left"), "");

                setTimeout(function(){
                    bar.removeClass("uk-offcanvas-bar-show");
                }, 0);

            } else {
                finalize();
            }
        },

        _initElement: function(element) {

            if (element.data("OffcanvasInit")) return;

            element.on("click.uk.offcanvas swipeRight.uk.offcanvas swipeLeft.uk.offcanvas", function(e) {

                var target = UI.$(e.target);

                if (!e.type.match(/swipe/)) {

                    if (!target.hasClass("uk-offcanvas-close")) {
                        if (target.hasClass("uk-offcanvas-bar")) return;
                        if (target.parents(".uk-offcanvas-bar:first").length) return;
                    }
                }

                e.stopImmediatePropagation();
                Offcanvas.hide();
            });

            element.on("click", "a[href^='#']", function(e){

                var element = UI.$(this),
                    href = element.attr("href");

                if (href == "#") {
                    return;
                }

                UI.$doc.one('hide.uk.offcanvas', function() {

                    var target = UI.$(href);

                    if (!target.length) {
                        target = UI.$('[name="'+href.replace('#','')+'"]');
                    }

                    if (UI.Utils.scrollToElement && target.length) {
                        UI.Utils.scrollToElement(target);
                    } else {
                        window.location.href = href;
                    }
                });

                Offcanvas.hide();
            });

            element.data("OffcanvasInit", true);
        }
    };

    UI.component('offcanvasTrigger', {

        boot: function() {

            // init code
            $html.on("click.offcanvas.uikit", "[data-uk-offcanvas]", function(e) {

                e.preventDefault();

                var ele = UI.$(this);

                if (!ele.data("offcanvasTrigger")) {
                    var obj = UI.offcanvasTrigger(ele, UI.Utils.options(ele.attr("data-uk-offcanvas")));
                    ele.trigger("click");
                }
            });

            $html.on('keydown.uk.offcanvas', function(e) {

                if (e.keyCode === 27) { // ESC
                    Offcanvas.hide();
                }
            });
        },

        init: function() {

            var $this = this;

            this.options = UI.$.extend({
                "target": $this.element.is("a") ? $this.element.attr("href") : false
            }, this.options);

            this.on("click", function(e) {
                e.preventDefault();
                Offcanvas.show($this.options.target);
            });
        }
    });

    UI.offcanvas = Offcanvas;

})(UIkit);
<|endoftext|>


<commit_before>var BundleTracker = require('webpack-bundle-tracker'),
    MiniCssExtractPlugin = require('mini-css-extract-plugin'),
    path = require('path'),
    webpack = require('webpack'),
    loaders = [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
            loader: 'sass-loader',
            options: {
                sassOptions: {
                    includePaths: [path.resolve('./sass/')]
                }
            }
        }
    ],
    context = path.join(__dirname, 'course_discovery/static');

module.exports = {
    context: context,

    entry: {
        'query-preview': './js/query-preview.js',
        'course-skills-admin': './js/course-skills-admin.js',
        'query-preview.style': './sass/query-preview.scss'
    },

    output: {
        path: path.join(context, './bundles/'),
        filename: '[name]-[hash].js'
    },

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        }),
        new MiniCssExtractPlugin({filename: '[name]-[hash].css'})
    ],

    module: {
        rules: [
            {
                test: /\.s?css$/,
                use: loaders
            },
            {
                test: /\.woff2?$/,
                // Inline small woff files and output them below font
                use: [{
                    loader: 'url-loader',
                    options: {
                        name: 'font/[name]-[hash].[ext]',
                        limit: 5000,
                        mimetype: 'application/font-woff'
                    }
                }]
            },
            {
                test: /\.(ttf|eot|svg)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: 'font/[name]-[hash].[ext]'
                    }
                }]
            },
            {
                test: require.resolve('datatables.net'),
                use: 'imports-loader?define=>false'
            },
            {
                test: require.resolve('datatables.net-bs'),
                use: 'imports-loader?define=>false'
            }
        ]
    },
    resolve: {
        modules: ['node_modules'],
        extensions: ['.css', '.js', '.scss']
    }
};
<commit_msg>fix: publicPath for css and js files<commit_after>var BundleTracker = require('webpack-bundle-tracker'),
    MiniCssExtractPlugin = require('mini-css-extract-plugin'),
    path = require('path'),
    webpack = require('webpack'),
    loaders = [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
            loader: 'sass-loader',
            options: {
                sassOptions: {
                    includePaths: [path.resolve('./sass/')]
                }
            }
        }
    ],
    context = path.join(__dirname, 'course_discovery/static');

module.exports = {
    context: context,

    entry: {
        'query-preview': './js/query-preview.js',
        'course-skills-admin': './js/course-skills-admin.js',
        'query-preview.style': './sass/query-preview.scss'
    },

    output: {
        path: path.join(context, './bundles/'),
        filename: '[name]-[hash].js',
        publicPath: ''
    },

    plugins: [
        new BundleTracker({filename: './webpack-stats.json'}),
        new webpack.ProvidePlugin({
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        }),
        new MiniCssExtractPlugin({filename: '[name]-[hash].css'})
    ],

    module: {
        rules: [
            {
                test: /\.s?css$/,
                use: loaders
            },
            {
                test: /\.woff2?$/,
                // Inline small woff files and output them below font
                use: [{
                    loader: 'url-loader',
                    options: {
                        name: 'font/[name]-[hash].[ext]',
                        limit: 5000,
                        mimetype: 'application/font-woff'
                    }
                }]
            },
            {
                test: /\.(ttf|eot|svg)$/,
                use: [{
                    loader: 'file-loader',
                    options: {
                        name: 'font/[name]-[hash].[ext]'
                    }
                }]
            },
            {
                test: require.resolve('datatables.net'),
                use: 'imports-loader?define=>false'
            },
            {
                test: require.resolve('datatables.net-bs'),
                use: 'imports-loader?define=>false'
            }
        ]
    },
    resolve: {
        modules: ['node_modules'],
        extensions: ['.css', '.js', '.scss']
    }
};
<|endoftext|>