<commit_before>/* eslint no-undefined: 0 */

'use strict';

const path      = require('path');
const assert    = require('assert');
const walk      = require('fs-walk');
const semver    = require('semver');
const digest    = require('../lib/helpers.js').sri.digest;
const helpers   = require('./test_helpers.js');

const config    = helpers.getConfig();

const expectedHeaders = {
    'accept-ranges': 'bytes',
    'access-control-allow-origin': '*',
    'cache-control': 'max-age=31536000',
    'connection': 'Keep-Alive',
    'content-encoding': 'gzip',
    'content-length': undefined,
    'content-type': undefined,
    'date': undefined,
    'etag': undefined,
    'last-modified': undefined,
    'vary': 'Accept-Encoding',
    'x-cache': undefined,
    'x-hello-human': 'Say hello back! @getBootstrapCDN on Twitter'
};

const responses = {};

function request(uri, cb) {
    // return memoized response to avoid making the same http call twice
    if (Object.prototype.hasOwnProperty.call(responses, uri)) {
        return cb(responses[uri]);
    }

    // build memoized response
    return helpers.preFetch(uri, (res) => {
        responses[uri] = res;
        cb(res);
    });
}

function assertSRI(uri, sri, done) {
    const expected = digest(responses[uri].body, true);

    assert.equal(expected, sri);
    done();
}

const s3include = ['content-type'];

function assertHeader(uri, header, value) {
    if (typeof process.env.TEST_S3 !== 'undefined' && !s3include.includes(header)) {
        it.skip(`has ${header}`);
    } else {
        it(`has ${header}`, (done) => {
            assert(Object.prototype.hasOwnProperty.call(responses[uri].headers, header),
                `Expects "${header}" in: ${Object.keys(responses[uri].headers).join(', ')}`);

            if (typeof value !== 'undefined') {
                assert.equal(responses[uri].headers[header], value);
            } else if (expectedHeaders[header]) {
                assert.equal(responses[uri].headers[header], expectedHeaders[header]);
            }

            done();
        });
    }
}

describe('functional', () => {
    config.bootstrap.forEach((self) => {
        describe(helpers.domainCheck(self.javascript), () => {
            const uri = helpers.domainCheck(self.javascript);

            it('it works', (done) => {
                request(uri, () => {
                    helpers.assert.itWorks(responses[uri].statusCode, done);
                });
            });

            Object.keys(expectedHeaders).forEach((header) => {
                assertHeader(uri, header);
            });

            assertHeader(uri, 'content-type', 'application/javascript; charset=utf-8');

            it('has integrity', (done) => {
                assertSRI(uri, self.javascriptSri, done);
            });
        });

        if (self.javascriptBundle) {
            describe(helpers.domainCheck(self.javascriptBundle), () => {
                const uri = helpers.domainCheck(self.javascriptBundle);

                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                Object.keys(expectedHeaders).forEach((header) => {
                    assertHeader(uri, header);
                });

                assertHeader(uri, 'content-type', 'application/javascript; charset=utf-8');

                it('has integrity', (done) => {
                    assertSRI(uri, self.javascriptBundleSri, done);
                });
            });
        }

        describe(helpers.domainCheck(self.stylesheet), () => {
            const uri = helpers.domainCheck(self.stylesheet);

            it('it works', (done) => {
                request(uri, () => {
                    helpers.assert.itWorks(responses[uri].statusCode, done);
                });
            });

            Object.keys(expectedHeaders).forEach((header) => {
                assertHeader(uri, header);
            });

            assertHeader(uri, 'content-type', 'text/css; charset=utf-8');

            it('has integrity', (done) => {
                assertSRI(uri, self.stylesheetSri, done);
            });
        });
    });

    describe('bootswatch3', () => {
        config.bootswatch3.themes.forEach((theme) => {
            const uri = helpers.domainCheck(config.bootswatch3.bootstrap
                .replace('SWATCH_VERSION', config.bootswatch3.version)
                .replace('SWATCH_NAME', theme.name));

            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                Object.keys(expectedHeaders).forEach((header) => {
                    assertHeader(uri, header);
                });

                assertHeader(uri, 'content-type', 'text/css; charset=utf-8');

                it('has integrity', (done) => {
                    assertSRI(uri, theme.sri, done);
                });
            });
        });
    });

    describe('bootswatch4', () => {
        config.bootswatch4.themes.forEach((theme) => {
            const uri = helpers.domainCheck(config.bootswatch4.bootstrap
                .replace('SWATCH_VERSION', config.bootswatch4.version)
                .replace('SWATCH_NAME', theme.name));

            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                Object.keys(expectedHeaders).forEach((header) => {
                    assertHeader(uri, header);
                });

                assertHeader(uri, 'content-type', 'text/css; charset=utf-8');

                it('has integrity', (done) => {
                    assertSRI(uri, theme.sri, done);
                });
            });
        });
    });

    describe('bootlint', () => {
        config.bootlint.forEach((self) => {
            const uri = helpers.domainCheck(self.javascript);

            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                Object.keys(expectedHeaders).forEach((header) => {
                    assertHeader(uri, header);
                });

                assertHeader(uri, 'content-type', 'application/javascript; charset=utf-8');

                it('has integrity', (done) => {
                    assertSRI(uri, self.javascriptSri, done);
                });
            });
        });
    });

    describe('fontawesome', () => {
        config.fontawesome.forEach((self) => {
            const uri = helpers.domainCheck(self.stylesheet);

            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                Object.keys(expectedHeaders).forEach((header) => {
                    assertHeader(uri, header);
                });

                assertHeader(uri, 'content-type', 'text/css; charset=utf-8');

                it('has integrity', (done) => {
                    assertSRI(uri, self.stylesheetSri, done);
                });
            });
        });
    });

    describe('public/**/*.*', () => {
        // Build File List
        const whitelist = [
            'bootlint',
            'bootstrap',
            'bootswatch',
            'font-awesome',
            'twitter-bootstrap',
            'css',
            'js'
        ];

        const publicURIs = [];

        walk.filesSync(path.join(__dirname, '..', 'public'), (base, name) => {
            let root = base.split(`${path.sep}public${path.sep}`)[1];

            // ensure file is in whitelisted directory
            if (typeof root === 'undefined' || !whitelist.includes(root.split(path.sep)[0])) {
                return;
            }

            // replace Windows backslashes with forward ones
            root = root.replace(/\\/g, '/');
            const domain = helpers.domainCheck('https://stackpath.bootstrapcdn.com/');
            const uri = `${domain + root}/${name}`;

            // ignore twitter-bootstrap versions after 2.3.2
            if (uri.includes('twitter-bootstrap')) {
                const m = uri.match(/(\d+\.\d+\.\d+)/);

                // err on the side of testing things that can't be abstracted
                if (m && m[1] && semver.valid(m[1]) && semver.gt(m[1], '2.3.2')) {
                    return; // don't add the file
                }
            }

            publicURIs.push(uri);
        });

        // Run Tests
        for (const uri of publicURIs) {
            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                it('has content-type', (done) => {
                    helpers.assert.contentType(uri, responses[uri].headers['content-type'], done);
                });
            });
        }
    });
});
<commit_msg>Test all public files for proper headers.<commit_after>/* eslint no-undefined: 0 */

'use strict';

const path      = require('path');
const assert    = require('assert');
const walk      = require('fs-walk');
const semver    = require('semver');
const digest    = require('../lib/helpers.js').sri.digest;
const helpers   = require('./test_helpers.js');

const config    = helpers.getConfig();

const expectedHeaders = {
    'accept-ranges': 'bytes',
    'access-control-allow-origin': '*',
    'cache-control': 'max-age=31536000',
    'connection': 'Keep-Alive',
    'content-encoding': 'gzip',
    'content-length': undefined,
    'date': undefined,
    'etag': undefined,
    'last-modified': undefined,
    'vary': 'Accept-Encoding',
    'x-cache': undefined,
    'x-hello-human': 'Say hello back! @getBootstrapCDN on Twitter'
};

const responses = {};

function request(uri, cb) {
    // return memoized response to avoid making the same http call twice
    if (Object.prototype.hasOwnProperty.call(responses, uri)) {
        return cb(responses[uri]);
    }

    // build memoized response
    return helpers.preFetch(uri, (res) => {
        responses[uri] = res;
        cb(res);
    });
}

function assertSRI(uri, sri, done) {
    const expected = digest(responses[uri].body, true);

    assert.equal(expected, sri);
    done();
}

