<commit_before>/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');
var Plotly = require('../plotly');
var Registry = require('../registry');
var Plots = require('../plots/plots');
var Lib = require('../lib');

var Color = require('../components/color');
var Drawing = require('../components/drawing');
var Titles = require('../components/titles');
var ModeBar = require('../components/modebar');
var initInteractions = require('../plots/cartesian/graph_interact');

exports.layoutStyles = function(gd) {
    return Lib.syncOrAsync([Plots.doAutoMargin, exports.lsInner], gd);
};

function overlappingDomain(xDomain, yDomain, domains) {
    for(var i = 0; i < domains.length; i++) {
        var existingX = domains[i][0],
            existingY = domains[i][1];

        if(existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) {
            continue;
        }
        if(existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) {
            return true;
        }
    }
    return false;
}

exports.lsInner = function(gd) {
    var fullLayout = gd._fullLayout,
        gs = fullLayout._size,
        axList = Plotly.Axes.list(gd),
        i;

    // clear axis line positions, to be set in the subplot loop below
    for(i = 0; i < axList.length; i++) axList[i]._linepositions = {};

    fullLayout._paperdiv
        .style({
            width: fullLayout.width + 'px',
            height: fullLayout.height + 'px'
        })
        .selectAll('.main-svg')
            .call(Drawing.setSize, fullLayout.width, fullLayout.height);

    gd._context.setBackground(gd, fullLayout.paper_bgcolor);

    var subplotSelection = fullLayout._paper.selectAll('g.subplot');

    // figure out which backgrounds we need to draw, and in which layers
    // to put them
    var lowerBackgroundIDs = [];
    var lowerDomains = [];
    subplotSelection.each(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];

        if(plotinfo.mainplot) {
            // mainplot is a reference to the main plot this one is overlaid on
            // so if it exists, this is an overlaid plot and we don't need to
            // give it its own background
            if(plotinfo.bg) {
                plotinfo.bg.remove();
            }
            plotinfo.bg = undefined;
            return;
        }

        var xa = Plotly.Axes.getFromId(gd, subplot, 'x'),
            ya = Plotly.Axes.getFromId(gd, subplot, 'y'),
            xDomain = xa.domain,
            yDomain = ya.domain,
            plotgroupBgData = [];

        if(overlappingDomain(xDomain, yDomain, lowerDomains)) {
            plotgroupBgData = [0];
        }
        else {
            lowerBackgroundIDs.push(subplot);
            lowerDomains.push([xDomain, yDomain]);
        }

        // create the plot group backgrounds now, since
        // they're all independent selections
        var plotgroupBg = plotinfo.plotgroup.selectAll('.bg')
            .data(plotgroupBgData);

        plotgroupBg.enter().append('rect')
            .classed('bg', true);

        plotgroupBg.exit().remove();

        plotgroupBg.each(function() {
            plotinfo.bg = plotgroupBg;
            var pgNode = plotinfo.plotgroup.node();
            pgNode.insertBefore(this, pgNode.childNodes[0]);
        });
    });

    // now create all the lower-layer backgrounds at once now that
    // we have the list of subplots that need them
    var lowerBackgrounds = fullLayout._bgLayer.selectAll('.bg')
        .data(lowerBackgroundIDs);

    lowerBackgrounds.enter().append('rect')
        .classed('bg', true);

    lowerBackgrounds.exit().remove();

    lowerBackgrounds.each(function(subplot) {
        fullLayout._plots[subplot].bg = d3.select(this);
    });

    var freefinished = [];
    subplotSelection.each(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];

        var xa = Plotly.Axes.getFromId(gd, subplot, 'x'),
            ya = Plotly.Axes.getFromId(gd, subplot, 'y');

        // reset scale in case the margins have changed
        xa.setScale();
        ya.setScale();

        if(plotinfo.bg && fullLayout._has('cartesian')) {
            plotinfo.bg
                .call(Drawing.setRect,
                    xa._offset - gs.p, ya._offset - gs.p,
                    xa._length + 2 * gs.p, ya._length + 2 * gs.p)
                .call(Color.fill, fullLayout.plot_bgcolor)
                .style('stroke-width', 0);
        }

        // Clip so that data only shows up on the plot area.
        plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot';

        var plotClip = fullLayout._defs.selectAll('g.clips')
            .selectAll('#' + plotinfo.clipId)
            .data([0]);

        plotClip.enter().append('clipPath')
            .attr({
                'class': 'plotclip',
                'id': plotinfo.clipId
            })
            .append('rect');

        plotClip.selectAll('rect')
            .attr({
                'width': xa._length,
                'height': ya._length
            });

        plotinfo.plot.call(Drawing.setTranslate, xa._offset, ya._offset);
        plotinfo.plot.call(Drawing.setClipUrl, plotinfo.clipId);

        var xlw = Drawing.crispRound(gd, xa.linewidth, 1),
            ylw = Drawing.crispRound(gd, ya.linewidth, 1),
            xp = gs.p + ylw,
            xpathPrefix = 'M' + (-xp) + ',',
            xpathSuffix = 'h' + (xa._length + 2 * xp),
            showfreex = xa.anchor === 'free' &&
                freefinished.indexOf(xa._id) === -1,
            freeposx = gs.h * (1 - (xa.position||0)) + ((xlw / 2) % 1),
            showbottom =
                (xa.anchor === ya._id && (xa.mirror || xa.side !== 'top')) ||
                xa.mirror === 'all' || xa.mirror === 'allticks' ||
                (xa.mirrors && xa.mirrors[ya._id + 'bottom']),
            bottompos = ya._length + gs.p + xlw / 2,
            showtop =
                (xa.anchor === ya._id && (xa.mirror || xa.side === 'top')) ||
                xa.mirror === 'all' || xa.mirror === 'allticks' ||
                (xa.mirrors && xa.mirrors[ya._id + 'top']),
            toppos = -gs.p - xlw / 2,

            // shorten y axis lines so they don't overlap x axis lines
            yp = gs.p,
            // except where there's no x line
            // TODO: this gets more complicated with multiple x and y axes
            ypbottom = showbottom ? 0 : xlw,
            yptop = showtop ? 0 : xlw,
            ypathSuffix = ',' + (-yp - yptop) +
                'v' + (ya._length + 2 * yp + yptop + ypbottom),
            showfreey = ya.anchor === 'free' &&
                freefinished.indexOf(ya._id) === -1,
            freeposy = gs.w * (ya.position||0) + ((ylw / 2) % 1),
            showleft =
                (ya.anchor === xa._id && (ya.mirror || ya.side !== 'right')) ||
                ya.mirror === 'all' || ya.mirror === 'allticks' ||
                (ya.mirrors && ya.mirrors[xa._id + 'left']),
            leftpos = -gs.p - ylw / 2,
            showright =
                (ya.anchor === xa._id && (ya.mirror || ya.side === 'right')) ||
                ya.mirror === 'all' || ya.mirror === 'allticks' ||
                (ya.mirrors && ya.mirrors[xa._id + 'right']),
            rightpos = xa._length + gs.p + ylw / 2;

        // save axis line positions for ticks, draggers, etc to reference
        // each subplot gets an entry:
        //    [left or bottom, right or top, free, main]
        // main is the position at which to draw labels and draggers, if any
        xa._linepositions[subplot] = [
            showbottom ? bottompos : undefined,
            showtop ? toppos : undefined,
            showfreex ? freeposx : undefined
        ];
        if(xa.anchor === ya._id) {
            xa._linepositions[subplot][3] = xa.side === 'top' ?
                toppos : bottompos;
        }
        else if(showfreex) {
            xa._linepositions[subplot][3] = freeposx;
        }

        ya._linepositions[subplot] = [
            showleft ? leftpos : undefined,
            showright ? rightpos : undefined,
            showfreey ? freeposy : undefined
        ];
        if(ya.anchor === xa._id) {
            ya._linepositions[subplot][3] = ya.side === 'right' ?
                rightpos : leftpos;
        }
        else if(showfreey) {
            ya._linepositions[subplot][3] = freeposy;
        }

        // translate all the extra stuff to have the
        // same origin as the plot area or axes
        var origin = 'translate(' + xa._offset + ',' + ya._offset + ')',
            originx = origin,
            originy = origin;
        if(showfreex) {
            originx = 'translate(' + xa._offset + ',' + gs.t + ')';
            toppos += ya._offset - gs.t;
            bottompos += ya._offset - gs.t;
        }
        if(showfreey) {
            originy = 'translate(' + gs.l + ',' + ya._offset + ')';
            leftpos += xa._offset - gs.l;
            rightpos += xa._offset - gs.l;
        }

        plotinfo.xlines
            .attr('transform', originx)
            .attr('d', (
                (showbottom ? (xpathPrefix + bottompos + xpathSuffix) : '') +
                (showtop ? (xpathPrefix + toppos + xpathSuffix) : '') +
                (showfreex ? (xpathPrefix + freeposx + xpathSuffix) : '')) ||
                // so it doesn't barf with no lines shown
                'M0,0')
            .style('stroke-width', xlw + 'px')
            .call(Color.stroke, xa.showline ?
                xa.linecolor : 'rgba(0,0,0,0)');
        plotinfo.ylines
            .attr('transform', originy)
            .attr('d', (
                (showleft ? ('M' + leftpos + ypathSuffix) : '') +
                (showright ? ('M' + rightpos + ypathSuffix) : '') +
                (showfreey ? ('M' + freeposy + ypathSuffix) : '')) ||
                'M0,0')
            .attr('stroke-width', ylw + 'px')
            .call(Color.stroke, ya.showline ?
                ya.linecolor : 'rgba(0,0,0,0)');

        plotinfo.xaxislayer.attr('transform', originx);
        plotinfo.yaxislayer.attr('transform', originy);
        plotinfo.gridlayer.attr('transform', origin);
        plotinfo.zerolinelayer.attr('transform', origin);
        plotinfo.draglayer.attr('transform', origin);

        // mark free axes as displayed, so we don't draw them again
        if(showfreex) { freefinished.push(xa._id); }
        if(showfreey) { freefinished.push(ya._id); }
    });

    Plotly.Axes.makeClipPaths(gd);
    exports.drawMainTitle(gd);
    ModeBar.manage(gd);

    return gd._promises.length && Promise.all(gd._promises);
};

exports.drawMainTitle = function(gd) {
    var fullLayout = gd._fullLayout;

    Titles.draw(gd, 'gtitle', {
        propContainer: fullLayout,
        propName: 'title',
        dfltName: 'Plot',
        attributes: {
            x: fullLayout.width / 2,
            y: fullLayout._size.t / 2,
            'text-anchor': 'middle'
        }
    });
};

// First, see if we need to do arraysToCalcdata
// call it regardless of what change we made, in case
// supplyDefaults brought in an array that was already
// in gd.data but not in gd._fullData previously
exports.doTraceStyle = function(gd) {
    for(var i = 0; i < gd.calcdata.length; i++) {
        var cdi = gd.calcdata[i],
            _module = ((cdi[0] || {}).trace || {})._module || {},
            arraysToCalcdata = _module.arraysToCalcdata;

        if(arraysToCalcdata) arraysToCalcdata(cdi, cdi[0].trace);
    }

    Plots.style(gd);
    Registry.getComponentMethod('legend', 'draw')(gd);

    return Plots.previousPromises(gd);
};

exports.doColorBars = function(gd) {
    for(var i = 0; i < gd.calcdata.length; i++) {
        var cdi0 = gd.calcdata[i][0];

        if((cdi0.t || {}).cb) {
            var trace = cdi0.trace,
                cb = cdi0.t.cb;

            if(Registry.traceIs(trace, 'contour')) {
                cb.line({
                    width: trace.contours.showlines !== false ?
                        trace.line.width : 0,
                    dash: trace.line.dash,
                    color: trace.contours.coloring === 'line' ?
                        cb._opts.line.color : trace.line.color
                });
            }
            if(Registry.traceIs(trace, 'markerColorscale')) {
                cb.options(trace.marker.colorbar)();
            }
            else cb.options(trace.colorbar)();
        }
    }

    return Plots.previousPromises(gd);
};

// force plot() to redo the layout and replot with the modified layout
exports.layoutReplot = function(gd) {
    var layout = gd.layout;
    gd.layout = undefined;
    return Plotly.plot(gd, '', layout);
};

exports.doLegend = function(gd) {
    Registry.getComponentMethod('legend', 'draw')(gd);
    return Plots.previousPromises(gd);
};

exports.doTicksRelayout = function(gd) {
    Plotly.Axes.doTicks(gd, 'redraw');
    exports.drawMainTitle(gd);
    return Plots.previousPromises(gd);
};

exports.doModeBar = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds, i;

    ModeBar.manage(gd);
    initInteractions(gd);

    subplotIds = Plots.getSubplotIds(fullLayout, 'gl3d');
    for(i = 0; i < subplotIds.length; i++) {
        var scene = fullLayout[subplotIds[i]]._scene;
        scene.updateFx(fullLayout.dragmode, fullLayout.hovermode);
    }

    return Plots.previousPromises(gd);
};

exports.doCamera = function(gd) {
    var fullLayout = gd._fullLayout,
        sceneIds = Plots.getSubplotIds(fullLayout, 'gl3d');

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneLayout = fullLayout[sceneIds[i]],
            scene = sceneLayout._scene;

        scene.setCamera(sceneLayout.camera);
    }
};
<commit_msg>don't try to style grid lines either<commit_after>/**
* Copyright 2012-2017, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

var d3 = require('d3');
var Plotly = require('../plotly');
var Registry = require('../registry');
var Plots = require('../plots/plots');
var Lib = require('../lib');

var Color = require('../components/color');
var Drawing = require('../components/drawing');
var Titles = require('../components/titles');
var ModeBar = require('../components/modebar');
var initInteractions = require('../plots/cartesian/graph_interact');

exports.layoutStyles = function(gd) {
    return Lib.syncOrAsync([Plots.doAutoMargin, exports.lsInner], gd);
};

function overlappingDomain(xDomain, yDomain, domains) {
    for(var i = 0; i < domains.length; i++) {
        var existingX = domains[i][0],
            existingY = domains[i][1];

        if(existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) {
            continue;
        }
        if(existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) {
            return true;
        }
    }
    return false;
}

exports.lsInner = function(gd) {
    var fullLayout = gd._fullLayout,
        gs = fullLayout._size,
        axList = Plotly.Axes.list(gd),
        i;

    // clear axis line positions, to be set in the subplot loop below
    for(i = 0; i < axList.length; i++) axList[i]._linepositions = {};

    fullLayout._paperdiv
        .style({
            width: fullLayout.width + 'px',
            height: fullLayout.height + 'px'
        })
        .selectAll('.main-svg')
            .call(Drawing.setSize, fullLayout.width, fullLayout.height);

    gd._context.setBackground(gd, fullLayout.paper_bgcolor);

    var subplotSelection = fullLayout._paper.selectAll('g.subplot');

    // figure out which backgrounds we need to draw, and in which layers
    // to put them
    var lowerBackgroundIDs = [];
    var lowerDomains = [];
    subplotSelection.each(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];

        if(plotinfo.mainplot) {
            // mainplot is a reference to the main plot this one is overlaid on
            // so if it exists, this is an overlaid plot and we don't need to
            // give it its own background
            if(plotinfo.bg) {
                plotinfo.bg.remove();
            }
            plotinfo.bg = undefined;
            return;
        }

        var xa = Plotly.Axes.getFromId(gd, subplot, 'x'),
            ya = Plotly.Axes.getFromId(gd, subplot, 'y'),
            xDomain = xa.domain,
            yDomain = ya.domain,
            plotgroupBgData = [];

        if(overlappingDomain(xDomain, yDomain, lowerDomains)) {
            plotgroupBgData = [0];
        }
        else {
            lowerBackgroundIDs.push(subplot);
            lowerDomains.push([xDomain, yDomain]);
        }

        // create the plot group backgrounds now, since
        // they're all independent selections
        var plotgroupBg = plotinfo.plotgroup.selectAll('.bg')
            .data(plotgroupBgData);

        plotgroupBg.enter().append('rect')
            .classed('bg', true);

        plotgroupBg.exit().remove();

        plotgroupBg.each(function() {
            plotinfo.bg = plotgroupBg;
            var pgNode = plotinfo.plotgroup.node();
            pgNode.insertBefore(this, pgNode.childNodes[0]);
        });
    });

    // now create all the lower-layer backgrounds at once now that
    // we have the list of subplots that need them
    var lowerBackgrounds = fullLayout._bgLayer.selectAll('.bg')
        .data(lowerBackgroundIDs);

    lowerBackgrounds.enter().append('rect')
        .classed('bg', true);

    lowerBackgrounds.exit().remove();

    lowerBackgrounds.each(function(subplot) {
        fullLayout._plots[subplot].bg = d3.select(this);
    });

    var freefinished = [];
    subplotSelection.each(function(subplot) {
        var plotinfo = fullLayout._plots[subplot];

        var xa = Plotly.Axes.getFromId(gd, subplot, 'x'),
            ya = Plotly.Axes.getFromId(gd, subplot, 'y');

        // reset scale in case the margins have changed
        xa.setScale();
        ya.setScale();

        if(plotinfo.bg && fullLayout._has('cartesian')) {
            plotinfo.bg
                .call(Drawing.setRect,
                    xa._offset - gs.p, ya._offset - gs.p,
                    xa._length + 2 * gs.p, ya._length + 2 * gs.p)
                .call(Color.fill, fullLayout.plot_bgcolor)
                .style('stroke-width', 0);
        }

        // Clip so that data only shows up on the plot area.
        plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot';

        var plotClip = fullLayout._defs.selectAll('g.clips')
            .selectAll('#' + plotinfo.clipId)
            .data([0]);

        plotClip.enter().append('clipPath')
            .attr({
                'class': 'plotclip',
                'id': plotinfo.clipId
            })
            .append('rect');

        plotClip.selectAll('rect')
            .attr({
                'width': xa._length,
                'height': ya._length
            });

        plotinfo.plot.call(Drawing.setTranslate, xa._offset, ya._offset);
        plotinfo.plot.call(Drawing.setClipUrl, plotinfo.clipId);

        var xlw = Drawing.crispRound(gd, xa.linewidth, 1),
            ylw = Drawing.crispRound(gd, ya.linewidth, 1),
            xp = gs.p + ylw,
            xpathPrefix = 'M' + (-xp) + ',',
            xpathSuffix = 'h' + (xa._length + 2 * xp),
            showfreex = xa.anchor === 'free' &&
                freefinished.indexOf(xa._id) === -1,
            freeposx = gs.h * (1 - (xa.position||0)) + ((xlw / 2) % 1),
            showbottom =
                (xa.anchor === ya._id && (xa.mirror || xa.side !== 'top')) ||
                xa.mirror === 'all' || xa.mirror === 'allticks' ||
                (xa.mirrors && xa.mirrors[ya._id + 'bottom']),
            bottompos = ya._length + gs.p + xlw / 2,
            showtop =
                (xa.anchor === ya._id && (xa.mirror || xa.side === 'top')) ||
                xa.mirror === 'all' || xa.mirror === 'allticks' ||
                (xa.mirrors && xa.mirrors[ya._id + 'top']),
            toppos = -gs.p - xlw / 2,

            // shorten y axis lines so they don't overlap x axis lines
            yp = gs.p,
            // except where there's no x line
            // TODO: this gets more complicated with multiple x and y axes
            ypbottom = showbottom ? 0 : xlw,
            yptop = showtop ? 0 : xlw,
            ypathSuffix = ',' + (-yp - yptop) +
                'v' + (ya._length + 2 * yp + yptop + ypbottom),
            showfreey = ya.anchor === 'free' &&
                freefinished.indexOf(ya._id) === -1,
            freeposy = gs.w * (ya.position||0) + ((ylw / 2) % 1),
            showleft =
                (ya.anchor === xa._id && (ya.mirror || ya.side !== 'right')) ||
                ya.mirror === 'all' || ya.mirror === 'allticks' ||
                (ya.mirrors && ya.mirrors[xa._id + 'left']),
            leftpos = -gs.p - ylw / 2,
            showright =
                (ya.anchor === xa._id && (ya.mirror || ya.side === 'right')) ||
                ya.mirror === 'all' || ya.mirror === 'allticks' ||
                (ya.mirrors && ya.mirrors[xa._id + 'right']),
            rightpos = xa._length + gs.p + ylw / 2;

        // save axis line positions for ticks, draggers, etc to reference
        // each subplot gets an entry:
        //    [left or bottom, right or top, free, main]
        // main is the position at which to draw labels and draggers, if any
        xa._linepositions[subplot] = [
            showbottom ? bottompos : undefined,
            showtop ? toppos : undefined,
            showfreex ? freeposx : undefined
        ];
        if(xa.anchor === ya._id) {
            xa._linepositions[subplot][3] = xa.side === 'top' ?
                toppos : bottompos;
        }
        else if(showfreex) {
            xa._linepositions[subplot][3] = freeposx;
        }

        ya._linepositions[subplot] = [
            showleft ? leftpos : undefined,
            showright ? rightpos : undefined,
            showfreey ? freeposy : undefined
        ];
        if(ya.anchor === xa._id) {
            ya._linepositions[subplot][3] = ya.side === 'right' ?
                rightpos : leftpos;
        }
        else if(showfreey) {
            ya._linepositions[subplot][3] = freeposy;
        }

        // translate all the extra stuff to have the
        // same origin as the plot area or axes
        var origin = 'translate(' + xa._offset + ',' + ya._offset + ')',
            originx = origin,
            originy = origin;
        if(showfreex) {
            originx = 'translate(' + xa._offset + ',' + gs.t + ')';
            toppos += ya._offset - gs.t;
            bottompos += ya._offset - gs.t;
        }
        if(showfreey) {
            originy = 'translate(' + gs.l + ',' + ya._offset + ')';
            leftpos += xa._offset - gs.l;
            rightpos += xa._offset - gs.l;
        }

        if(fullLayout._has('cartesian')) {
            plotinfo.xlines
                .attr('transform', originx)
                .attr('d', (
                    (showbottom ? (xpathPrefix + bottompos + xpathSuffix) : '') +
                    (showtop ? (xpathPrefix + toppos + xpathSuffix) : '') +
                    (showfreex ? (xpathPrefix + freeposx + xpathSuffix) : '')) ||
                    // so it doesn't barf with no lines shown
                    'M0,0')
                .style('stroke-width', xlw + 'px')
                .call(Color.stroke, xa.showline ?
                    xa.linecolor : 'rgba(0,0,0,0)');
            plotinfo.ylines
                .attr('transform', originy)
                .attr('d', (
                    (showleft ? ('M' + leftpos + ypathSuffix) : '') +
                    (showright ? ('M' + rightpos + ypathSuffix) : '') +
                    (showfreey ? ('M' + freeposy + ypathSuffix) : '')) ||
                    'M0,0')
                .attr('stroke-width', ylw + 'px')
                .call(Color.stroke, ya.showline ?
                    ya.linecolor : 'rgba(0,0,0,0)');
        }

        plotinfo.xaxislayer.attr('transform', originx);
        plotinfo.yaxislayer.attr('transform', originy);
        plotinfo.gridlayer.attr('transform', origin);
        plotinfo.zerolinelayer.attr('transform', origin);
        plotinfo.draglayer.attr('transform', origin);

        // mark free axes as displayed, so we don't draw them again
        if(showfreex) { freefinished.push(xa._id); }
        if(showfreey) { freefinished.push(ya._id); }
    });

    Plotly.Axes.makeClipPaths(gd);
    exports.drawMainTitle(gd);
    ModeBar.manage(gd);

    return gd._promises.length && Promise.all(gd._promises);
};