const s3include = ['content-type'];

function assertHeaders(uri, header, value) {
    if (typeof process.env.TEST_S3 !== 'undefined' && !s3include.includes(header)) {
        it.skip(`has ${header}`);
    } else {
        it(`has ${header}`, (done) => {
            assert(Object.prototype.hasOwnProperty.call(responses[uri].headers, header),
                `Expects "${header}" in: ${Object.keys(responses[uri].headers).join(', ')}`);

            if (typeof value !== 'undefined') {
                assert.equal(responses[uri].headers[header], value);
            } else if (expectedHeaders[header]) {
                assert.equal(responses[uri].headers[header], expectedHeaders[header]);
            }

            done();
        });
    }
}

describe('functional', () => {
    config.bootstrap.forEach((self) => {
        describe(helpers.domainCheck(self.javascript), () => {
            const uri = helpers.domainCheck(self.javascript);

            it('it works', (done) => {
                request(uri, () => {
                    helpers.assert.itWorks(responses[uri].statusCode, done);
                });
            });

            it('has integrity', (done) => {
                assertSRI(uri, self.javascriptSri, done);
            });
        });

        if (self.javascriptBundle) {
            describe(helpers.domainCheck(self.javascriptBundle), () => {
                const uri = helpers.domainCheck(self.javascriptBundle);

                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                it('has integrity', (done) => {
                    assertSRI(uri, self.javascriptBundleSri, done);
                });
            });
        }

        describe(helpers.domainCheck(self.stylesheet), () => {
            const uri = helpers.domainCheck(self.stylesheet);

            it('it works', (done) => {
                request(uri, () => {
                    helpers.assert.itWorks(responses[uri].statusCode, done);
                });
            });

            it('has integrity', (done) => {
                assertSRI(uri, self.stylesheetSri, done);
            });
        });
    });

    describe('bootswatch3', () => {
        config.bootswatch3.themes.forEach((theme) => {
            const uri = helpers.domainCheck(config.bootswatch3.bootstrap
                .replace('SWATCH_VERSION', config.bootswatch3.version)
                .replace('SWATCH_NAME', theme.name));

            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                it('has integrity', (done) => {
                    assertSRI(uri, theme.sri, done);
                });
            });
        });
    });

    describe('bootswatch4', () => {
        config.bootswatch4.themes.forEach((theme) => {
            const uri = helpers.domainCheck(config.bootswatch4.bootstrap
                .replace('SWATCH_VERSION', config.bootswatch4.version)
                .replace('SWATCH_NAME', theme.name));

            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                it('has integrity', (done) => {
                    assertSRI(uri, theme.sri, done);
                });
            });
        });
    });

    describe('bootlint', () => {
        config.bootlint.forEach((self) => {
            const uri = helpers.domainCheck(self.javascript);

            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                it('has integrity', (done) => {
                    assertSRI(uri, self.javascriptSri, done);
                });
            });
        });
    });

    describe('fontawesome', () => {
        config.fontawesome.forEach((self) => {
            const uri = helpers.domainCheck(self.stylesheet);

            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                it('has integrity', (done) => {
                    assertSRI(uri, self.stylesheetSri, done);
                });
            });
        });
    });

    describe('public/**/*.*', () => {
        // Build File List
        const whitelist = [
            'bootlint',
            'bootstrap',
            'bootswatch',
            'font-awesome',
            'twitter-bootstrap',
            'css',
            'js'
        ];

        const publicURIs = [];

        walk.filesSync(path.join(__dirname, '..', 'public'), (base, name) => {
            let root = base.split(`${path.sep}public${path.sep}`)[1];

            // ensure file is in whitelisted directory
            if (typeof root === 'undefined' || !whitelist.includes(root.split(path.sep)[0])) {
                return;
            }

            // replace Windows backslashes with forward ones
            root = root.replace(/\\/g, '/');
            const domain = helpers.domainCheck('https://stackpath.bootstrapcdn.com/');
            const uri = `${domain + root}/${name}`;

            // ignore twitter-bootstrap versions after 2.3.2
            if (uri.includes('twitter-bootstrap')) {
                const m = uri.match(/(\d+\.\d+\.\d+)/);

                // err on the side of testing things that can't be abstracted
                if (m && m[1] && semver.valid(m[1]) && semver.gt(m[1], '2.3.2')) {
                    return; // don't add the file
                }
            }

            publicURIs.push(uri);
        });

        // Run Tests
        for (const uri of publicURIs) {
            describe(uri, () => {
                it('it works', (done) => {
                    request(uri, () => {
                        helpers.assert.itWorks(responses[uri].statusCode, done);
                    });
                });

                Object.keys(expectedHeaders).forEach((header) => {
                    assertHeaders(uri, header);
                });

                it(`has content-type (${uri})`, (done) => {
                    helpers.assert.contentType(uri, responses[uri].headers['content-type'], done);
                });
            });
        }
    });
});
<|endoftext|>


<commit_before>var oldVal = "";
var newVal = "";
var thisObj = null;
var timeout;
var l;
var working = false;
var tabbed = false;

function btnConfirm(btnThis){
    if(!working){
        l = Ladda.create(btnThis);
        l.start();
        working = true;
        clearTimeout(timeout);
        $('#alertbox').fadeOut(100);

        $.ajax({
            type: "GET",
            url: '?p=json&r=edit&d='+(thisObj.parent().parent().attr('id'))+'&f='+(thisObj.parent().index())+'&n='+newVal
        }).done(handleresponse).fail(function(){console.log('Something has gone very wrong');btnDeny();});
    }
}

function btnDeny(btnThis){
    if(thisObj != null){
        thisObj.popover('destroy');
        thisObj.html(oldVal);
        thisObj = null;
    }
    if (tabbed)
        $(this).parent().next().children('.editable').click();
}

$(".editable").click( function(){
    if( $(this).children().length == 0 && thisObj == null ){
        oldVal = $(this).text();
        $(this).html('<input type="text" class="form-control edit input-sm" value="'+ $(this).text() +'" autocomplete="off">');
        $("input.form-control.edit").focus();
        $("input.edit").on('focusout keypress',
            function(e){
                if (e.type === "focusout" || e.which === 13 || e.which === 9) {
                    if (e.which === 9)
                        tabbed = true;
                    if (oldVal !== $(this).val()) {
                        thisObj = $(this).parent();
                        thisObj.popover({
                            placement: 'bottom',
                            html: 'true',
                            trigger: 'manual',
                            title: 'Confirm edit',
                            content: '
<button type="button" class="btn btn-default ladda-button" data-style="slide-up" onclick="btnConfirm(this)">Yes</button><button type="button" class="btn btn-default ladda-button" data-style="slide-up" onclick="btnDeny(this)">No</button>
'
                        });
                        thisObj.popover('show');
                        newVal = $(this).val();
                        $('[data-style=slide-up]:eq(0)').focus();
                    }
                    $(this).replaceWith( $(this).val() );
                }
            }
        )
    }
});