exports.drawMainTitle = function(gd) {
    var fullLayout = gd._fullLayout;

    Titles.draw(gd, 'gtitle', {
        propContainer: fullLayout,
        propName: 'title',
        dfltName: 'Plot',
        attributes: {
            x: fullLayout.width / 2,
            y: fullLayout._size.t / 2,
            'text-anchor': 'middle'
        }
    });
};

// First, see if we need to do arraysToCalcdata
// call it regardless of what change we made, in case
// supplyDefaults brought in an array that was already
// in gd.data but not in gd._fullData previously
exports.doTraceStyle = function(gd) {
    for(var i = 0; i < gd.calcdata.length; i++) {
        var cdi = gd.calcdata[i],
            _module = ((cdi[0] || {}).trace || {})._module || {},
            arraysToCalcdata = _module.arraysToCalcdata;

        if(arraysToCalcdata) arraysToCalcdata(cdi, cdi[0].trace);
    }

    Plots.style(gd);
    Registry.getComponentMethod('legend', 'draw')(gd);

    return Plots.previousPromises(gd);
};

exports.doColorBars = function(gd) {
    for(var i = 0; i < gd.calcdata.length; i++) {
        var cdi0 = gd.calcdata[i][0];

        if((cdi0.t || {}).cb) {
            var trace = cdi0.trace,
                cb = cdi0.t.cb;

            if(Registry.traceIs(trace, 'contour')) {
                cb.line({
                    width: trace.contours.showlines !== false ?
                        trace.line.width : 0,
                    dash: trace.line.dash,
                    color: trace.contours.coloring === 'line' ?
                        cb._opts.line.color : trace.line.color
                });
            }
            if(Registry.traceIs(trace, 'markerColorscale')) {
                cb.options(trace.marker.colorbar)();
            }
            else cb.options(trace.colorbar)();
        }
    }

    return Plots.previousPromises(gd);
};

// force plot() to redo the layout and replot with the modified layout
exports.layoutReplot = function(gd) {
    var layout = gd.layout;
    gd.layout = undefined;
    return Plotly.plot(gd, '', layout);
};

exports.doLegend = function(gd) {
    Registry.getComponentMethod('legend', 'draw')(gd);
    return Plots.previousPromises(gd);
};

exports.doTicksRelayout = function(gd) {
    Plotly.Axes.doTicks(gd, 'redraw');
    exports.drawMainTitle(gd);
    return Plots.previousPromises(gd);
};

exports.doModeBar = function(gd) {
    var fullLayout = gd._fullLayout;
    var subplotIds, i;

    ModeBar.manage(gd);
    initInteractions(gd);

    subplotIds = Plots.getSubplotIds(fullLayout, 'gl3d');
    for(i = 0; i < subplotIds.length; i++) {
        var scene = fullLayout[subplotIds[i]]._scene;
        scene.updateFx(fullLayout.dragmode, fullLayout.hovermode);
    }

    return Plots.previousPromises(gd);
};

exports.doCamera = function(gd) {
    var fullLayout = gd._fullLayout,
        sceneIds = Plots.getSubplotIds(fullLayout, 'gl3d');

    for(var i = 0; i < sceneIds.length; i++) {
        var sceneLayout = fullLayout[sceneIds[i]],
            scene = sceneLayout._scene;

        scene.setCamera(sceneLayout.camera);
    }
};
<|endoftext|>