handleresponse = function (msg) {
    l.stop();

    working = false;
    var level='danger';
    var title='';
    if(msg.code=="success"){
        thisObj.popover('destroy');
        thisObj = null;
        level='success';
        title='Edit saved';
    } else if(msg.code=="failure"){
        btnDeny();
        level='warning';
        title='Edit failed';
    } else if(msg.code=="nothing"){
        btnDeny();
        level='info';
        title='Nothing to update';
    } else {
        btnDeny();
        level='danger';
        title='Something broke...';
    }
    $('#alertbox').html('
'+title+'
');
    $('#alertbox').fadeIn(200);
    timeout=setTimeout(function(){$('#alertbox').fadeOut(100);},3000);
}
<commit_msg>add changes to tab check<commit_after>var oldVal = "";
var newVal = "";
var thisObj = null;
var timeout;
var l;
var working = false;
var tabbed = false;

function btnConfirm(btnThis){
    if(!working){
        l = Ladda.create(btnThis);
        l.start();
        working = true;
        clearTimeout(timeout);
        $('#alertbox').fadeOut(100);

        $.ajax({
            type: "GET",
            url: '?p=json&r=edit&d='+(thisObj.parent().parent().attr('id'))+'&f='+(thisObj.parent().index())+'&n='+newVal
        }).done(handleresponse).fail(function(){console.log('Something has gone very wrong');btnDeny();});
    }
}

function btnDeny(btnThis){
    if(thisObj != null){
        thisObj.popover('destroy');
        thisObj.html(oldVal);
        thisObj = null;
    }
    if (tabbed)
        $(this).parent().next().children('.editable').click();
    tabbed = false;
}

$(".editable").click( function(){
    if( $(this).children().length == 0 && thisObj == null ){
        oldVal = $(this).text();
        $(this).html('<input type="text" class="form-control edit input-sm" value="'+ $(this).text() +'" autocomplete="off">');
        $("input.form-control.edit").focus();
        $("input.edit").on('focusout keypress',
            function(e){
                if (e.type === "focusout" || e.which === 13 || e.which === 9) {
                    if (e.which === 9)
                        tabbed = true;
                    if (oldVal !== $(this).val()) {
                        thisObj = $(this).parent();
                        thisObj.popover({
                            placement: 'bottom',
                            html: 'true',
                            trigger: 'manual',
                            title: 'Confirm edit',
                            content: '
<button type="button" class="btn btn-default ladda-button" data-style="slide-up" onclick="btnConfirm(this)">Yes</button><button type="button" class="btn btn-default ladda-button" data-style="slide-up" onclick="btnDeny(this)">No</button>
'
                        });
                        thisObj.popover('show');
                        newVal = $(this).val();
                        $('[data-style=slide-up]:eq(0)').focus();
                        tabbed = true;
                    }
                    $(this).replaceWith( $(this).val() );
                }
            }
        )
    }
});

handleresponse = function (msg) {
    l.stop();

    working = false;
    var level='danger';
    var title='';
    if(msg.code=="success"){
        thisObj.popover('destroy');
        thisObj = null;
        level='success';
        title='Edit saved';
    } else if(msg.code=="failure"){
        btnDeny();
        level='warning';
        title='Edit failed';
    } else if(msg.code=="nothing"){
        btnDeny();
        level='info';
        title='Nothing to update';
    } else {
        btnDeny();
        level='danger';
        title='Something broke...';
    }
    $('#alertbox').html('
'+title+'
');
    $('#alertbox').fadeIn(200);
    timeout=setTimeout(function(){$('#alertbox').fadeOut(100);},3000);
}
<|endoftext|>


<commit_before>$.fn.showChartDataEntryTanggal = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,form){
        var x = [];
        var y = [];
        $.each(form,function(index,value){
            x.push(index);
            y.push(value);
        });
        user = user.replace(/ /g,"_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Jumlah Entry',
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryMinggu = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,weeks){
        var x = ['Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
        var y_now = [];
        var y_last = [];
        $.each(weeks,function(week,form){
            if(week=='thisweek'){
                $.each(form,function(index,value){
                    y_now.push(value);
                });
            }else{
                $.each(form,function(index,value){
                    y_last.push(value);
                });
            }

        });
        user = user.replace(/ /g,"_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Minggu Ini',
                    type: 'column',
                    data: y_now,
                    color: '#0000ff',
                    tooltip: {
                        valueSuffix: ''
                    }
                },{
                    name: 'Minggu Lalu',
                    type: 'column',
                    data: y_last,
                    color: '#ff0000',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryBulan = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,months){
        var x = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
        var y_now = [];
        var y_last = [];
        var thisyear = 0;
        var lastyear = 0;
        $.each(months,function(month,form){
            if(month=='thisyear'){
                $.each(form,function(index,value){
                    thisyear = index.split("-");
                    y_now.push(value);
                });
            }else{
                $.each(form,function(index,value){
                    lastyear = index.split("-");
                    y_last.push(value);
                });
            }

        });
        user = user.replace(/ /g,"_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Tahun '+thisyear[0],
                    type: 'column',
                    data: y_now,
                    color: '#0000ff',
                    tooltip: {
                        valueSuffix: ''
                    }
                },{
                    name: 'Tahun '+lastyear[0],
                    type: 'column',
                    data: y_last,
                    color: '#ff0000',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryForm = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,form){
        var x = [];
        var y = [];
        $.each(form,function(index,value){
            x.push(index);
            y.push(value);
        });
        user = user.replace(/ /g,"_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Jumlah Entry',
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChart = function(data){
    $.each(data,function(index1,data1){
        var id = data1['page'];
        var x = [];
        var y = [];
        $.each(data1['form'],function(index2,data2){
            x.push(index2);
            y.push(data2);
        });
        Highcharts.setOptions({
            lang: {
                decimalPoint: ',',
                thousandsSep: '.'
            }
        });

        $('#'+id).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,minrange:100},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: data1['y_label'],
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true,
                pointFormat: data1['y_label']+": {point.y:.2f} %"
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y:.2f}'
                    }
                }
            },
            series: [{
                    name: data1['series_name'],
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });
};

$.fn.showChartStack = function(data){
    $.each(data,function(index1,data1){
        var id = data1['page'];
        var x = [];
        var y1 = [];
        var y2 = [];
        $.each(data1['form'],function(index2,data2){
            x.push(index2);
            y1.push(data2['l']);
            y2.push(data2['p']);
        });
        Highcharts.setOptions({
            lang: {
                decimalPoint: ',',
                thousandsSep: '.'
            }
        });

        $('#'+id).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    stacking: 'normal',
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            tooltip: {
                formatter: function () {
                    return '' + this.x + '
' +
                        this.series.name + ': ' + this.y + '
' +
                        'Total: ' + this.point.stackTotal;
                }
            },
            series: [{
                    name: data1['series_name'][0],
                    type: 'column',
                    data: y1,
                    color: 'blue'
                },{
                    name: data1['series_name'][1],
                    type: 'column',
                    data: y2,
                    color: 'red'
                }]
        });
    });
};

$.fn.showChartStackDouble = function(data){
    $.each(data,function(index1,data1){
        var id = data1['page'];
        var x = [];
        var y1bl = [];
        var y2bl = [];
        var y1bi = [];
        var y2bi = [];
        $.each(data1['form'],function(index2,data2){
            x.push(index2);
            y1bl.push(data2['lbl']);
            y2bl.push(data2['pbl']);
            y1bi.push(data2['lbi']);
            y2bi.push(data2['pbi']);
        });
        Highcharts.setOptions({
            lang: {
                decimalPoint: ',',
                thousandsSep: '.'
            }
        });

        $('#'+id).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    stacking: 'normal',
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            tooltip: {
                formatter: function () {
                    return '' + this.series.options.stack + '
' +
                            '' + this.x + '
' +
                        this.series.name + ': ' + this.y + '
' +
                        'Total: ' + this.point.stackTotal;
                }
            },
            series: [{
                    name: data1['series_name'][0],
                    type: 'column',
                    data: y1bl,
                    color: 'green',
                    stack: data1['series_stack_name'][0]
                },{
                    name: data1['series_name'][1],
                    type: 'column',
                    data: y2bl,
                    color: 'yellow',
                    stack: data1['series_stack_name'][0]
                },{
                    name: data1['series_name'][0],
                    type: 'column',
                    data: y1bi,
                    color: 'blue',
                    stack: data1['series_stack_name'][1]
                },{
                    name: data1['series_name'][1],
                    type: 'column',
                    data: y2bi,
                    color: 'red',
                    stack: data1['series_stack_name'][1]
                }]
        });
    });
};<commit_msg>AH | add function for drilldown funtionality<commit_after>$.fn.showChartDataEntryTanggal = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,form){
        var x = [];
        var y = [];
        $.each(form,function(index,value){
            x.push(index);
            y.push(value);
        });
        user = user.replace(/ /g,"_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Jumlah Entry',
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryTanggalDrill = function(data,url){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,form){
        var x = [];
        var y = [];
        var drill = [];
        var a = 0;
        $.each(form,function(index,value){
            x.push(index);
            y.push({"name":index,"y":value,"drilldown":index});
        });
        //console.log(drill);
        user = user.replace(/ /g,"_");
        $('#'+user).highcharts({
            chart: {
                type: 'column',
                zoomType: 'xy',
                height: 400,
                events: {
                    drilldown: function (e) {
                        if (!e.seriesOptions) {

                            var chart = this,
                                drilldowns = [],
                                series = [];
                            $.get(url+"dataentry/getbidanByForm/"+user+"/"+e.point.name,function(data){
                                drilldowns = jQuery.parseJSON(data);
                                series = drilldowns[e.point.name];
                                chart.hideLoading();
                                chart.addSeriesAsDrilldown(e.point, series);
                            }).fail(function(jqxhr, textStatus, error ) {
                               var err = textStatus + ", " + error;
                                console.log( "Request Failed: " + err );
                            });
                            // Show the loading label
                            chart.showLoading('Mengambil data ...');
                        }

                    }
                }
            },
            title: {
                text: ''
            },
            xAxis: {
                type: 'category'
            },
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Jumlah Entry',
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }],
            drilldown: {
                series: []
            }
        });
    });

};

$.fn.showChartDataEntryMinggu = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,weeks){
        var x = ['Senin','Selasa','Rabu','Kamis','Jumat','Sabtu'];
        var y_now = [];
        var y_last = [];
        $.each(weeks,function(week,form){
            if(week=='thisweek'){
                $.each(form,function(index,value){
                    y_now.push(value);
                });
            }else{
                $.each(form,function(index,value){
                    y_last.push(value);
                });
            }

        });
        user = user.replace(/ /g,"_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Minggu Ini',
                    type: 'column',
                    data: y_now,
                    color: '#0000ff',
                    tooltip: {
                        valueSuffix: ''
                    }
                },{
                    name: 'Minggu Lalu',
                    type: 'column',
                    data: y_last,
                    color: '#ff0000',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryBulan = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,months){
        var x = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember'];
        var y_now = [];
        var y_last = [];
        var thisyear = 0;
        var lastyear = 0;
        $.each(months,function(month,form){
            if(month=='thisyear'){
                $.each(form,function(index,value){
                    thisyear = index.split("-");
                    y_now.push(value);
                });
            }else{
                $.each(form,function(index,value){
                    lastyear = index.split("-");
                    y_last.push(value);
                });
            }

        });
        user = user.replace(/ /g,"_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Tahun '+thisyear[0],
                    type: 'column',
                    data: y_now,
                    color: '#0000ff',
                    tooltip: {
                        valueSuffix: ''
                    }
                },{
                    name: 'Tahun '+lastyear[0],
                    type: 'column',
                    data: y_last,
                    color: '#ff0000',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChartDataEntryForm = function(data){
    var chart_data = data;
    Highcharts.setOptions({
        lang: {
            decimalPoint: ',',
            thousandsSep: '.'
        }
    });

    $.each(chart_data,function(user,form){
        var x = [];
        var y = [];
        $.each(form,function(index,value){
            x.push(index);
            y.push(value);
        });
        user = user.replace(/ /g,"_");
        $('#'+user).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,startOnTick: false},{min:0,startOnTick: false,opposite: true},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: 'Jumlah Entry',
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y}'
                    }
                }
            },
            series: [{
                    name: 'Jumlah Entry',
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });

};

$.fn.showChart = function(data){
    $.each(data,function(index1,data1){
        var id = data1['page'];
        var x = [];
        var y = [];
        $.each(data1['form'],function(index2,data2){
            x.push(index2);
            y.push(data2);
        });
        Highcharts.setOptions({
            lang: {
                decimalPoint: ',',
                thousandsSep: '.'
            }
        });

        $('#'+id).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            yAxis: [{min:0,minrange:100},{ // Primary yAxis
                labels: {
                    format: '{value}',
                    style: {
                        color: Highcharts.getOptions().colors[1]
                        }
                    },
                    title: {
                        text: data1['y_label'],
                        style: {
                            color: Highcharts.getOptions().colors[1]
                        }
                    }
                }],
            tooltip: {
                shared: true,
                pointFormat: data1['y_label']+": {point.y:.2f} %"
            },
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    dataLabels: {
                        enabled: true,
                        format: '{point.y:.2f}'
                    }
                }
            },
            series: [{
                    name: data1['series_name'],
                    type: 'column',
                    data: y,
                    color: '#73c1f7',
                    tooltip: {
                        valueSuffix: ''
                    }
                }]
        });
    });
};

$.fn.showChartStack = function(data){
    $.each(data,function(index1,data1){
        var id = data1['page'];
        var x = [];
        var y1 = [];
        var y2 = [];
        $.each(data1['form'],function(index2,data2){
            x.push(index2);
            y1.push(data2['l']);
            y2.push(data2['p']);
        });
        Highcharts.setOptions({
            lang: {
                decimalPoint: ',',
                thousandsSep: '.'
            }
        });

        $('#'+id).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    stacking: 'normal',
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            tooltip: {
                formatter: function () {
                    return '' + this.x + '
' +
                        this.series.name + ': ' + this.y + '
' +
                        'Total: ' + this.point.stackTotal;
                }
            },
            series: [{
                    name: data1['series_name'][0],
                    type: 'column',
                    data: y1,
                    color: 'blue'
                },{
                    name: data1['series_name'][1],
                    type: 'column',
                    data: y2,
                    color: 'red'
                }]
        });
    });
};

$.fn.showChartStackDouble = function(data){
    $.each(data,function(index1,data1){
        var id = data1['page'];
        var x = [];
        var y1bl = [];
        var y2bl = [];
        var y1bi = [];
        var y2bi = [];
        $.each(data1['form'],function(index2,data2){
            x.push(index2);
            y1bl.push(data2['lbl']);
            y2bl.push(data2['pbl']);
            y1bi.push(data2['lbi']);
            y2bi.push(data2['pbi']);
        });
        Highcharts.setOptions({
            lang: {
                decimalPoint: ',',
                thousandsSep: '.'
            }
        });

        $('#'+id).highcharts({
            chart: {
                zoomType: 'xy',
                height: 400
            },
            title: {
                text: ''
            },
            xAxis: [{
                    categories: x
                }],
            legend: {
                enabled : false
            },
            plotOptions: {
                series: {
                    borderWidth: 0,
                    stacking: 'normal',
                    dataLabels: {
                        enabled: true
                    }
                }
            },
            tooltip: {
                formatter: function () {
                    return '' + this.series.options.stack + '
' +
                            '' + this.x + '
' +
                        this.series.name + ': ' + this.y + '
' +
                        'Total: ' + this.point.stackTotal;
                }
            },
            series: [{
                    name: data1['series_name'][0],
                    type: 'column',
                    data: y1bl,
                    color: 'green',
                    stack: data1['series_stack_name'][0]
                },{
                    name: data1['series_name'][1],
                    type: 'column',
                    data: y2bl,
                    color: 'yellow',
                    stack: data1['series_stack_name'][0]
                },{
                    name: data1['series_name'][0],
                    type: 'column',
                    data: y1bi,
                    color: 'blue',
                    stack: data1['series_stack_name'][1]
                },{
                    name: data1['series_name'][1],
                    type: 'column',
                    data: y2bi,
                    color: 'red',
                    stack: data1['series_stack_name'][1]
                }]
        });
    });
};<|endoftext|>


<commit_before>
var UI = UI || {},
	Class = Class || function() {},
	Locale = Locale || {},
	mnml = mnml || {},
	floor = floor || {};

/**
 * @class UI.Button
 * @extends {UI.Control}
 * @type {Class}
 */