<commit_before>module.exports = {
  // @グラフ描画_CHARTJS
  'グラフ描画': { // @ Chart.jsを利用して、DATAのグラフを描画 // @ぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: true,
    fn: function (data, sys) {
      // Chart.jsが使えるかチェック
      if (!window['Chart']) {
        throw new Error('『グラフ描画』のエラー。Chart.jsを取り込んでください。')
      }
      // Canvasが有効？
      if (!sys.__canvas) {
        throw new Error('『グラフ描画』のエラー。『描画開始』命令で描画先のCanvasを指定してください。 ')
      }
      // 日本語のキーワードを変換
      if (data['タイプ']) { data['type'] = data['タイプ'] }
      if (data['データ']) { data['data'] = data['データ'] }
      if (data['オプション']) { data['options'] = data['オプション'] }
      if (sys.__chartjs) {
        sys.__chartjs.destroy()
      }
      const chart = new Chart(sys.__canvas, data)
      sys.__chartjs = chart
      return chart
    }
  },
  'グラフオプション': {type: 'const', value: {}}, // @ぐらふおぷしょん
  '線グラフ描画': { // @ 線グラフを描画 // @せんぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['line', data, sys])
      const d = {
        type: 'line',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '棒グラフ描画': { // @ 棒グラフを描画 // @ぼうぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        {'indexAxis': 'x'})
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'bar',
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '横棒グラフ描画': { // @ 横棒グラフを描画 // @よこぼうぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        {'indexAxis': 'y'})
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'bar', // horizontalBar
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '積上棒グラフ描画': { // @ 複数列のデータがある場合積み上げ棒グラフを描画 // @つみあげぼうぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        {
          'indexAxis': 'x',
          'scales': {
            x: { stacked: true },
            y: { stacked: true }
          }
        })
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'bar',
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '積上横棒グラフ描画': { // @ 複数列のデータがある場合積み上げ棒グラフを描画 // @つみあげよこぼうぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        {
          'indexAxis': 'y',
          'scales': {
            x: { stacked: true },
            y: { stacked: true }
          }
        })
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'bar',
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '散布図描画': { // @ 散布図を描画 // @さんぷず
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        {})
      data = sys.__exec('二次元グラフデータ変形', ['scatter', data, sys])
      const d = {
        type: 'scatter',
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '円グラフ描画': { // @ 円グラフを描画 // @えんぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['pie', data, sys])
      const d = {
        type: 'pie',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  'ドーナツグラフ描画': { // @ 円グラフ（ドーナツ）を描画 // @ドーナツぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['pie', data, sys])
      const d = {
        type: 'doughnut',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  'ポーラーグラフ描画': { // @ 円グラフ（鶏頭グラフ/ポーラーエリアチャート）を描画 // @ぽーらーぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['pie', data, sys])
      const d = {
        type: 'polarArea',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  'レーダーグラフ描画': { // @ レーダーチャートを描画 // @れーだーぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'radar',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '二次元グラフデータ変形': { // @ 二次元配列をXXグラフ描画の形式に整形する。種類TとDATAを指定。 // @にじげんぐらふでーたへんけい
    type: 'func',
    josi: [['の'],['を']],
    pure: false,
    fn: function (t, data, sys) {
      const bgcolorList = [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ]
      const fgcolorList = [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ]
      const res = {}
      const bgcolors = []
      const fgcolors = []
      res['labels'] = []
      // 配列かどうか
      if (data instanceof Array) {
        // 二次元データのとき
        if (data[0] instanceof Array) {
          if (t === 'pie') { // 円グラフの時だけ整形方法が異なる
            const o = {}
            o['data'] = []
            res['datasets'] = [o]
            for (let i = 0; i < data.length; i++) {
              res['labels'].push(data[i][0]) // label
              o['data'].push(data[i][1]) // value
              bgcolors.push(bgcolorList[i % 6])
              fgcolors.push(fgcolorList[i % 6])
            }
            o['backgroundColor'] = bgcolors
            o['borderColor'] = fgcolors
            return res
          }
          // 左側のラベルの処理
          // [1,0]が文字列ならラベルあり
          if (typeof(data[1][0]) === 'string') {
            for (let i = 1; i < data.length; i++) {
              res['labels'].push(data[i][0]) // 左ラベルを追加
              data[i] = data[i].slice(1) // 左ラベル除去
            }
            data[0] = data[0].slice(1) // ヘッダ行も左ラベルを削除
          } else {
            // 左側ラベルない場合 - ダミーのラベルを追加
            for (let i = 1; i < data.length; i++) {
              res['labels'].push(i)
            }
          }
          res['datasets'] = []
          for (let i = 0; i < data[0].length; i++) {
            const o = {}
            res['datasets'].push(o)
            o.label = data[0][i]
            o.backgroundColor = bgcolorList[i % 6]
            o.borderColor = fgcolorList[i % 6]
            o.data = []
            for (let j = 1; j < data.length; j++) {
              o.data.push(data[j][i])
            }
          }
          // console.log(res)
          return res
        }
        // 一次元データのとき
        // ラベルを作成
        for (let i = 0; i < data.length; i++) {
          res['labels'].push(i+1)
          bgcolors.push(bgcolorList[i % 6])
          fgcolors.push(fgcolorList[i % 6])
        }
        const o1 = {}
        res['datasets'] = [o1]
        o1['label'] = 'データ'
        o1['data'] = data
        o1['backgroundColor'] = bgcolors
        o1['borderColor'] = fgcolors
        // console.log(res)
        return res
      }
      if (data instanceof Object) {return data}
      // データが1つだけのとき
      return sys.__exec('二次元グラフデータ変形', [[data], sys])
    }
  }
}
<commit_msg>ESLintをかける #1046<commit_after>// @ts-nocheck
module.exports = {
  // @グラフ描画_CHARTJS
  'グラフ描画': { // @ Chart.jsを利用して、DATAのグラフを描画 // @ぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: true,
    fn: function (data, sys) {
      // Chart.jsが使えるかチェック
      if (!window.Chart) {
        throw new Error('『グラフ描画』のエラー。Chart.jsを取り込んでください。')
      }
      // Canvasが有効？
      if (!sys.__canvas) {
        throw new Error('『グラフ描画』のエラー。『描画開始』命令で描画先のCanvasを指定してください。 ')
      }
      // 日本語のキーワードを変換
      if (data['タイプ']) { data.type = data['タイプ'] }
      if (data['データ']) { data.data = data['データ'] }
      if (data['オプション']) { data.options = data['オプション'] }
      if (sys.__chartjs) {
        sys.__chartjs.destroy()
      }
      // eslint-disable-next-line no-undef
      const chart = new Chart(sys.__canvas, data)
      sys.__chartjs = chart
      return chart
    }
  },
  'グラフオプション': { type: 'const', value: {} }, // @ぐらふおぷしょん
  '線グラフ描画': { // @ 線グラフを描画 // @せんぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['line', data, sys])
      const d = {
        type: 'line',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '棒グラフ描画': { // @ 棒グラフを描画 // @ぼうぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        { 'indexAxis': 'x' })
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'bar',
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '横棒グラフ描画': { // @ 横棒グラフを描画 // @よこぼうぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        { 'indexAxis': 'y' })
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'bar', // horizontalBar
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '積上棒グラフ描画': { // @ 複数列のデータがある場合積み上げ棒グラフを描画 // @つみあげぼうぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        {
          'indexAxis': 'x',
          'scales': {
            x: { stacked: true },
            y: { stacked: true }
          }
        })
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'bar',
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '積上横棒グラフ描画': { // @ 複数列のデータがある場合積み上げ棒グラフを描画 // @つみあげよこぼうぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        {
          'indexAxis': 'y',
          'scales': {
            x: { stacked: true },
            y: { stacked: true }
          }
        })
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'bar',
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '散布図描画': { // @ 散布図を描画 // @さんぷず
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      // グラフオプションの差分作成
      const gopt = Object.assign({},
        sys.__v0['グラフオプション'],
        {})
      data = sys.__exec('二次元グラフデータ変形', ['scatter', data, sys])
      const d = {
        type: 'scatter',
        data: data,
        options: gopt
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '円グラフ描画': { // @ 円グラフを描画 // @えんぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['pie', data, sys])
      const d = {
        type: 'pie',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  'ドーナツグラフ描画': { // @ 円グラフ（ドーナツ）を描画 // @ドーナツぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['pie', data, sys])
      const d = {
        type: 'doughnut',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  'ポーラーグラフ描画': { // @ 円グラフ（鶏頭グラフ/ポーラーエリアチャート）を描画 // @ぽーらーぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['pie', data, sys])
      const d = {
        type: 'polarArea',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  'レーダーグラフ描画': { // @ レーダーチャートを描画 // @れーだーぐらふびょうが
    type: 'func',
    josi: [['を', 'で', 'の']],
    pure: false,
    fn: function (data, sys) {
      data = sys.__exec('二次元グラフデータ変形', ['bar', data, sys])
      const d = {
        type: 'radar',
        data: data,
        options: sys.__v0['グラフオプション']
      }
      return sys.__exec('グラフ描画', [d, sys])
    }
  },
  '二次元グラフデータ変形': { // @ 二次元配列をXXグラフ描画の形式に整形する。種類TとDATAを指定。 // @にじげんぐらふでーたへんけい
    type: 'func',
    josi: [['の'], ['を']],
    pure: false,
    fn: function (t, data, sys) {
      const bgcolorList = [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ]
      const fgcolorList = [
        'rgba(255, 99, 132, 1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ]
      const res = {}
      const bgcolors = []
      const fgcolors = []
      res.labels = []
      // 配列かどうか
      if (data instanceof Array) {
        // 二次元データのとき
        if (data[0] instanceof Array) {
          if (t === 'pie') { // 円グラフの時だけ整形方法が異なる
            const o = {}
            o.data = []
            res.datasets = [o]
            for (let i = 0; i < data.length; i++) {
              res.labels.push(data[i][0]) // label
              o.data.push(data[i][1]) // value
              bgcolors.push(bgcolorList[i % 6])
              fgcolors.push(fgcolorList[i % 6])
            }
            o.backgroundColor = bgcolors
            o.borderColor = fgcolors
            return res
          }
          // 左側のラベルの処理
          // [1,0]が文字列ならラベルあり
          if (typeof (data[1][0]) === 'string') {
            for (let i = 1; i < data.length; i++) {
              res.labels.push(data[i][0]) // 左ラベルを追加
              data[i] = data[i].slice(1) // 左ラベル除去
            }
            data[0] = data[0].slice(1) // ヘッダ行も左ラベルを削除
          } else {
            // 左側ラベルない場合 - ダミーのラベルを追加
            for (let i = 1; i < data.length; i++) {
              res.labels.push(i)
            }
          }
          res.datasets = []
          for (let i = 0; i < data[0].length; i++) {
            const o = {}
            res.datasets.push(o)
            o.label = data[0][i]
            o.backgroundColor = bgcolorList[i % 6]
            o.borderColor = fgcolorList[i % 6]
            o.data = []
            for (let j = 1; j < data.length; j++) {
              o.data.push(data[j][i])
            }
          }
          // console.log(res)
          return res
        }
        // 一次元データのとき
        // ラベルを作成
        for (let i = 0; i < data.length; i++) {
          res.labels.push(i + 1)
          bgcolors.push(bgcolorList[i % 6])
          fgcolors.push(fgcolorList[i % 6])
        }
        const o1 = {}
        res.datasets = [o1]
        o1.label = 'データ'
        o1.data = data
        o1.backgroundColor = bgcolors
        o1.borderColor = fgcolors
        // console.log(res)
        return res
      }
      if (data instanceof Object) { return data }
      // データが1つだけのとき
      return sys.__exec('二次元グラフデータ変形', [[data], sys])
    }
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import radium from 'radium';
import merge from 'lodash/merge';

import {
  getType,
  getReference,
  findElement,
} from '../../Modules/ElementUtils/ElementUtils';

import { MONO_FONT_FAMILY } from '../../Constants/fonts';

class Type extends React.Component {
  static propTypes = {
    type: React.PropTypes.string,
    reference: React.PropTypes.bool,
    element: React.PropTypes.object,
    onClick: React.PropTypes.func,
    style: React.PropTypes.object,
  };

  static contextTypes = {
    theme: React.PropTypes.object,
    onElementLinkClick: React.PropTypes.func,
    dereferencedDataStructures: React.PropTypes.array,
  };

  get style() {
    const { TYPE_COLOR } = this.context.theme;

    const style = {
      type: {
        width: '100%',
        fontFamily: MONO_FONT_FAMILY,
        fontWeight: 'regular',
        fontSize: '13px',
        color: TYPE_COLOR,
        lineHeight: '13px',
      },
      reference: {
        width: '100%',
        fontFamily: MONO_FONT_FAMILY,
        fontWeight: 'regular',
        fontSize: '13px',
        color: TYPE_COLOR,
        textDecoration: 'underline',
        cursor: 'pointer',

        ':hover': {
          textDecoration: 'none',
        },
      },
    };

    return merge(style, this.props.style || {});
  }

  handleClick = (event) => {
    const reference = getReference(this.props.element);
    const element = findElement(reference, this.context.dereferencedDataStructures);

    if (this.context.onElementLinkClick) {
      return this.context.onElementLinkClick(
        element.meta.id, element, event
      );
    }

    return null;
  }

  render() {
    if (this.props.reference) {
      return (

          {this.props.reference}

      );
    }

    if (this.props.type) {
      return (

          {this.props.type}

      );
    }

    if (this.props.element) {
      const type = getType(this.props.element);

      if (type) {
        return (

            {type}

        );
      }
    }

    return null;
  }
}

export default radium(Type);
<commit_msg>fix: correct Type.propTypes.reference<commit_after>import React from 'react';
import radium from 'radium';
import merge from 'lodash/merge';

import {
  getType,
  getReference,
  findElement,
} from '../../Modules/ElementUtils/ElementUtils';

import { MONO_FONT_FAMILY } from '../../Constants/fonts';

class Type extends React.Component {
  static propTypes = {
    type: React.PropTypes.string,
    reference: React.PropTypes.string,
    element: React.PropTypes.object,
    onClick: React.PropTypes.func,
    style: React.PropTypes.object,
  };

  static contextTypes = {
    theme: React.PropTypes.object,
    onElementLinkClick: React.PropTypes.func,
    dereferencedDataStructures: React.PropTypes.array,
  };

  get style() {
    const { TYPE_COLOR } = this.context.theme;

    const style = {
      type: {
        width: '100%',
        fontFamily: MONO_FONT_FAMILY,
        fontWeight: 'regular',
        fontSize: '13px',
        color: TYPE_COLOR,
        lineHeight: '13px',
      },
      reference: {
        width: '100%',
        fontFamily: MONO_FONT_FAMILY,
        fontWeight: 'regular',
        fontSize: '13px',
        color: TYPE_COLOR,
        textDecoration: 'underline',
        cursor: 'pointer',

        ':hover': {
          textDecoration: 'none',
        },
      },
    };

    return merge(style, this.props.style || {});
  }

  handleClick = (event) => {
    const reference = getReference(this.props.element);
    const element = findElement(reference, this.context.dereferencedDataStructures);

    if (this.context.onElementLinkClick) {
      return this.context.onElementLinkClick(
        element.meta.id, element, event
      );
    }

    return null;
  }

  render() {
    if (this.props.reference) {
      return (

          {this.props.reference}

      );
    }

    if (this.props.type) {
      return (

          {this.props.type}

      );
    }

    if (this.props.element) {
      const type = getType(this.props.element);

      if (type) {
        return (

            {type}

        );
      }
    }

    return null;
  }
}

export default radium(Type);
<|endoftext|>


<commit_before>/*
* @Author: mike
* @Date:   2015-05-18 17:04:13
* @Last Modified 2015-11-05
* @Last Modified time: 2015-11-05 18:55:08
*/

'use strict';

import fs from 'fs'
import _ from 'underscore'
import path from 'path'

class ConfigurationManager {

  constructor(opts = {}) {

  }

  getNodeEnv() {
    return process.env.NODE_ENV || 'dev'
  }

  getPackageJSONConfig() {
    var config = {};
    var jsonPath = path.resolve(this.appDir + '/package.json')
    if(fs.existsSync(jsonPath)) {
      try {
        var jsonParsed = JSON.parse(fs.readFileSync(jsonPath))
        if(jsonParsed.config)
          config = jsonParsed.config[this.getNodeEnv()]
      } catch(e) {
        console.log('Warning: error parsing config file', jsonPath, e)
      }
    }
    return config
  }

  getEnvironmentVariables() {
    // alias the MONGO_URI variable as `db`
    if (process.env.MONGO_URI) {
      process.env.db = process.env.MONGO_URI
    }
    // default port for HTTP
    if (!process.env.PORT) {
      process.env.PORT = 3000
    }
    return process.env
  }

  getConfig() {
    return _.extend(
      // Read the config in the app's package.json
      this.getPackageJSONConfig() || {},
      // Environment variables take precedence
      this.getEnvironmentVariables(),
      // but NODE_ENV must be present so, ensure it
      {NODE_ENV: this.getNodeEnv()}
    )
  }
}

module.exports = ConfigurationManager<commit_msg>Fixed issue with config manager not loading config when no env is present<commit_after>/*
* @Author: mike
* @Date:   2015-05-18 17:04:13
* @Last Modified 2015-12-08
* @Last Modified time: 2015-12-08 17:24:21
*/

'use strict';

import fs from 'fs'
import _ from 'underscore'
import path from 'path'

class ConfigurationManager {

  constructor(opts = {}) {
    this.opts = opts
  }

  getNodeEnv() {
    return process.env.NODE_ENV || 'dev'
  }

  getPackageJSONConfig() {
    var config = {};
    var jsonPath = path.resolve(this.opts.appDir + '/package.json')
    if(fs.existsSync(jsonPath)) {
      try {
        var jsonParsed = JSON.parse(fs.readFileSync(jsonPath))
        if(jsonParsed.config) {
          if(jsonParsed.config[this.getNodeEnv()])
            config = jsonParsed.config[this.getNodeEnv()]
          else
            config = jsonParsed.config
        }
      } catch(e) {
        console.log('Warning: error parsing config file', jsonPath, e)
      }
    }
    return config
  }

  getEnvironmentVariables() {
    // alias the MONGO_URI variable as `db`
    if (process.env.MONGO_URI) {
      process.env.db = process.env.MONGO_URI
    }
    // default port for HTTP
    if (!process.env.PORT) {
      process.env.PORT = 3000
    }
    return process.env
  }

  getConfig() {
    return _.extend(
      // Read the config in the app's package.json
      this.getPackageJSONConfig() || {},
      // Environment variables take precedence
      this.getEnvironmentVariables(),
      // but NODE_ENV must be present so, ensure it
      {NODE_ENV: this.getNodeEnv()}
    )
  }
}

module.exports = ConfigurationManager<|endoftext|>


<commit_before>var webpack = require('webpack');

import { webpack_resolve, webpack_modules_loaders, devApi, liveApi } from './settings.conf.js';

module.exports = function (config) {
	config.set({
		browsers: ['Firefox'], //run in Chrome
		singleRun: false, //just run once by default
		frameworks: ['mocha'], //use the mocha test framework
		files: [
			'tests.webpack.js' //just load this file
		],
		preprocessors: {
			'tests.webpack.js': ['webpack', 'sourcemap'] //preprocess with webpack and our sourcemap loader
		},
		reporters: ['dots'], //report results in this format
		autoWatch: true,
		webpack: { //kind of a copy of your webpack config
			devtool: 'inline-source-map', //just do inline source maps instead of the default
			resolve: webpack_resolve,
			module: {
				loaders: webpack_modules_loaders
			},
			plugins: [
				new webpack.DefinePlugin({
					__DEVELOPMENT__: false,
					__DEVTOOLS__: false, // <-------- DISABLE redux-devtools HERE
					__DEVAPI__: devApi,
					__LIVEAPI__: liveApi
				})
			]
		},
		webpackServer: {
			noInfo: true //please don't spam the console when running in karma!
		}
	});
};
<commit_msg>Remove trying to use global setting in karma.conf.js<commit_after>var webpack = require('webpack');

module.exports = function (config) {
	config.set({
		browsers: ['Firefox'], //run in Chrome
		singleRun: false, //just run once by default
		frameworks: ['mocha'], //use the mocha test framework
		files: [
			'tests.webpack.js' //just load this file
		],
		preprocessors: {
			'tests.webpack.js': ['webpack', 'sourcemap'] //preprocess with webpack and our sourcemap loader
		},
		reporters: ['dots'], //report results in this format
		autoWatch: true,
		webpack: { //kind of a copy of your webpack config
			devtool: 'inline-source-map', //just do inline source maps instead of the default
			resolve: {
				extensions: ['', '.js', '.jsx'],
				alias: {
					'styles': __dirname + '/src/styles',
					'components': __dirname + '/src/components/',
					'reducers': __dirname + '/src/reducers/',
					'actions': __dirname + '/src/actions/',
					'constants': __dirname + '/src/constants/',
					'pages': __dirname + '/src/pages/'
				}
			},
			module: {
				loaders: [{
					test: /\.(js|jsx)$/,
					exclude: /node_modules/,
					loader: 'react-hot!babel'
				}, {
					test: /\.scss/,
					loader: 'style!css?sourceMap!autoprefixer!sass?outputStyle=expanded'
				}, {
					test: /\.css$/,
					exclude: [/\.raw\.css$/, /\.useable\.css$/],
					loader: 'style!css?sourceMap!autoprefixer'
				}, {
					test: /\.raw\.css$/,
					loader: 'style!raw!autoprefixer'
				}, {
					test: /\.(png|jpg|woff|woff2)$/,
					loader: 'url?limit=8192'
				}]
			},
			plugins: [
				new webpack.DefinePlugin({
					__DEVELOPMENT__: false,
					__DEVTOOLS__: false, // <-------- DISABLE redux-devtools HERE
					__DEVAPI__: "'http://tbg-staging-1.thebuddygroup.com:5000'",
					__LIVEAPI__: "'http://tbg-staging-1.thebuddygroup.com:5000'"
				})
			]
		},
		webpackServer: {
			noInfo: true //please don't spam the console when running in karma!
		}
	});
};
<|endoftext|>


<commit_before>// Tests for the calculator.
var ScreenshotReporter = require('./ScreenshotReporter.js');

exports.config = {
  directConnect: true,

  specs: [
    'spec.js'
  ],

  capabilities: {
    'browserName': 'chrome'
  },

  baseUrl: 'http://localhost:8888',

  onPrepare: function() {
    jasmine.getEnv().addReporter(new ScreenshotReporter("/tmp/protractorss"));
  }
};
<commit_msg>Update conf.js<commit_after>// Tests for the calculator.
var ScreenshotReporter = require('./screenshotReporter.js');

exports.config = {
  directConnect: true,

  specs: [
    'spec.js'
  ],

  capabilities: {
    'browserName': 'chrome'
  },

  baseUrl: 'http://localhost:8888',

  onPrepare: function() {
    jasmine.getEnv().addReporter(new ScreenshotReporter("/tmp/protractorss"));
  }
};
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import {BLOCK_ACTION, FILTER_ACTION, NO_ACTION, REDIRECT_ACTION, WHITELIST_ACTION} from "/src/RequestControl/base.js";
import {OptionsManager} from "/src/options/lib/OptionsManager.js";
import {REQUEST_CONTROL_ICONS} from "/src/notifier.js";

/**
 * Browser Action for displaying applied rules for current tab.
 */

const myOptionsManager = new OptionsManager();
const RECORD_TITLES = {};
RECORD_TITLES[WHITELIST_ACTION] = browser.i18n.getMessage("title_whitelist");
RECORD_TITLES[BLOCK_ACTION] = browser.i18n.getMessage("title_block");
RECORD_TITLES[FILTER_ACTION] = browser.i18n.getMessage("title_filter");
RECORD_TITLES[REDIRECT_ACTION] = browser.i18n.getMessage("title_redirect");
RECORD_TITLES[NO_ACTION] = "";
RECORD_TITLES[FILTER_ACTION | REDIRECT_ACTION] = RECORD_TITLES[FILTER_ACTION];

function setRecords(records) {
    if (!records) {
        return;
    }

    let recordsList = document.getElementById("records");

    for (let i = records.length - 1; i >= 0; i--) {
        let item = newListItem(records[i]);
        recordsList.appendChild(item);
        item.dataset.record = i.toString();
        item.querySelector(".entry-header").addEventListener("click", function () {
            let details = document.getElementById("details");
            item.appendChild(details);
            showDetails(records[i]);
        });
    }
    recordsList.querySelector(".entry:first-child .entry-header").click();

    document.getElementById("records").classList.remove("hidden");
}

function getTags(details) {
    let tags = [];
    let ids = [];
    if (typeof details.rules !== "undefined") {
        ids = details.rules.map(rule => rule.uuid);
    } else {
        ids = details.rule.uuid;
    }
    for (let rule of myOptionsManager.options.rules) {
        if (ids.includes(rule.uuid) && rule.tag) {
            tags.push(rule.tag);
        }
    }
    return tags;
}

function newListItem(details) {
    let model = document.getElementById("entryModel").cloneNode(true);
    model.removeAttribute("id");
    model.querySelector(".type").textContent = browser.i18n.getMessage(details.type);
    model.querySelector(".timestamp").textContent = timestamp(details.timestamp);
    model.querySelector(".icon").src = REQUEST_CONTROL_ICONS[details.action][19];

    if (details.error) {
        model.querySelector(".icon").src = "/icons/ionicons/alert-circled.svg";
        model.querySelector(".action").textContent = browser.i18n.getMessage(details.error.name);
    } else {
        model.querySelector(".action").textContent = RECORD_TITLES[details.action];
        model.querySelector(".url").textContent = details.url;
    }
    let tags = getTags(details);
    let tagsNode = model.querySelector(".tags");
    if (tags.length === 0) {
        tagsNode.parentNode.removeChild(tagsNode);
    } else {
        tagsNode.textContent = decodeURIComponent(tags.join(", "));
    }
    return model;
}

function timestamp(ms) {
    let d = new Date(ms);
    return padDigit(d.getHours(), 2) +
        ":" + padDigit(d.getMinutes(), 2) +
        ":" + padDigit(d.getSeconds(), 2) +
        "." + padDigit(d.getMilliseconds(), 3);
}

function padDigit(digit, padSize) {
    let str = digit.toString();
    let pad = padSize - str.length;
    if (pad > 0) {
        return "0".repeat(pad) + str;
    } else {
        return str;
    }
}

function showDetails(details) {
    document.getElementById("details").classList.remove("hidden");
    document.getElementById("url").textContent = details.url;
    if (details.target) {
        document.getElementById("target").textContent = details.target;
        document.getElementById("targetBlock").classList.remove("hidden");
    } else {
        document.getElementById("targetBlock").classList.add("hidden");
    }
    let editLink = browser.runtime.getURL("src/options/options.html") + "?edit=";
    if (typeof details.rules === "undefined") {
        editLink += details.rule.uuid;
    } else {
        editLink += details.rules.map(rule => rule.uuid).join("&edit=");
    }
    document.getElementById("editLink").href = editLink;
}

function copyText(e) {
    let range = document.createRange();
    let text = document.getElementById(e.currentTarget.dataset.copyTarget);
    range.selectNodeContents(text);
    let selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand("Copy");
    e.currentTarget.classList.add("copied");
}

function copied(e) {
    e.currentTarget.classList.remove("copied");
}

function openOptionsPage() {
    browser.runtime.openOptionsPage();
    window.close();
}

function toggleActive() {
    myOptionsManager.saveOption("disabled", !myOptionsManager.options.disabled);
    setEnabled(!myOptionsManager.options.disabled);
}

function setEnabled(enabled) {
    let button = document.getElementById("toggleActive");
    let textId = enabled ? "activate_false" : "activate_true";
    let titleId = enabled ? "disable_rules" : "enabled_rules";
    button.classList.toggle("disabled", !enabled);
    button.textContent = browser.i18n.getMessage(textId);
    button.title = browser.i18n.getMessage(titleId);
}

document.addEventListener("DOMContentLoaded", function () {
    myOptionsManager.loadOptions().then(function () {
        if (myOptionsManager.options.disabled) {
            setEnabled(false);
            return Promise.reject("");
        } else {
            return browser.runtime.sendMessage(null);
        }
    }).then(records => {
        setEnabled(true);
        if (myOptionsManager.options.rules) {
            setRecords(records);
        }
        let copyButtons = document.getElementsByClassName("copyButton");
        for (let copyButton of copyButtons) {
            copyButton.addEventListener("click", copyText);
            copyButton.addEventListener("mouseleave", copied);
        }
    });

    document.getElementById("showRules").addEventListener("click", openOptionsPage);
    document.getElementById("toggleActive").addEventListener("click", toggleActive);
    document.getElementById("editLink").addEventListener("click", function (e) {
        e.preventDefault();
        browser.tabs.create({
            url: this.href
        });
        window.close();
    });
});
<commit_msg>Fix bad message key<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import {BLOCK_ACTION, FILTER_ACTION, NO_ACTION, REDIRECT_ACTION, WHITELIST_ACTION} from "/src/RequestControl/base.js";
import {OptionsManager} from "/src/options/lib/OptionsManager.js";
import {REQUEST_CONTROL_ICONS} from "/src/notifier.js";

/**
 * Browser Action for displaying applied rules for current tab.
 */

const myOptionsManager = new OptionsManager();
const RECORD_TITLES = {};
RECORD_TITLES[WHITELIST_ACTION] = browser.i18n.getMessage("title_whitelist");
RECORD_TITLES[BLOCK_ACTION] = browser.i18n.getMessage("title_block");
RECORD_TITLES[FILTER_ACTION] = browser.i18n.getMessage("title_filter");
RECORD_TITLES[REDIRECT_ACTION] = browser.i18n.getMessage("title_redirect");
RECORD_TITLES[NO_ACTION] = "";
RECORD_TITLES[FILTER_ACTION | REDIRECT_ACTION] = RECORD_TITLES[FILTER_ACTION];

function setRecords(records) {
    if (!records) {
        return;
    }

    let recordsList = document.getElementById("records");

    for (let i = records.length - 1; i >= 0; i--) {
        let item = newListItem(records[i]);
        recordsList.appendChild(item);
        item.dataset.record = i.toString();
        item.querySelector(".entry-header").addEventListener("click", function () {
            let details = document.getElementById("details");
            item.appendChild(details);
            showDetails(records[i]);
        });
    }
    recordsList.querySelector(".entry:first-child .entry-header").click();

    document.getElementById("records").classList.remove("hidden");
}

function getTags(details) {
    let tags = [];
    let ids = [];
    if (typeof details.rules !== "undefined") {
        ids = details.rules.map(rule => rule.uuid);
    } else {
        ids = details.rule.uuid;
    }
    for (let rule of myOptionsManager.options.rules) {
        if (ids.includes(rule.uuid) && rule.tag) {
            tags.push(rule.tag);
        }
    }
    return tags;
}

function newListItem(details) {
    let model = document.getElementById("entryModel").cloneNode(true);
    model.removeAttribute("id");
    model.querySelector(".type").textContent = browser.i18n.getMessage(details.type);
    model.querySelector(".timestamp").textContent = timestamp(details.timestamp);
    model.querySelector(".icon").src = REQUEST_CONTROL_ICONS[details.action][19];

    if (details.error) {
        model.querySelector(".icon").src = "/icons/ionicons/alert-circled.svg";
        model.querySelector(".action").textContent = browser.i18n.getMessage(details.error.name);
    } else {
        model.querySelector(".action").textContent = RECORD_TITLES[details.action];
        model.querySelector(".url").textContent = details.url;
    }
    let tags = getTags(details);
    let tagsNode = model.querySelector(".tags");
    if (tags.length === 0) {
        tagsNode.parentNode.removeChild(tagsNode);
    } else {
        tagsNode.textContent = decodeURIComponent(tags.join(", "));
    }
    return model;
}

function timestamp(ms) {
    let d = new Date(ms);
    return padDigit(d.getHours(), 2) +
        ":" + padDigit(d.getMinutes(), 2) +
        ":" + padDigit(d.getSeconds(), 2) +
        "." + padDigit(d.getMilliseconds(), 3);
}

function padDigit(digit, padSize) {
    let str = digit.toString();
    let pad = padSize - str.length;
    if (pad > 0) {
        return "0".repeat(pad) + str;
    } else {
        return str;
    }
}

function showDetails(details) {
    document.getElementById("details").classList.remove("hidden");
    document.getElementById("url").textContent = details.url;
    if (details.target) {
        document.getElementById("target").textContent = details.target;
        document.getElementById("targetBlock").classList.remove("hidden");
    } else {
        document.getElementById("targetBlock").classList.add("hidden");
    }
    let editLink = browser.runtime.getURL("src/options/options.html") + "?edit=";
    if (typeof details.rules === "undefined") {
        editLink += details.rule.uuid;
    } else {
        editLink += details.rules.map(rule => rule.uuid).join("&edit=");
    }
    document.getElementById("editLink").href = editLink;
}

function copyText(e) {
    let range = document.createRange();
    let text = document.getElementById(e.currentTarget.dataset.copyTarget);
    range.selectNodeContents(text);
    let selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand("Copy");
    e.currentTarget.classList.add("copied");
}

function copied(e) {
    e.currentTarget.classList.remove("copied");
}

function openOptionsPage() {
    browser.runtime.openOptionsPage();
    window.close();
}

function toggleActive() {
    myOptionsManager.saveOption("disabled", !myOptionsManager.options.disabled);
    setEnabled(!myOptionsManager.options.disabled);
}

function setEnabled(enabled) {
    let button = document.getElementById("toggleActive");
    let textId = enabled ? "activate_false" : "activate_true";
    let titleId = enabled ? "disable_rules" : "enable_rules";
    button.classList.toggle("disabled", !enabled);
    button.textContent = browser.i18n.getMessage(textId);
    button.title = browser.i18n.getMessage(titleId);
}

document.addEventListener("DOMContentLoaded", function () {
    myOptionsManager.loadOptions().then(function () {
        if (myOptionsManager.options.disabled) {
            setEnabled(false);
            return Promise.reject("");
        } else {
            return browser.runtime.sendMessage(null);
        }
    }).then(records => {
        setEnabled(true);
        if (myOptionsManager.options.rules) {
            setRecords(records);
        }
        let copyButtons = document.getElementsByClassName("copyButton");
        for (let copyButton of copyButtons) {
            copyButton.addEventListener("click", copyText);
            copyButton.addEventListener("mouseleave", copied);
        }
    });

    document.getElementById("showRules").addEventListener("click", openOptionsPage);
    document.getElementById("toggleActive").addEventListener("click", toggleActive);
    document.getElementById("editLink").addEventListener("click", function (e) {
        e.preventDefault();
        browser.tabs.create({
            url: this.href
        });
        window.close();
    });
});
<|endoftext|>


<commit_before>/**
* @version		$Id: validate.js 7401 2007-05-14 04:12:55Z eddieajau $
* @package		Joomla
* @copyright	Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/

/**
 * Unobtrusive Form Validation library
 *
 * Inspired by: Chris Campbell <www.particletree.com>
 *
 * @package		Joomla.Framework
 * @subpackage	Forms
 * @since		1.5
 */
var JFormValidator = new Class({
	initialize: function()
	{
		// Initialize variables
		this.handlers	= Object();
		this.custom		= Object();

		// Default handlers
		this.setHandler('username',
			function (value) {
				regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i");
				return !regex.test(value);
			}
		);

		this.setHandler('password',
			function (value) {
				regex=/^\S[\S ]{2,98}\S$/;
				return regex.test(value);
			}
		);

		this.setHandler('numeric',
			function (value) {
				regex=/^(\d|-)?(\d|,)*\.?\d*$/;
				return regex.test(value);
			}
		);

		this.setHandler('email',
			function (value) {
				regex=/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
				return regex.test(value);
			}
		);

		// Attach to forms with class 'form-validate'
		var forms = $$('form.form-validate');
		forms.each(function(form){ this.attachToForm(form); }, this);
	},

	setHandler: function(name, fn, en)
	{
		en = (en == '') ? true : en;
		this.handlers[name] = { enabled: en, exec: fn };
	},

	attachToForm: function(form)
	{
		// Iterate through the form object and attach the validate method to all input fields.
		$A(form.elements).each(function(el){
			el = $(el);
			if ((el.getTag() == 'input' || el.getTag() == 'button') && el.getProperty('type') == 'submit') {
				if (el.hasClass('validate')) {
					el.onclick = function(){return document.formvalidator.isValid(this.form);};
				}
			} else {
				el.addEvent('blur', function(){return document.formvalidator.validate(this);});
			}
		});
	},

	validate: function(el)
	{
		// If the field is required make sure it has a value
		if ($(el).hasClass('required')) {
			if (!($(el).getValue())) {
				this.handleResponse(false, el);
				return false;
			}
		}

		// Only validate the field if the validate class is set
		var handler = (el.className && el.className.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? el.className.match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : "";
		if (handler == '') {
			this.handleResponse(true, el);
			return true;
		}

		// Check the additional validation types
		if ((handler) && (handler != 'none') && (this.handlers[handler]) && $(el).getValue()) {
			// Execute the validation handler and return result
			if (this.handlers[handler].exec($(el).getValue()) != true) {
				this.handleResponse(false, el);
				return false;
			}
		}

		// Return validation state
		this.handleResponse(true, el);
		return true;
	},

	isValid: function(form)
	{
		var valid = true;

		// Validate form fields
		for (var i=0;i < form.elements.length; i++) {
			if (this.validate(form.elements[i]) == false) {
				valid = false;
			}
		}

		// Run custom form validators if present
		$A(this.custom).each(function(validator){
			if (validator.exec() != true) {
				valid = false;
			}
		});

		return valid;
	},

	handleResponse: function(state, el)
	{
		// Find the label object for the given field if it exists
		if (!(el.labelref)) {
			var labels = $$('label');
			labels.each(function(label){
				if (label.getProperty('for') == el.getProperty('id')) {
					el.labelref = label;
				}
			});
		}

		// Set the element and its label (if exists) invalid state
		if (state == false) {
			el.addClass('invalid');
			if (el.labelref) {
				$(el.labelref).addClass('invalid');
			}
		} else {
			el.removeClass('invalid');
			if (el.labelref) {
				$(el.labelref).removeClass('invalid');
			}
		}
	}
});

document.formvalidator = null;
Window.onDomReady(function(){
	document.formvalidator = new JFormValidator();
});<commit_msg>re #76 dollar safe mode<commit_after>/**
* @version		$Id: validate.js 7401 2007-05-14 04:12:55Z eddieajau $
* @package		Joomla
* @copyright	Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/

/**
 * Unobtrusive Form Validation library
 *
 * Inspired by: Chris Campbell <www.particletree.com>
 *
 * @package		Joomla.Framework
 * @subpackage	Forms
 * @since		1.5
 */
var JFormValidator = new Class({
	initialize: function()
	{
		// Initialize variables
		this.handlers	= Object();
		this.custom		= Object();

		// Default handlers
		this.setHandler('username',
			function (value) {
				regex = new RegExp("[\<|\>|\"|\'|\%|\;|\(|\)|\&]", "i");
				return !regex.test(value);
			}
		);

		this.setHandler('password',
			function (value) {
				regex=/^\S[\S ]{2,98}\S$/;
				return regex.test(value);
			}
		);

		this.setHandler('numeric',
			function (value) {
				regex=/^(\d|-)?(\d|,)*\.?\d*$/;
				return regex.test(value);
			}
		);

		this.setHandler('email',
			function (value) {
				regex=/^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
				return regex.test(value);
			}
		);

		// Attach to forms with class 'form-validate'
		var forms = $$('form.form-validate');
		forms.each(function(form){ this.attachToForm(form); }, this);
	},

	setHandler: function(name, fn, en)
	{
		en = (en == '') ? true : en;
		this.handlers[name] = { enabled: en, exec: fn };
	},

	attachToForm: function(form)
	{
		// Iterate through the form object and attach the validate method to all input fields.
		$A(form.elements).each(function(el){
			el = document.id(el);
			if ((el.getTag() == 'input' || el.getTag() == 'button') && el.getProperty('type') == 'submit') {
				if (el.hasClass('validate')) {
					el.onclick = function(){return document.formvalidator.isValid(this.form);};
				}
			} else {
				el.addEvent('blur', function(){return document.formvalidator.validate(this);});
			}
		});
	},

	validate: function(el)
	{
		// If the field is required make sure it has a value
		if (document.id(el).hasClass('required')) {
			if (!(document.id(el).getValue())) {
				this.handleResponse(false, el);
				return false;
			}
		}

		// Only validate the field if the validate class is set
		var handler = (el.className && el.className.search(/validate-([a-zA-Z0-9\_\-]+)/) != -1) ? el.className.match(/validate-([a-zA-Z0-9\_\-]+)/)[1] : "";
		if (handler == '') {
			this.handleResponse(true, el);
			return true;
		}

		// Check the additional validation types
		if ((handler) && (handler != 'none') && (this.handlers[handler]) && document.id(el).getValue()) {
			// Execute the validation handler and return result
			if (this.handlers[handler].exec(document.id(el).getValue()) != true) {
				this.handleResponse(false, el);
				return false;
			}
		}

		// Return validation state
		this.handleResponse(true, el);
		return true;
	},

	isValid: function(form)
	{
		var valid = true;

		// Validate form fields
		for (var i=0;i < form.elements.length; i++) {
			if (this.validate(form.elements[i]) == false) {
				valid = false;
			}
		}

		// Run custom form validators if present
		$A(this.custom).each(function(validator){
			if (validator.exec() != true) {
				valid = false;
			}
		});

		return valid;
	},

	handleResponse: function(state, el)
	{
		// Find the label object for the given field if it exists
		if (!(el.labelref)) {
			var labels = $$('label');
			labels.each(function(label){
				if (label.getProperty('for') == el.getProperty('id')) {
					el.labelref = label;
				}
			});
		}

		// Set the element and its label (if exists) invalid state
		if (state == false) {
			el.addClass('invalid');
			if (el.labelref) {
				document.id(el.labelref).addClass('invalid');
			}
		} else {
			el.removeClass('invalid');
			if (el.labelref) {
				document.id(el.labelref).removeClass('invalid');
			}
		}
	}
});

document.formvalidator = null;
Window.onDomReady(function(){
	document.formvalidator = new JFormValidator();
});<|endoftext|>


<commit_before>var GameState = require('./gamestate');
var Rates = require('./rates');
var RankingService = require('./rankingservice');

module.exports = {
    apply: function(game_state_data) {
        var gameState = new GameState(game_state_data),
            rate = gameState.rateHand();

        if (rate === Rates.VERY_GOOD) {
            return gameState.getMinimumRaise() + 200;
        }

        if (gameState.isPreFlopState() && (rate === Rates.GOOD)) {
            return gameState.getHoldValue();

        } else if (rate === Rates.GOOD) {
            var cards = gameState.getHand().concat(gameState.data.community_cards),
                rankingStat = RankingService.fetch(cards);

            if (rankingStat.rank >= 2) {
                return gameState.getMinimumRaise() + 200;
            }

            return gameState.getHoldValue();
        }

        return 0;
    }
};<commit_msg>Revert Super AI<commit_after>var GameState = require('./gamestate');
var Rates = require('./rates');
var RankingService = require('./rankingservice');

module.exports = {
    apply: function(game_state_data) {
        var gameState = new GameState(game_state_data),
            rate = gameState.rateHand();

        if (rate === Rates.VERY_GOOD) {
            return gameState.getMinimumRaise() + 200;
        }

        if (gameState.isPreFlopState() && (rate === Rates.GOOD)) {
            return gameState.getMinimumRaise();

        } else if (rate === Rates.GOOD) {
            var cards = gameState.getHand().concat(gameState.data.community_cards),
                rankingStat = RankingService.fetch(cards);

            if (rankingStat.rank >= 2) {
                return gameState.getMinimumRaise() + 200;
            }

            return gameState.getHoldValue();
        }

        return 0;
    }
};<|endoftext|>


<commit_before><commit_msg>Remove unneeded comments<commit_after><|endoftext|>


<commit_before>require('shelljs/make');
require('shelljs/global');

// Targets

target.all = function () {
  target.test();
  target.minify();
  target.boilerplate();
};

target.highlighter = function () {
  console.log('Bundling highlighter...');

  rm('-rf', 'vendor/highlight.js');
  mkdir('-p', 'vendor');
  pushd('vendor');
  exec('git clone https://github.com/isagalaev/highlight.js.git');
  pushd('highlight.js');
  exec('git checkout tags/9.6.0');
  popd();
  popd();

  bundleHighlighter('src/remark/highlighter.js');
};

target.test = function () {
  target['lint']();
  target['bundle']();
  target['test-bundle']();

  console.log('Running tests...');
  run('mocha-phantomjs test/runner.html', true);
};

target.lint = function () {
  console.log('Linting...');
  run('jshint src');
};

target.bundle = function () {
  console.log('Bundling...');
  bundleResources('src/remark/resources.js');

  mkdir('-p', 'out');

  run('browserify ' + components() + ' src/remark.js').stdout.to('out/remark.js');
};

function components () {
  var componentsPath = './src/remark/components';

  return ls(componentsPath)
    .map(function (component) {
      return '-r ' + componentsPath + '/' + component + '/' + component +
        '.js:' + 'components/' + component;
    })
    .join(' ');
}

target['test-bundle'] = function () {
  console.log('Bundling tests...');

  [
    "require('should');",
    "require('sinon');",
    "require('should-sinon');"
  ]
    .concat(find('./test')
      .filter(function(file) { return file.match(/\.js$/); })
      .map(function (file) { return "require('./" + file + "');" })
    )
      .join('\n')
      .to('_tests.js');

  run('browserify ' + components() + ' _tests.js').stdout.to('out/tests.js');
  rm('_tests.js');
};

target.boilerplate = function () {
  console.log('Generating boilerplate...');
  generateBoilerplateSingle("boilerplate-single.html");
};

target.minify = function () {
  console.log('Minifying...');
  run('uglifyjs -m -c -o out/remark.min.js out/remark.js');
};

target.deploy = function () {
  var currentBranch = git('branch')
    .split('\n')
    .filter(function (line) {
      return line[0] === '*';
    })[0]
    .substr(2);

  var version = require('./package.json').version;
  var tagForVersion = git('tag -l v' + version);

  if (tagForVersion) {
    console.log('Update version in package.json before deploying.');
    return;
  }

  git('add package.json');
  git('add -f out');
  git('checkout head');
  git('commit -m "Deploy version ' + version + '."');
  git('tag -a v' + version + ' -m "Version ' + version + '."');
  git('checkout ' + currentBranch);
  git('push origin --tags');
};

// Helper functions

var path = require('path')
  , package = require('./package.json')
  , version = package.version
  , config = package.config
  , ignoredStyles = ['brown_paper', 'school_book', 'pojoaque']
  ;

function bundleResources (target) {
  var resources = {
        VERSION: version
      , DOCUMENT_STYLES: JSON.stringify(
          less('src/remark.less'))
      , CONTAINER_LAYOUT: JSON.stringify(
          cat('src/remark.html'))
      };

  cat('src/templates/resources.js.template')
    .replace(/%(\w+)%/g, function (match, key) {
      return resources[key];
    })
    .to(target);
}

function bundleHighlighter (target) {
  var highlightjs = 'vendor/highlight.js/src/'
    , resources = {
        HIGHLIGHTER_STYLES: JSON.stringify(
          ls(highlightjs + 'styles/*.css').reduce(mapStyle, {}))
      , HIGHLIGHTER_ENGINE:
          cat(highlightjs + 'highlight.js')
      , HIGHLIGHTER_LANGUAGES:
          ls(highlightjs + 'languages/*.js')
            .sort(function (a, b) {
              // Other languages depend on cpp, so put it first
              return a.indexOf('cpp.js') !== -1 ? -1 : 0;
            })
            .map(function (file) {
              var language = path.basename(file, path.extname(file))
              return '{name:"' + language + '",create:' + cat(file) + '}';
            }).join(',')
      };

  cat('src/templates/highlighter.js.template')
    .replace(/%(\w+)%/g, function (match, key) {
      return resources[key];
    })
    .to(target);
}

function generateBoilerplateSingle(target) {
  var resources = {
        REMARK_MINJS: escape(cat('out/remark.min.js')
                              // highlighter has a ending script tag as a string literal, and
                              // that causes early termination of escaped script. Split that literal.
                              .replace('"</script>"', '"</" + "script>"'))
      };

  cat('src/templates/boilerplate-single.html.template')
    .replace(/%(\w+)%/g, function (match, key) {
      return resources[key];
    })
    .to(target);
}

function mapStyle (map, file) {
  var key = path.basename(file, path.extname(file))
    , tmpfile = path.join(tempdir(), 'remark.tmp')
    ;

  if (ignoredStyles.indexOf(key) === -1) {
    ('.hljs-' + key + ' {\n' + cat(file) + '\n}').to(tmpfile);
    map[key] = less(tmpfile);
    rm(tmpfile);
  }

  return map;
}

function less (file) {
  return run('lessc -x -s ' + file).stdout.replace(/\n/g, '');
}

function git (cmd) {
  return exec('git ' + cmd, {silent: true}).stdout;
}

function run (command, loud) {
  var result = exec(pwd() + '/node_modules/.bin/' + command, {silent: !loud, fatal: false});

  if (result.code !== 0) {
    if (!options || options.silent) {
      console.error(result.stdout);
    }
    exit(1);
  }

  return result;
}
<commit_msg>#379: Enable excluding highlight.js from build.<commit_after>require('shelljs/make');
require('shelljs/global');

// Targets

target.all = function () {
  target.test();
  target.minify();
  target.boilerplate();
};

target.highlighter = function () {
  var config = require('./package.json').config;
  if (config && config.highlighter === false) {
    console.log('Bundling empty highlighter skeleton...');
    "module.exports = {styles:[],engine:{highlightBlock:function(){}}};"
      .to('src/remark/highlighter.js');
    return;
  }

  console.log('Bundling highlighter...');

  rm('-rf', 'vendor/highlight.js');
  mkdir('-p', 'vendor');
  pushd('vendor');
  exec('git clone https://github.com/isagalaev/highlight.js.git');
  pushd('highlight.js');
  exec('git checkout tags/9.6.0');
  popd();
  popd();

  bundleHighlighter('src/remark/highlighter.js');
};

target.test = function () {
  target['lint']();
  target['bundle']();
  target['test-bundle']();

  console.log('Running tests...');
  run('mocha-phantomjs test/runner.html', true);
};

target.lint = function () {
  console.log('Linting...');
  run('jshint src');
};

target.bundle = function () {
  console.log('Bundling...');
  bundleResources('src/remark/resources.js');

  mkdir('-p', 'out');

  run('browserify ' + components() + ' src/remark.js').stdout.to('out/remark.js');
};

function components () {
  var componentsPath = './src/remark/components';

  return ls(componentsPath)
    .map(function (component) {
      return '-r ' + componentsPath + '/' + component + '/' + component +
        '.js:' + 'components/' + component;
    })
    .join(' ');
}

target['test-bundle'] = function () {
  console.log('Bundling tests...');

  [
    "require('should');",
    "require('sinon');",
    "require('should-sinon');"
  ]
    .concat(find('./test')
      .filter(function(file) { return file.match(/\.js$/); })
      .map(function (file) { return "require('./" + file + "');" })
    )
      .join('\n')
      .to('_tests.js');

  run('browserify ' + components() + ' _tests.js').stdout.to('out/tests.js');
  rm('_tests.js');
};

target.boilerplate = function () {
  console.log('Generating boilerplate...');
  generateBoilerplateSingle("boilerplate-single.html");
};

target.minify = function () {
  console.log('Minifying...');
  run('uglifyjs -m -c -o out/remark.min.js out/remark.js');
};

target.deploy = function () {
  var currentBranch = git('branch')
    .split('\n')
    .filter(function (line) {
      return line[0] === '*';
    })[0]
    .substr(2);

  var version = require('./package.json').version;
  var tagForVersion = git('tag -l v' + version);

  if (tagForVersion) {
    console.log('Update version in package.json before deploying.');
    return;
  }

  git('add package.json');
  git('add -f out');
  git('checkout head');
  git('commit -m "Deploy version ' + version + '."');
  git('tag -a v' + version + ' -m "Version ' + version + '."');
  git('checkout ' + currentBranch);
  git('push origin --tags');
};

// Helper functions

var path = require('path')
  , package = require('./package.json')
  , version = package.version
  , config = package.config
  , ignoredStyles = ['brown_paper', 'school_book', 'pojoaque']
  ;

function bundleResources (target) {
  var resources = {
        VERSION: version
      , DOCUMENT_STYLES: JSON.stringify(
          less('src/remark.less'))
      , CONTAINER_LAYOUT: JSON.stringify(
          cat('src/remark.html'))
      };

  cat('src/templates/resources.js.template')
    .replace(/%(\w+)%/g, function (match, key) {
      return resources[key];
    })
    .to(target);
}

function bundleHighlighter (target) {
  var highlightjs = 'vendor/highlight.js/src/'
    , resources = {
        HIGHLIGHTER_STYLES: JSON.stringify(
          ls(highlightjs + 'styles/*.css').reduce(mapStyle, {}))
      , HIGHLIGHTER_ENGINE:
          cat(highlightjs + 'highlight.js')
      , HIGHLIGHTER_LANGUAGES:
          ls(highlightjs + 'languages/*.js')
            .sort(function (a, b) {
              // Other languages depend on cpp, so put it first
              return a.indexOf('cpp.js') !== -1 ? -1 : 0;
            })
            .map(function (file) {
              var language = path.basename(file, path.extname(file))
              return '{name:"' + language + '",create:' + cat(file) + '}';
            }).join(',')
      };

  cat('src/templates/highlighter.js.template')
    .replace(/%(\w+)%/g, function (match, key) {
      return resources[key];
    })
    .to(target);
}

function generateBoilerplateSingle(target) {
  var resources = {
        REMARK_MINJS: escape(cat('out/remark.min.js')
                              // highlighter has a ending script tag as a string literal, and
                              // that causes early termination of escaped script. Split that literal.
                              .replace('"</script>"', '"</" + "script>"'))
      };

  cat('src/templates/boilerplate-single.html.template')
    .replace(/%(\w+)%/g, function (match, key) {
      return resources[key];
    })
    .to(target);
}

function mapStyle (map, file) {
  var key = path.basename(file, path.extname(file))
    , tmpfile = path.join(tempdir(), 'remark.tmp')
    ;

  if (ignoredStyles.indexOf(key) === -1) {
    ('.hljs-' + key + ' {\n' + cat(file) + '\n}').to(tmpfile);
    map[key] = less(tmpfile);
    rm(tmpfile);
  }

  return map;
}

function less (file) {
  return run('lessc -x -s ' + file).stdout.replace(/\n/g, '');
}

function git (cmd) {
  return exec('git ' + cmd, {silent: true}).stdout;
}

function run (command, loud) {
  var result = exec(pwd() + '/node_modules/.bin/' + command, {silent: !loud, fatal: false});

  if (result.code !== 0) {
    if (!options || options.silent) {
      console.error(result.stdout);
    }
    exit(1);
  }

  return result;
}
<|endoftext|>


<commit_before>/*!
 * CallWithName v1.0
 *
 * Copyright 2015, Himanshu Tanwar
 * Released under the MIT license
 * https://github.com/webXtended/callWithName
 * Date: 2017-03-16
 */
var callWithName = function(name, fn, options){
    var context,errorMsg,nameType = typeof name, fnType = typeof fn;
    options = options || {};
    if(nameType === 'string' && fnType === 'function'){
        context = options.context || window;
        context[name] = fn;
        context[name].toString = function(){
            var sendBack = fn.call(context);
            return sendBack || options.returnValue ||undefined;
        }
    }else{
        errorMsg = [];
        errorMsg.push("cannot assign");
        errorMsg.push(nameType);
        errorMsg.push("to a");
        errorMsg.push(fnType);
        console.error(errorMsg.join(" "));
        console.info("Pass a string for name and a function to associate it with the name");
        console.info("for more details visit https://github.com/webXtended/callWithName");
    }
};
<commit_msg>Update callWithName.js<commit_after>/*!
 * CallWithName v1.0
 *
 * Copyright 2015, Himanshu Tanwar
 * Released under the MIT license
 * https://github.com/webXtended/callWithName
 * Date: 2017-03-16
 */
var callWithName = function(name, fn, options){
    var context,errorMsg,nameType = typeof name, fnType = typeof fn;
    options = options || {};
    if(nameType === 'string' && fnType === 'function'){
        context = options.context || window;
        context[name] = fn;
        context[name].toString = function(){
            var sendBack = fn.call(context);
            return sendBack || options.returnValue ||undefined;
        }
    }else{
        errorMsg = [];
        errorMsg.push("cannot assign");
        errorMsg.push(nameType);
        errorMsg.push("to a");
        errorMsg.push(fnType);
        console.error(errorMsg.join(" "));
        console.info("Pass a string for name and a function to associate it with the name");
        console.info("for more details visit https://github.com/webXtended/callWithName");
    }
};

callWithName.toString = function(){
    return "callWithName is a mini JS library for calling functions without use of ()." +
        "\nMore info at https://github.com/webXtended/callWithName";
};
<|endoftext|>