UI.Dropdown = new Class({

	Extends: UI.Field,

	name: 'dropdown',

	options: {
		name: 'dropdown',
		type: 'text', // push, file
		menuFx: {
		    duration: 150,
		    link: 'chain',
		    transition: Fx.Transitions.Quart.easeOut
		},
		input: {
			'input.keyup': '_onKeyUp',
			'input.keydown': '_onKeyDown',
			'input.mousedown': '_onMouseDown',
			'input.focus': '_onFocus',
			'input.blur': '_onBlur'
		}
	},

	/**
	 * [_initElement description]
	 * @return {[type]} [description]
	 */
	_initElement: function(){
		this.parent();

		this.control = {};

		this.element.addClass('type-dropdown');

		this.input.addEvent('keydown', function(e) {
			_log('keydown', e);

			if (e.key !== 'tab') {
				e.stop();
			}
		});

		var opts = this.options;

		if (!this.readonly) {
			this._initMenu(opts);
			this._initEvents();
		}

		this._initButton();
	},

	/**
	 * [_initIcon description]
	 * @return {[type]} [description]
	 */
	_initButton: function() {
		var self = this;

		new UI.Button({
			'clss': 'right',
			type: 'icon',
			name: 'movedown',
			icon: 'icon-times-circle',
		}).inject(this.element, 'top').addEvent('press', function() {
			self._showMenu();
		});
	},

	/**
	 * [_initToolbarComp description]
	 * @type {[type]}
	 */
	_initMenu: function(opts) {
		//_log('_initMenu', opts);
		var self = this,
			//list = opts.list,
			timer = null;

		opts.list = opts.list || [];

		this.container = this.element.getParent();

		var value = self.input.get('value');

		var menu = this.menu = new Element('ul', {
			class: 'ui-menu',
		}).inject(this.element, 'bottom');

		for (var i= 0; i < opts.list.length; i++) {
			var name = opts.list[i];
			var def = opts.list[name];
			this._initItem(name, def, this.menu, value);
		}

		this.menuFx = new Fx.Morph(this.menu, opts.menuFx);

		//_log('menu coord', menu.getCoordinates());
		//menu.setStyle('display', 'none');

		return menu;
	},

	/**
	 * [_initEvents description]
	 * @return {[type]} [description]
	 */
	_initEvents: function() {
		var self = this;

		if (this.readonly) return;

		this.addEvents({
			select: function(name) {
				_log('select');
				self.input.set('value', name);
				self.fireEvent('change', name);
			}
		});

	},

	/**
	 * [_onFocus description]
	 * @return {[type]} [description]
	 */
	_onFocus: function(e) {
		//_log('_onFocus');

		this._showMenu(e);

		this.parent(e);

	},

	/**
	 * [_onFocus description]
	 * @return {[type]} [description]
	 */
	_onBlur: function(e) {
		//_log('_onBlur');
		this.parent(e);
		this._hideMenu(e);
	},

	/**
	 * [_showMenu description]
	 * @return {[type]} [description]
	 */
	_showMenu: function() {

		if (this.readonly) return;

		var menu = this.menu;

		menu.setStyles({
			height: 0,
			left: 16,
			paddingTop: 0,
			paddingBottom: 0,
			display: 'block',
			opacity: 0
		});

		var coord = this.input.getCoordinates();

		var width = coord.width;

		//_log('widh', menu.scrollWidth, coord.width);

		if (menu.scrollWidth > coord.width)
			width = menu.scrollWidth;

		menu.setStyle('width', width);

		this.menuFx.start({
		    height: this.menu.scrollHeight + 20,
		  	paddingTop: 10,
		  	paddingBottom: 10,
		  	opacity: 1
		});

		this.fireEvent('showMenu', menu);
	},

	/**
	 * [_showMenu description]
	 * @return {[type]} [description]
	 */
	_hideMenu: function() {

		if (this.input.get('readonly')) return;

		this.menuFx.start({
		    height: 0,
		  	paddingTop: 0,
		  	paddingBottom: 0,
		  	opacity: 0
		});

		var self = this;
		(function() {
			self.menu.setStyle('display', 'none');
		}).delay(this.options.menuFx.duration);

		this.fireEvent('hide');
	},

	/**
	 * [_initMenuPosition description]
	 * @return {[type]} [description]
	 */
	_initMenuPosition: function() {
		//_log('_initMenuPosition');
		//var container = this.container.getParent().getCoordinates();
		var coord = this.element.getCoordinates(this.container);

		return coord;
	},

	/**
	 * [_initItem description]
	 * @param  {[type]} name    [description]
	 * @param  {[type]} def     [description]
	 * @param  {[type]} element [description]
	 * @return {[type]}         [description]
	 */
	_initItem: function(name, def, element, value){
		var self = this,
			clss = 'UI.Button',
			comp,
			opts,
			comps = name.split(/\./);

		if (comps.length > 1) {
			clss = 'UI.'+comps[0].capitalize();
			name = comps[1];
		}

		if (name === 'separator')
			clss = 'UI.Separator';

		if (def && def.clss)
			clss = def.clss;

		if (def && def.opts) {
			opts = def.opts;
			console.log('--', name, def.opts);
			opts.text = Locale.get('control.'+name, name) || name;
			opts.icon = mnml.icon.font[name] || 'mdi-action-help';
			opts.tag = 'span';
		} else {
			opts = {
				name: name,
				icon: mnml.icon.font[name] || 'mdi-action-help'
			};
		}

		if (typeof name === 'string')

		if (!name) return;

		var	Clss = mnml.strToClss(clss);

		if (clss === 'UI.Button' || clss === 'UI.ButtonMenu')
			opts.text = Locale.get('control.'+name, name) || name;

		//_log('n', n, opts);
		var role = floor.controller.session.role;

		this.options.control = this.options.control || {};

		//console.log('----', name, opts);
		this.control[name] = new Clss(opts).inject(element);

		if (clss === 'UI.Button')
		this.control[name].addEvents({
			press: function() {
				var name =  this.options.name;
				//_log('press', name, this.isEnable());
				if (this.isEnable()) {
					//self.fireEvent('control::'+name, this);
					self.fireEvent('select', name);
				}
				self.menu.hide();
			}
		});
	},

	/**
	 * [_onElementMouseDown description]
	 * @param  {event} e [description]
	 * @return {[type]}   [description]
	 */
	_onClick: function(e) {
		//_log('_onElementClick');
		var opts = this.options;
		e.stopPropagation();

		if (!this.menu) this._initMenu(opts);

		this.menuShow(e);
	}

});
<commit_msg>Clean consoles<commit_after>
var UI = UI || {},
	Class = Class || function() {},
	Locale = Locale || {},
	mnml = mnml || {},
	floor = floor || {};

/**
 * @class UI.Button
 * @extends {UI.Control}
 * @type {Class}
 */
UI.Dropdown = new Class({

	Extends: UI.Field,

	name: 'dropdown',

	options: {
		name: 'dropdown',
		type: 'text', // push, file
		menuFx: {
		    duration: 150,
		    link: 'chain',
		    transition: Fx.Transitions.Quart.easeOut
		},
		input: {
			'input.keyup': '_onKeyUp',
			'input.keydown': '_onKeyDown',
			'input.mousedown': '_onMouseDown',
			'input.focus': '_onFocus',
			'input.blur': '_onBlur'
		}
	},

	/**
	 * [_initElement description]
	 * @return {[type]} [description]
	 */
	_initElement: function(){
		this.parent();

		this.control = {};

		this.element.addClass('type-dropdown');

		this.input.addEvent('keydown', function(e) {
			//_log('keydown', e);

			if (e.key !== 'tab') {
				e.stop();
			}
		});

		var opts = this.options;

		if (!this.readonly) {
			this._initMenu(opts);
			this._initEvents();
		}

		this._initButton();
	},

	/**
	 * [_initIcon description]
	 * @return {[type]} [description]
	 */
	_initButton: function() {
		var self = this;

		new UI.Button({
			'clss': 'right',
			type: 'icon',
			name: 'movedown',
			icon: 'icon-times-circle',
		}).inject(this.element, 'top').addEvent('press', function() {
			self._showMenu();
		});
	},

	/**
	 * [_initToolbarComp description]
	 * @type {[type]}
	 */
	_initMenu: function(opts) {
		//_log('_initMenu', opts);
		var self = this,
			//list = opts.list,
			timer = null;

		opts.list = opts.list || [];

		this.container = this.element.getParent();

		var value = self.input.get('value');

		var menu = this.menu = new Element('ul', {
			class: 'ui-menu',
		}).inject(this.element, 'bottom');

		for (var i= 0; i < opts.list.length; i++) {
			var name = opts.list[i];
			var def = opts.list[name];
			this._initItem(name, def, this.menu, value);
		}

		this.menuFx = new Fx.Morph(this.menu, opts.menuFx);

		//_log('menu coord', menu.getCoordinates());
		//menu.setStyle('display', 'none');

		return menu;
	},

	/**
	 * [_initEvents description]
	 * @return {[type]} [description]
	 */
	_initEvents: function() {
		var self = this;

		if (this.readonly) return;

		this.addEvents({
			select: function(name) {
				//_log('select');
				self.input.set('value', name);
				self.fireEvent('change', name);
			}
		});

	},

	/**
	 * [_onFocus description]
	 * @return {[type]} [description]
	 */
	_onFocus: function(e) {
		//_log('_onFocus');

		this._showMenu(e);

		this.parent(e);

	},

	/**
	 * [_onFocus description]
	 * @return {[type]} [description]
	 */
	_onBlur: function(e) {
		//_log('_onBlur');
		this.parent(e);
		this._hideMenu(e);
	},

	/**
	 * [_showMenu description]
	 * @return {[type]} [description]
	 */
	_showMenu: function() {

		if (this.readonly) return;

		var menu = this.menu;

		menu.setStyles({
			height: 0,
			left: 16,
			paddingTop: 0,
			paddingBottom: 0,
			display: 'block',
			opacity: 0
		});

		var coord = this.input.getCoordinates();

		var width = coord.width;

		//_log('widh', menu.scrollWidth, coord.width);

		if (menu.scrollWidth > coord.width)
			width = menu.scrollWidth;

		menu.setStyle('width', width);

		this.menuFx.start({
		    height: this.menu.scrollHeight + 20,
		  	paddingTop: 10,
		  	paddingBottom: 10,
		  	opacity: 1
		});

		this.fireEvent('showMenu', menu);
	},

	/**
	 * [_showMenu description]
	 * @return {[type]} [description]
	 */
	_hideMenu: function() {

		if (this.input.get('readonly')) return;

		this.menuFx.start({
		    height: 0,
		  	paddingTop: 0,
		  	paddingBottom: 0,
		  	opacity: 0
		});

		var self = this;
		(function() {
			self.menu.setStyle('display', 'none');
		}).delay(this.options.menuFx.duration);

		this.fireEvent('hide');
	},

	/**
	 * [_initMenuPosition description]
	 * @return {[type]} [description]
	 */
	_initMenuPosition: function() {
		//_log('_initMenuPosition');
		//var container = this.container.getParent().getCoordinates();
		var coord = this.element.getCoordinates(this.container);

		return coord;
	},

	/**
	 * [_initItem description]
	 * @param  {[type]} name    [description]
	 * @param  {[type]} def     [description]
	 * @param  {[type]} element [description]
	 * @return {[type]}         [description]
	 */
	_initItem: function(name, def, element, value){
		var self = this,
			clss = 'UI.Button',
			comp,
			opts,
			comps = name.split(/\./);

		if (comps.length > 1) {
			clss = 'UI.'+comps[0].capitalize();
			name = comps[1];
		}

		if (name === 'separator')
			clss = 'UI.Separator';

		if (def && def.clss)
			clss = def.clss;

		if (def && def.opts) {
			opts = def.opts;
			console.log('--', name, def.opts);
			opts.text = Locale.get('control.'+name, name) || name;
			opts.icon = mnml.icon.font[name] || 'mdi-action-help';
			opts.tag = 'span';
		} else {
			opts = {
				name: name,
				icon: mnml.icon.font[name] || 'mdi-action-help'
			};
		}

		if (typeof name === 'string')

		if (!name) return;

		var	Clss = mnml.strToClss(clss);

		if (clss === 'UI.Button' || clss === 'UI.ButtonMenu')
			opts.text = Locale.get('control.'+name, name) || name;

		//_log('n', n, opts);
		var role = floor.controller.session.role;

		this.options.control = this.options.control || {};

		//console.log('----', name, opts);
		this.control[name] = new Clss(opts).inject(element);

		if (clss === 'UI.Button')
		this.control[name].addEvents({
			press: function() {
				var name =  this.options.name;
				//_log('press', name, this.isEnable());
				if (this.isEnable()) {
					//self.fireEvent('control::'+name, this);
					self.fireEvent('select', name);
				}
				self.menu.hide();
			}
		});
	},

	/**
	 * [_onElementMouseDown description]
	 * @param  {event} e [description]
	 * @return {[type]}   [description]
	 */
	_onClick: function(e) {
		//_log('_onElementClick');
		var opts = this.options;
		e.stopPropagation();

		if (!this.menu) this._initMenu(opts);

		this.menuShow(e);
	}

});
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

const usage = '\nbuild <vn.n.n[-pre[.n]]> | <HEAD> [-p]\n'
const versionsFile = path.resolve(__dirname, '../public/versions.json')

const args = process.argv
if (args.length < 3) {
  console.log(usage, '\n')
  process.exit()
}

const version = args[2]
let versions
const versionIsHEAD = version === 'HEAD'
const useForcePush = args[3] === '-p'
const versionNumber = versionIsHEAD ? (
  JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')).version
) : version

function execSyncWithLog(command) {
  console.log(command)
  try {
    execSync(command, { stdio: 'inherit' })
  } catch (error) {
    console.error(error.output[1])
    process.exit(error.status)
 }
}

function saveVersionsFile() {
  versions = JSON.parse(fs.readFileSync(path.resolve(__dirname, versionsFile), 'utf8'))
  if (!version.includes(versionNumber)) {
    versions.push(versionNumber)
    versions.sort()
    fs.writeFileSync(versionsFile, JSON.stringify(versions, null, 2), 'utf8')
    execSyncWithLog(`git add ${versionsFile} && git commit -m "add ${versionNumber} to versions file"`)
  }
}

function savePublicVersionsFile() {
  const publicVersionsFile = path.resolve(__dirname, '../../versions.json')
  if (fs.existsSync(publicVersionsFile)) {
    const publicVersions = JSON.parse(fs.writeFileSync(publicVersionsFile, 'utf8'))
    if (!publicVersions.includes(versionNumber)) {
      publicVersions.push(versionNumber)
      publicVersions.sort()
    }
    fs.writeFileSync(publicVersionsFile, JSON.stringify(publicVersions, null, 2), 'utf8')
  } else {
    fs.writeFileSync(publicVersionsFile, JSON.stringify(versions, null, 2), 'utf8')
  }
}

function buildDocs() {
  process.chdir(__dirname)
  execSyncWithLog('git checkout gh-pages')
  execSyncWithLog('git reset --hard HEAD~1')

  if (versionIsHEAD) {
    execSyncWithLog('git checkout --detach master')
  } else {
    execSyncWithLog(`git checkout tags/${version}`)
  }

  execSyncWithLog('test -d \"./build\" && rm -r \"./build\" || exit 0')
  execSyncWithLog('cd ../../ && npm install && cd docs && npm run build')
  execSyncWithLog('git checkout gh-pages')
  execSyncWithLog(`mv ../build ../../${version}`)

  if (versionIsHEAD) {
    execSyncWithLog(`ln -sfh ./${versionNumber} ../release`)
  }
  savePublicVersionsFile()

  if (versionIsHEAD) {
    execSyncWithLog('git commit --amend --no-edit')
  } else {
    execSyncWithLog(`git add ../../ && git commit -m '${version}'`)
  }

  execSyncWithLog(`git push${useForcePush ? ' -f' : ''}`)
}

saveVersionsFile()
buildDocs()
<commit_msg>fixed build script bug<commit_after>const fs = require('fs')
const path = require('path')
const { execSync } = require('child_process')

const usage = '\nbuild <vn.n.n[-pre[.n]]> | <HEAD> [-p]\n'
const versionsFile = path.resolve(__dirname, '../public/versions.json')

const args = process.argv
if (args.length < 3) {
  console.log(usage, '\n')
  process.exit()
}

const version = args[2]
let versions
const versionIsHEAD = version === 'HEAD'
const useForcePush = args[3] === '-p'
const versionNumber = versionIsHEAD ? (
  JSON.parse(fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf8')).version
) : version

function execSyncWithLog(command) {
  console.log(command)
  try {
    execSync(command, { stdio: 'inherit' })
  } catch (error) {
    console.error(error.output[1])
    process.exit(error.status)
 }
}

function saveVersionsFile() {
  versions = JSON.parse(fs.readFileSync(path.resolve(__dirname, versionsFile), 'utf8'))
  if (!version.includes(versionNumber)) {
    versions.push(versionNumber)
    versions.sort()
    fs.writeFileSync(versionsFile, JSON.stringify(versions, null, 2), 'utf8')
    execSyncWithLog(`git add ${versionsFile} && git commit -m "add ${versionNumber} to versions file"`)
  }
}

function savePublicVersionsFile() {
  const publicVersionsFile = path.resolve(__dirname, '../../versions.json')
  if (fs.existsSync(publicVersionsFile)) {
    const publicVersions = JSON.parse(fs.writeFileSync(publicVersionsFile, 'utf8'))
    if (!publicVersions.includes(versionNumber)) {
      publicVersions.push(versionNumber)
      publicVersions.sort()
    }
    fs.writeFileSync(publicVersionsFile, JSON.stringify(publicVersions, null, 2), 'utf8')
  } else {
    fs.writeFileSync(publicVersionsFile, JSON.stringify(versions, null, 2), 'utf8')
  }
}

function buildDocs() {
  process.chdir(__dirname)
  execSyncWithLog('git checkout gh-pages')
  execSyncWithLog('git reset --hard HEAD~1')

  if (versionIsHEAD) {
    execSyncWithLog('git checkout --detach master')
  } else {
    execSyncWithLog(`git checkout tags/${version}`)
  }

  execSyncWithLog('test -d \"./build\" && rm -r \"./build\" || exit 0')
  execSyncWithLog('cd ../../ && npm install && cd docs && npm run build')
  execSyncWithLog('git checkout gh-pages')
  execSyncWithLog(`mv ../build ../../${versionNumber}`)

  if (versionIsHEAD) {
    execSyncWithLog(`echo "./${versionNumber}" > ../../release`)
  }
  savePublicVersionsFile()

  if (versionIsHEAD) {
    execSyncWithLog('git commit --amend --no-edit')
  } else {
    execSyncWithLog(`git add ../../ && git commit -m '${version}'`)
  }

  execSyncWithLog(`git push${useForcePush ? ' -f' : ''}`)
}

saveVersionsFile()
buildDocs()
<|endoftext|>


<commit_before>/*

readme.js - example from the README

The MIT License (MIT)

Copyright (c) 2015 Dale Schumacher

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var tart = require('tart');
var sponsor = tart.minimal({
    fail: function (e) {
        console.log('ERROR!', e);
    }
});

var PEG = require('../PEG.js');
var input = require('../input.js');

//var log = console.log;
var log = function () {};

var pf = PEG.factory(sponsor);
var ns = pf.namespace(log);

/*
Assign <- Name "=" Assign
        / Expr
*/
ns.define('Assign',
    pf.choice([
        pf.sequence([
            ns.call('Name'),
            pf.terminal('='),
            ns.call('Assign')
        ]),
        ns.call('Expr')
    ])
);

/*
Name   <- [a-zA-Z]
*/
ns.define('Name',
    pf.predicate(function (token) {
        return /[a-zA-Z]/.test(token);
    })
);

/*
Expr   <- Term ([-+] Term)*
*/
ns.define('Expr',
    pf.sequence([
        ns.call('Term'),
        pf.zeroOrMore(
            pf.sequence([
                pf.predicate(function (token) {
                    return /[-+]/.test(token);
                }),
                ns.call('Term')
            ])
        )
    ])
);

/*
Term   <- Factor ([/*] Factor)*
*/
ns.define('Term',
    pf.sequence([
        ns.call('Factor'),
        pf.zeroOrMore(
            pf.sequence([
                pf.predicate(function (token) {
                    return /[/*]/.test(token);
                }),
                ns.call('Factor')
            ])
        )
    ])
);

/*
Factor <- "(" Assign ")"
        / Name
        / [0-9]+
*/
ns.define('Factor',
    pf.choice([
        pf.sequence([
            pf.terminal('('),
            ns.call('Assign'),
            pf.terminal(')')
        ]),
        ns.call('Name'),
        pf.oneOrMore(
            pf.predicate(function (token) {
                return /[0-9]/.test(token);
            })
        )
    ])
);

var ok = sponsor(function okBeh(m) {
    console.log('OK:', JSON.stringify(m, null, '  '));
});
var fail = sponsor(function failBeh(m) {
    console.log('FAIL:', JSON.stringify(m, null, '  '));
});

var start = ns.call('Assign');
var matcher = pf.matcher(start, ok, fail);
var stream = sponsor(input.stringStream('x=y=10-2/3+4*5/(6-7)'));
stream(matcher);
<commit_msg>Use fromReadable in readme example<commit_after>/*

readme.js - example from the README

The MIT License (MIT)

Copyright (c) 2015 Dale Schumacher

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var tart = require('tart');
var sponsor = tart.minimal({
    fail: function (e) {
        console.log('ERROR!', e);
    }
});

var PEG = require('../PEG.js');
var input = require('../input.js');

//var log = console.log;
var log = function () {};

var pf = PEG.factory(sponsor);
var ns = pf.namespace(log);

/*
Assign <- Name "=" Assign
        / Expr
*/
ns.define('Assign',
    pf.choice([
        pf.sequence([
            ns.call('Name'),
            pf.terminal('='),
            ns.call('Assign')
        ]),
        ns.call('Expr')
    ])
);

/*
Name   <- [a-zA-Z]
*/
ns.define('Name',
    pf.predicate(function (token) {
        return /[a-zA-Z]/.test(token);
    })
);

/*
Expr   <- Term ([-+] Term)*
*/
ns.define('Expr',
    pf.sequence([
        ns.call('Term'),
        pf.zeroOrMore(
            pf.sequence([
                pf.predicate(function (token) {
                    return /[-+]/.test(token);
                }),
                ns.call('Term')
            ])
        )
    ])
);

/*
Term   <- Factor ([/*] Factor)*
*/
ns.define('Term',
    pf.sequence([
        ns.call('Factor'),
        pf.zeroOrMore(
            pf.sequence([
                pf.predicate(function (token) {
                    return /[/*]/.test(token);
                }),
                ns.call('Factor')
            ])
        )
    ])
);

/*
Factor <- "(" Assign ")"
        / Name
        / [0-9]+
*/
ns.define('Factor',
    pf.choice([
        pf.sequence([
            pf.terminal('('),
            ns.call('Assign'),
            pf.terminal(')')
        ]),
        ns.call('Name'),
        pf.oneOrMore(
            pf.predicate(function (token) {
                return /[0-9]/.test(token);
            })
        )
    ])
);

var ok = sponsor(function okBeh(m) {
    console.log('OK:', JSON.stringify(m, null, '  '));
});
var fail = sponsor(function failBeh(m) {
    console.log('FAIL:', JSON.stringify(m, null, '  '));
});

var start = ns.call('Assign');
var matcher = pf.matcher(start, ok, fail);
/*
var stream = sponsor(input.stringStream('x=y=10-2/3+4*5/(6-7)'));
stream(matcher);
*/
var stream = require('../stream.js').characters();
var next = input.fromReadable(sponsor, stream);
next(matcher);
stream.write('x=y=10-2/3+4*5/(6-7)');
stream.end();
<|endoftext|>


<commit_before>import { $, $$ } from './utils/dom';

/* NOTE: We assume that all items have fixed width. */

export default function() {
  const gridExists = $('.js-grid');

  if (gridExists) {
    setupLayout();
    window.addEventListener('resize', setupLayout);
  }
}

function setupLayout() {
  const grid = $('.js-grid');

  const imagesResized = resizeImages(grid),
        layout = calculateLayout(grid);

  (imagesResized
    || grid.clientWidth != layout.gridWidth) && applyLayout(grid, layout);
}

function calculateLayout(grid) {
  const itemMargin = 10; /* TODO: move to CSS */

  const itemWidth = $('.js-grid__item', grid).clientWidth,
        spaceFree = grid.closest('.js-grid-container').clientWidth;

  const itemSpace = itemMargin + itemWidth,
        itemsTotal = grid.childElementCount,
        /* We add itemMargin to spaceFree because the last item in a row
         * doesn't have a margin but it's still included in itemSpace */
        columnCountByWidth = Math.floor((spaceFree + itemMargin) / itemSpace),
        columnCount = Math.min(itemsTotal, Math.max(1, columnCountByWidth)),
        gridWidth = columnCount * itemSpace - itemMargin;

  return { itemMargin, itemSpace, columnCount, gridWidth };
}

function resizeImages(grid) {
  const sampleImage = $('.js-grid__media', grid),
        currentWidth = sampleImage.dataset.measuredAt;

  const container = sampleImage.closest('.js-grid__item');
  const availableWidth =
    window.getComputedStyle(container).getPropertyValue("width");

  if (currentWidth != availableWidth) {
    sampleImage.dataset.measuredAt = availableWidth;

    $$('.js-grid__media', grid).forEach((image) => {
      const ratio = parseFloat(image.dataset.ratio),
            width = parseInt(availableWidth, 10),
            height = Math.floor(width / ratio);

      image.style.height = `${height}px`;
    });

    return true;
  }
}

function applyLayout(grid, layout) {
  const items = $$('.js-grid__item', grid),
        { columnCount, gridWidth } = layout,
        { offsets, columnHeights } = calculateOffsets(items, layout),
        gridHeight = Math.max(...columnHeights);

  offsets.forEach(([top, left], index) => {
    items[index].style.position = 'absolute';
    items[index].style.top = `${top}px`;
    items[index].style.left = `${left}px`;

    items[index].classList.remove('media--unstyled');
  });

  grid.style.position = 'relative';
  grid.style.width = `${gridWidth}px`;
  grid.style.height = `${gridHeight}px`;
}

function calculateOffsets(gridItems, layout) {
  const { itemMargin, itemSpace, columnCount } = layout;

  const offsets = [],
        columnHeights = Array(columnCount).fill(0);

  gridItems.forEach((item, index) => {
    const column = index % columnCount,
          top = columnHeights[column],
          left = itemSpace * column,
          addedHeight = item.clientHeight + itemMargin;

    offsets.push([top, left]);
    columnHeights[column] += addedHeight;
  });

  return { offsets, columnHeights };
}
<commit_msg>fix font loading throwing off layout calculations<commit_after>import { $, $$ } from './utils/dom';

/* NOTE: We assume that all items have fixed width. */

export default function() {
  const gridExists = $('.js-grid');

  if (gridExists) {
    setupLayout();
    window.addEventListener('resize', setupLayout);
  }

  /* Fonts that have not been loaded yet may throw off layout calculations.
   * FontFaceSet provides a neat way to account for that, but it's not
   * supported in Edge yet, so we have to check if it's present. */
  document.fonts && document.fonts.ready.then(() => setupLayout(true));
}

function setupLayout(force) {
  const grid = $('.js-grid');

  const imagesResized = resizeImages(grid),
        layout = calculateLayout(grid);

  (force
    || imagesResized
    || grid.clientWidth != layout.gridWidth) && applyLayout(grid, layout);
}

function calculateLayout(grid) {
  const itemMargin = 10; /* TODO: move to CSS */

  const itemWidth = $('.js-grid__item', grid).clientWidth,
        spaceFree = grid.closest('.js-grid-container').clientWidth;

  const itemSpace = itemMargin + itemWidth,
        itemsTotal = grid.childElementCount,
        /* We add itemMargin to spaceFree because the last item in a row
         * doesn't have a margin but it's still included in itemSpace */
        columnCountByWidth = Math.floor((spaceFree + itemMargin) / itemSpace),
        columnCount = Math.min(itemsTotal, Math.max(1, columnCountByWidth)),
        gridWidth = columnCount * itemSpace - itemMargin;

  return { itemMargin, itemSpace, columnCount, gridWidth };
}

function resizeImages(grid) {
  const sampleImage = $('.js-grid__media', grid),
        currentWidth = sampleImage.dataset.measuredAt;

  const container = sampleImage.closest('.js-grid__item');
  const availableWidth =
    window.getComputedStyle(container).getPropertyValue("width");

  if (currentWidth != availableWidth) {
    sampleImage.dataset.measuredAt = availableWidth;

    $$('.js-grid__media', grid).forEach((image) => {
      const ratio = parseFloat(image.dataset.ratio),
            width = parseInt(availableWidth, 10),
            height = Math.floor(width / ratio);

      image.style.height = `${height}px`;
    });

    return true;
  }
}

function applyLayout(grid, layout) {
  const items = $$('.js-grid__item', grid),
        { columnCount, gridWidth } = layout,
        { offsets, columnHeights } = calculateOffsets(items, layout),
        gridHeight = Math.max(...columnHeights);

  offsets.forEach(([top, left], index) => {
    items[index].style.position = 'absolute';
    items[index].style.top = `${top}px`;
    items[index].style.left = `${left}px`;

    items[index].classList.remove('media--unstyled');
  });

  grid.style.position = 'relative';
  grid.style.width = `${gridWidth}px`;
  grid.style.height = `${gridHeight}px`;
}

function calculateOffsets(gridItems, layout) {
  const { itemMargin, itemSpace, columnCount } = layout;

  const offsets = [],
        columnHeights = Array(columnCount).fill(0);

  gridItems.forEach((item, index) => {
    const column = index % columnCount,
          top = columnHeights[column],
          left = itemSpace * column,
          addedHeight = item.clientHeight + itemMargin;

    offsets.push([top, left]);
    columnHeights[column] += addedHeight;
  });

  return { offsets, columnHeights };
}
<|endoftext|>


<commit_before>/*
    Example of using raml2html as a script.
 */

var raml2html = require('../lib/raml2html');

// raml2html.render() needs a config object with at least a `template` property (a string or handlebars template object).
// Instead of creating this config object ourselves, we can just ask for raml2html.getDefaultConfig():
var config1 = raml2html.getDefaultConfig();

raml2html.render('example.raml', config1, function(result) {
    console.log('1: ', result.length);
}, function(error) {
    console.log('error! ', error);
});

// If you want to use your own templates that follow the same structure, helpers and partials,
// you could do something like this:
var config2 = raml2html.getDefaultConfig(false, require('../lib/template.handlebars'));

raml2html.render('example.raml', config2, function(result) {
    console.log('2: ', result.length);
}, function(error) {
    console.log('error! ', error);
});

// If you want to customize everything, just create the config object yourself from scratch:
var config3 = {
    template: require('../lib/template.handlebars')
};

raml2html.render('example.raml', config3, function(result) {
    console.log('3: ', result.length);
}, function(error) {
    console.log('error! ', error);
});
<commit_msg>Update script.js<commit_after>/*
    Example of using raml2html as a script.
 */

var raml2html = require('../lib/raml2html');

// raml2html.render() needs a config object with at least a `template` property (a string or handlebars template object).
// Instead of creating this config object ourselves, we can just ask for raml2html.getDefaultConfig():
var config1 = raml2html.getDefaultConfig();

raml2html.render('example.raml', config1, function(result) {
    console.log('1: ', result.length);
}, function(error) {
    console.log('error! ', error);
});

// If you want to use your own templates that follow the same structure, helpers and partials,
// you could do something like this:
var config2 = raml2html.getDefaultConfig(false, require('../lib/template.handlebars'));

raml2html.render('example.raml', config2, function(result) {
    console.log('2: ', result.length);
}, function(error) {
    console.log('error! ', error);
});

// If you want to customize everything, just create the config object yourself from scratch.
// Check raml2html.getDefaultConfig for the possible properties (https, helpers, partials, processOutput).
// The template property should be a string containing the template or a Handlebars template object.
var config3 = {
    template: '
Hello!
'
};

raml2html.render('example.raml', config3, function(result) {
    console.log('3: ', result.length);
}, function(error) {
    console.log('error! ', error);
});
<|endoftext|>


<commit_before>var request = require( 'request' );
var config = require( '../../config' );

exports.postManifest = function ( manifest, callback ) {
  var options = {
    uri: 'http://localhost:' + config.port + '/packages',
    timeout: 8000,
    form: require( '../manifests/' + manifest + '.json' ),
    json: true
  };
  request.post( options, callback );
};

exports.getPackage = function () {
  var query = arguments.length === 2 ? arguments[ 0 ] : null;
  var callback = arguments[ arguments.length - 1 ];
  var options = {
    uri: 'http://localhost:' + config.port + '/packages',
    timeout: 3000,
    json: true
  };

  if ( query ) {
    options.uri += '/' + query;
  }

  request.get( options, callback );
};

exports.searchPackages = function ( query, callback ) {
  var options = {
    uri: 'http://localhost:' + config.port + '/packages/search/' + query,
    timeout: 3000,
    json: true
  };

  request.get( options, callback );
};
<commit_msg>Add getScript helper to test<commit_after>var request = require( 'request' );
var config = require( '../../config' );

exports.postManifest = function ( manifest, callback ) {
  var options = {
    uri: 'http://localhost:' + config.port + '/packages',
    timeout: 8000,
    form: require( '../manifests/' + manifest + '.json' ),
    json: true
  };
  request.post( options, callback );
};

exports.getPackage = function () {
  var query = arguments.length === 2 ? arguments[ 0 ] : null;
  var callback = arguments[ arguments.length - 1 ];
  var options = {
    uri: 'http://localhost:' + config.port + '/packages',
    timeout: 3000,
    json: true
  };

  if ( query ) {
    options.uri += '/' + query;
  }

  request.get( options, callback );
};

exports.searchPackages = function ( query, callback ) {
  var options = {
    uri: 'http://localhost:' + config.port + '/packages/search/' + query,
    timeout: 3000,
    json: true
  };

  request.get( options, callback );
};

exports.getScript = function ( pkg, callback ) {
  var options = {
    uri: 'http://localhost:' + config.port + '/packages/' + pkg + '/script.js',
    timeout: 3000
  };

  request.get( options, callback );
};
<|endoftext|>