<commit_before>$.cssHooks.backgroundColor = {
    get: function(elem) {
        if (elem.currentStyle)
            var bg = elem.currentStyle["backgroundColor"];
        else if (window.getComputedStyle)
            var bg = document.defaultView.getComputedStyle(elem,
                null).getPropertyValue("background-color");
        if (bg.search("rgb") == -1)
            return bg;
        else {
            bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
        }
    }
};

$.fn.dataTableExt.oSort['numeric_ignore_nan-asc']  = function(x,y) {
    if (isNaN(x) && isNaN(y)) return ((x < y) ? 1 : ((x > y) ?  -1 : 0));

    if (isNaN(x)) return 1;
    if (isNaN(y)) return -1;

    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

$.fn.dataTableExt.oSort['numeric_ignore_nan-desc'] = function(x,y) {
    if (isNaN(x) && isNaN(y)) return ((x < y) ? 1 : ((x > y) ?  -1 : 0));

    if (isNaN(x)) return 1;
    if (isNaN(y)) return -1;

    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};

$.fn.dataTableExt.afnFiltering.push(
    function(oSettings, aData, iDataIndex) {
        var selected_tags = $('.filter_labels h3 span.tag-checked').map(function(k, v) {
                return $(this).text();
            }).get(),
            row_tags = aData[9].split(',');

        if (!selected_tags.length) { // nothing to filter out
            return true;
        } else {
            if (!row_tags.length || (row_tags.length === 1 && row_tags[0] === "")) {
                return false;
            }
            for (var i = 0; i < selected_tags.length; i++) {
                for (var j = 0; j < row_tags.length; j++) {
                    if (selected_tags[i] === row_tags[j]) {
                        return true;
                    }
                }
            }
            return false;
        }
    }
);

$.fn.dataTableExt.afnFiltering.push(
    function(oSettings, aData, iDataIndex) {
        var selected_categories = $('.category_labels h2 span.tag-checked').map(function(k, v) {
                return $(this).css('background-color');
            }).get(),
            row_color = aData[10];
        if (!selected_categories.length) { // nothing to filter out
            return true;
        } else {
            for (var i = 0; i < selected_categories.length; i++) {
                if (selected_categories[i] === row_color) {
                    return true;
                }
            }
        }
        return false;
    }
);

var genomeData = $('#genomeData');
var reset_checkboxes = function(checkbox_settings) {
    var checkboxes = $(".checkbox-row input");
    checkbox_settings.forEach(function(element, index) {
        var checkbox = $(checkboxes[index]);
        checkbox.prop('checked', element).trigger('change');
    });

};
$(document).ready(function() {
    var genome_url = genomeData.data('genome_url');
    var genomeTable = genomeData.dataTable({
        "ajax": genome_url,
        "columns": [
            {"data": "rsid" },
            {"data": "chromosome_position" },
            {"data": "risk_allele" },
            {"data": "genotype" },
            {"data": "disease_trait" },
            {"data": "p_value" },
            {"data": "or_or_beta" },
            {"data": "risk" },
            {"data": "priority", "defaultContent": "0" },
            {"data": "tags", "defaultContent": " "},
            {"data": "color", "defaultContent": ""}
        ],
        "pageLength": 100,
        //'bSort': false,
        "aoColumnDefs": [
            { "sType": "numeric_ignore_nan", "aTargets": [ 5, 6 ] },
            { "bSearchable": false, "bVisible": false, "aTargets": [ 8 ] }
        ],
        "columnDefs": [{"targets": [ 8 ], "visible": false, "searchable": false}],
        "order": [[ 8, "desc" ]],
        "processing": true,
        "rowCallback": function(row, data, index) {
            var $row = $(row);
            $row.data('url', encodeURI(data['link'] + '?allele=' + data['genotype']));
            $('td:not(.color-marked)', row).prepend(' ').addClass('color-marked');
        },
        "drawCallback": function( settings ) {
            var rows = $('#genomeData tbody tr');

            // Remove existing event handlers;
            rows.off('click');

            rows.click(function(e) {
                e.preventDefault();
                var row = $(this);
                var destination = $('#genomeDataDestination');
                var doc_top = $(document).scrollTop()+100;
                var table_top = $('#genomeData tbody').offset().top;
                var computed_top;
                if (doc_top > table_top) {
                    computed_top = doc_top;
                } else {
                    computed_top = table_top;
                }
                destination.text('Loading...').data('original_top', computed_top);
                $(window).scroll();
                $.get(row.data('url'), {'ajax':'1'})
                .fail(function(data) {
                    destination.text('error\n'+data.statusCode()+' '+data.statusText+'\n\n'+data.responseText);
                    $(window).scroll();
                })
                .done(function(data) {
                    destination.html(data);
                    $(window).scroll();
                });
                return false;
                window.open(row.data('url'), 'Your genome', "height=" + window.screen.height +",width=" + window.screen.width);
            });
            // Fix datatable for fluid container
            genomeData.css('width', '');

            // Ugly way to make table columns show/hide on init as requested
            var checkbox_settings = [
                false, // RSID
                false, // CHROMOSOME POS
                false, // RISK ALLELE
                true, // GENOTYPE
                true, // DISEASE TRAIT
                false, // P VALUE
                false, // OR
                false, // RISK
                false, // PRIORITY
                false, // TAGS
                false  // CATEGORY COLOR
            ];
            $('.table-settings').data('default-values', checkbox_settings);
            reset_checkboxes($('.table-settings').data('default-values'));

        }
    }).columnFilter({ sPlaceHolder: "head:after",
        aoColumns: [
            { type: "number-range" },
            { type: "number-range" },
            { type: "select" },
            { type: "select" },
            { type: "select" },
            { type: "number-range" },
            { type: "number-range" },
            { type: "select" },
            { type: "number-range" },
            { type: "select" },
            { type: "select" },
            { type: "select" }
        ]
    });
});

var progressbar = $('.progress-bar');
var interval;

function updateBar(values) {
    var l = values.received;
    var tot = values.size;

    var perc = (l / tot) * (100.00);
    progressbar.css('width', perc + '%');
    progressbar.text(perc + '%');
    if (values.status === 'done') {
        window.clearInterval(interval);
    }
}

$("form#upload_form").submit(function(e){
    $('form#upload_form input[type=submit]').hide();
    progressbar.parent().show();
    var getProgress = function() {
        $.ajax({
            url: "/progress",
            headers: {"X-Progress-ID": $('#progress-bar').data('upload_id')},
            dataType: 'json',
            success: function(data) {
                updateBar(data);
            }
        });
    };
    interval = window.setInterval(getProgress, 1000);
});

$('.genomeData_advanced').click(function(e) {
    $('#genomeData thead tr.filter-visiblity, .dataTables_length, .dataTables_filter, .table-settings').toggle();
});

$(".checkbox-row input").change(function() {
    var checked = $(this).is(":checked");
    var index = $(this).parent().parent().index();
    $('#genomeData tbody tr').each(function() {
        var $cell = $(this).find("td").eq(index);
        if(checked) {
            $cell.show();
        } else {
            $cell.hide();
        }
        $('td.first', this).removeClass('first');
        $('td:visible:first', this).addClass('first');
    });
    $('#genomeData thead tr').each(function() {
        if(checked) {
            $(this).find("th").eq(index).show();
        } else {
            $(this).find("th").eq(index).hide();
        }
    });
    $('#genomeData tfoot tr').each(function() {
        if(checked) {
            $(this).find("th").eq(index).show();
        } else {
            $(this).find("th").eq(index).hide();
        }
    });
});
$(".table-settings .defaultbutton").click(function() {
    reset_checkboxes($('.table-settings').data('default-values'));
    return false;
});

$('.filter_labels h3 span.label').on('click', function(e) {
    var label = $(e.delegateTarget),
        labelColorOff = label.data('color-off'),
        labelColorOn = label.data('color-on');
    label.toggleClass('tag-checked');
    if (label.hasClass('tag-checked')) {
        label.css('background-color', labelColorOn);
    } else {
        label.css('background-color', labelColorOff);
    }
    genomeData.DataTable().draw();
});

$('.category_labels h2 span.label').on('click', function(e) {
    var category = $(e.delegateTarget);
    category.toggleClass('tag-checked');
    genomeData.DataTable().draw();
});

/**
 * Layout expand
 */
function setLayout() {
    if(window.localStorage['expand'] == 'true') {
        $('.layout').removeClass('container container-fluid').addClass('container-fluid')
        $('[data-toggle=layout-fluid] .glyphicon.glyphicon-resize-full').removeClass('glyphicon-resize-full').addClass('glyphicon-resize-small')
    } else {
        $('.layout').removeClass('container container-fluid').addClass('container')
        $('[data-toggle=layout-fluid] .glyphicon.glyphicon-resize-small').removeClass('glyphicon-resize-small').addClass('glyphicon-resize-full')
    }
}

//setLayout();

$('[data-toggle=layout-fluid]').click(function() {
    window.localStorage['expand'] = String(!(window.localStorage['expand'] == 'true'));
    setLayout();
    return false;
});

if (window.location.href === '/disease/browse/') {
    (function poll(){
        setTimeout(function(){
            if ($('.alert.alert-info').length) {
                location.reload();
                poll();
            }
        }, 1000);
    })();
}

$(function() {
    $(window).scroll(function() {
        var doc_top = $(document).scrollTop();
        var doc_height = $(window).height();
        var border_top = $('#genomeData').offset().top;
        var border_bottom = $('footer').offset().top;
        $('.stay-visible').each(function() {
            var $this = $(this);
            if (!$this.data('original_top')) {
                var elem_offset = $this.offset()
                $this.data('original_top', elem_offset.top);
                $this.css('position', 'absolute').css('top', elem_offset.top).css('left', elem_offset.left);
            }
            var elem_top = $this.data('original_top');
            var elem_bottom = elem_top + $this.height();
            var computed_top;

            if (doc_top + doc_height > elem_bottom) {
                if ($this.height() < doc_height) {
                    computed_top = doc_top;
                } else {
                    computed_top = doc_top + doc_height - $this.height();
                }
            } else {
                computed_top = elem_top;
            }

            if (computed_top < border_top) {
                computed_top = border_top;
            } else if (computed_top > border_bottom) {
                computed_top = border_bottom - $this.height();
            }

            $this.css('top', computed_top);
        });
    });
});
<commit_msg> Floating right pane genome description #1<commit_after>$.cssHooks.backgroundColor = {
    get: function(elem) {
        if (elem.currentStyle)
            var bg = elem.currentStyle["backgroundColor"];
        else if (window.getComputedStyle)
            var bg = document.defaultView.getComputedStyle(elem,
                null).getPropertyValue("background-color");
        if (bg.search("rgb") == -1)
            return bg;
        else {
            bg = bg.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            function hex(x) {
                return ("0" + parseInt(x).toString(16)).slice(-2);
            }
            return "#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3]);
        }
    }
};

$.fn.dataTableExt.oSort['numeric_ignore_nan-asc']  = function(x,y) {
    if (isNaN(x) && isNaN(y)) return ((x < y) ? 1 : ((x > y) ?  -1 : 0));

    if (isNaN(x)) return 1;
    if (isNaN(y)) return -1;

    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ? -1 : ((x > y) ?  1 : 0));
};

$.fn.dataTableExt.oSort['numeric_ignore_nan-desc'] = function(x,y) {
    if (isNaN(x) && isNaN(y)) return ((x < y) ? 1 : ((x > y) ?  -1 : 0));

    if (isNaN(x)) return 1;
    if (isNaN(y)) return -1;

    x = parseFloat( x );
    y = parseFloat( y );
    return ((x < y) ?  1 : ((x > y) ? -1 : 0));
};

$.fn.dataTableExt.afnFiltering.push(
    function(oSettings, aData, iDataIndex) {
        var selected_tags = $('.filter_labels h3 span.tag-checked').map(function(k, v) {
                return $(this).text();
            }).get(),
            row_tags = aData[9].split(',');

        if (!selected_tags.length) { // nothing to filter out
            return true;
        } else {
            if (!row_tags.length || (row_tags.length === 1 && row_tags[0] === "")) {
                return false;
            }
            for (var i = 0; i < selected_tags.length; i++) {
                for (var j = 0; j < row_tags.length; j++) {
                    if (selected_tags[i] === row_tags[j]) {
                        return true;
                    }
                }
            }
            return false;
        }
    }
);

$.fn.dataTableExt.afnFiltering.push(
    function(oSettings, aData, iDataIndex) {
        var selected_categories = $('.category_labels h2 span.tag-checked').map(function(k, v) {
                return $(this).css('background-color');
            }).get(),
            row_color = aData[10];
        if (!selected_categories.length) { // nothing to filter out
            return true;
        } else {
            for (var i = 0; i < selected_categories.length; i++) {
                if (selected_categories[i] === row_color) {
                    return true;
                }
            }
        }
        return false;
    }
);

var genomeData = $('#genomeData');
var reset_checkboxes = function(checkbox_settings) {
    var checkboxes = $(".checkbox-row input");
    checkbox_settings.forEach(function(element, index) {
        var checkbox = $(checkboxes[index]);
        checkbox.prop('checked', element).trigger('change');
    });

};
$(document).ready(function() {
    var genome_url = genomeData.data('genome_url');
    var genomeTable = genomeData.dataTable({
        "ajax": genome_url,
        "columns": [
            {"data": "rsid" },
            {"data": "chromosome_position" },
            {"data": "risk_allele" },
            {"data": "genotype" },
            {"data": "disease_trait" },
            {"data": "p_value" },
            {"data": "or_or_beta" },
            {"data": "risk" },
            {"data": "priority", "defaultContent": "0" },
            {"data": "tags", "defaultContent": " "},
            {"data": "color", "defaultContent": ""}
        ],
        "pageLength": 100,
        //'bSort': false,
        "aoColumnDefs": [
            { "sType": "numeric_ignore_nan", "aTargets": [ 5, 6 ] },
            { "bSearchable": false, "bVisible": false, "aTargets": [ 8 ] }
        ],
        "columnDefs": [{"targets": [ 8 ], "visible": false, "searchable": false}],
        "order": [[ 8, "desc" ]],
        "processing": true,
        "rowCallback": function(row, data, index) {
            var $row = $(row);
            $row.data('url', encodeURI(data['link'] + '?allele=' + data['genotype']));
            $('td:not(.color-marked)', row).prepend(' ').addClass('color-marked');
        },
        "drawCallback": function( settings ) {
            var rows = $('#genomeData tbody tr');

            // Remove existing event handlers;
            rows.off('click');

            rows.click(function(e) {
                e.preventDefault();
                var row = $(this);
                var destination = $('#genomeDataDestination');
                var doc_top = $(document).scrollTop()+100;
                var table_top = $('#genomeData tbody').offset().top;
                var computed_top;
                if (doc_top > table_top) {
                    computed_top = doc_top;
                } else {
                    computed_top = table_top;
                }
                destination.text('Loading...').data('original_top', computed_top);
                $(window).scroll();
                $.get(row.data('url'), {'ajax':'1'})
                .fail(function(data) {
                    destination.text('error\n'+data.statusCode()+' '+data.statusText+'\n\n'+data.responseText);
                    $(window).scroll();
                })
                .done(function(data) {
                    destination.html(data);
                    $(window).scroll();
                });
                return false;
                window.open(row.data('url'), 'Your genome', "height=" + window.screen.height +",width=" + window.screen.width);
            });
            // Fix datatable for fluid container
            genomeData.css('width', '');

            // Ugly way to make table columns show/hide on init as requested
            var checkbox_settings = [
                false, // RSID
                false, // CHROMOSOME POS
                false, // RISK ALLELE
                true, // GENOTYPE
                true, // DISEASE TRAIT
                false, // P VALUE
                false, // OR
                false, // RISK
                false, // PRIORITY
                false, // TAGS
                false  // CATEGORY COLOR
            ];
            $('.table-settings').data('default-values', checkbox_settings);
            reset_checkboxes($('.table-settings').data('default-values'));

        }
    }).columnFilter({ sPlaceHolder: "head:after",
        aoColumns: [
            { type: "number-range" },
            { type: "number-range" },
            { type: "select" },
            { type: "select" },
            { type: "select" },
            { type: "number-range" },
            { type: "number-range" },
            { type: "select" },
            { type: "number-range" },
            { type: "select" },
            { type: "select" },
            { type: "select" }
        ]
    });
});

var progressbar = $('.progress-bar');
var interval;

function updateBar(values) {
    var l = values.received;
    var tot = values.size;

    var perc = (l / tot) * (100.00);
    progressbar.css('width', perc + '%');
    progressbar.text(perc + '%');
    if (values.status === 'done') {
        window.clearInterval(interval);
    }
}

$("form#upload_form").submit(function(e){
    $('form#upload_form input[type=submit]').hide();
    progressbar.parent().show();
    var getProgress = function() {
        $.ajax({
            url: "/progress",
            headers: {"X-Progress-ID": $('#progress-bar').data('upload_id')},
            dataType: 'json',
            success: function(data) {
                updateBar(data);
            }
        });
    };
    interval = window.setInterval(getProgress, 1000);
});

$('.genomeData_advanced').click(function(e) {
    $('#genomeData thead tr.filter-visiblity, .dataTables_length, .dataTables_filter, .table-settings').toggle();
});

$(".checkbox-row input").change(function() {
    var checked = $(this).is(":checked");
    var index = $(this).parent().parent().index();
    $('#genomeData tbody tr').each(function() {
        var $cell = $(this).find("td").eq(index);
        if(checked) {
            $cell.show();
        } else {
            $cell.hide();
        }
        $('td.first', this).removeClass('first');
        $('td:visible:first', this).addClass('first');
    });
    $('#genomeData thead tr').each(function() {
        if(checked) {
            $(this).find("th").eq(index).show();
        } else {
            $(this).find("th").eq(index).hide();
        }
    });
    $('#genomeData tfoot tr').each(function() {
        if(checked) {
            $(this).find("th").eq(index).show();
        } else {
            $(this).find("th").eq(index).hide();
        }
    });
});
$(".table-settings .defaultbutton").click(function() {
    reset_checkboxes($('.table-settings').data('default-values'));
    return false;
});

$('.filter_labels h3 span.label').on('click', function(e) {
    var label = $(e.delegateTarget),
        labelColorOff = label.data('color-off'),
        labelColorOn = label.data('color-on');
    label.toggleClass('tag-checked');
    if (label.hasClass('tag-checked')) {
        label.css('background-color', labelColorOn);
    } else {
        label.css('background-color', labelColorOff);
    }
    genomeData.DataTable().draw();
});

$('.category_labels h2 span.label').on('click', function(e) {
    var category = $(e.delegateTarget);
    category.toggleClass('tag-checked');
    genomeData.DataTable().draw();
});

/**
 * Layout expand
 */
function setLayout() {
    if(window.localStorage['expand'] == 'true') {
        $('.layout').removeClass('container container-fluid').addClass('container-fluid')
        $('[data-toggle=layout-fluid] .glyphicon.glyphicon-resize-full').removeClass('glyphicon-resize-full').addClass('glyphicon-resize-small')
    } else {
        $('.layout').removeClass('container container-fluid').addClass('container')
        $('[data-toggle=layout-fluid] .glyphicon.glyphicon-resize-small').removeClass('glyphicon-resize-small').addClass('glyphicon-resize-full')
    }
}

//setLayout();

$('[data-toggle=layout-fluid]').click(function() {
    window.localStorage['expand'] = String(!(window.localStorage['expand'] == 'true'));
    setLayout();
    return false;
});

if (window.location.href === '/disease/browse/') {
    (function poll(){
        setTimeout(function(){
            if ($('.alert.alert-info').length) {
                location.reload();
                poll();
            }
        }, 1000);
    })();
}

$(function() {
    $(window).scroll(function() {
        var doc_top = $(document).scrollTop();
        var doc_height = $(window).height();
        var border_top = $('#genomeData tbody').offset().top;
        var border_bottom = $('footer').offset().top;
        $('.stay-visible').each(function() {
            var $this = $(this);
            if (!$this.data('original_top')) {
                var elem_offset = $this.offset()
                $this.data('original_top', elem_offset.top);
                $this.css('position', 'absolute').css('top', elem_offset.top).css('left', elem_offset.left);
            }
            var elem_top = $this.data('original_top');
            var elem_bottom = elem_top + $this.height();
            var computed_top;

            if (doc_top + doc_height > elem_bottom) {
                if ($this.height() < doc_height) {
                    computed_top = doc_top;
                } else {
                    computed_top = doc_top + doc_height - $this.height();
                }
            } else {
                computed_top = elem_top;
            }

            if (computed_top < border_top) {
                computed_top = border_top;
            } else if (computed_top > border_bottom) {
                computed_top = border_bottom - $this.height();
            }

            $this.css('top', computed_top);
        });
    });
});
<|endoftext|>


<commit_before>/*eslint require-jsdoc: 0, valid-jsdoc: 0*/

import LZString from "lz-string";

/**
 * Compressing an object into a sendable string
 *
 * @param {Object} object object to compress
 */
function compress(object) {
  return LZString.compressToBase64(JSON.stringify(object))
    .replace(/\+/g, "-") // Convert '+' to '-'
    .replace(/\//g, "_") // Convert '/' to '_'
    .replace(/=+$/, ""); // Remove ending '='
}

/**
 * Creating an hidden input to send the codesandbox
 */
function addHiddenInput(form, name, value) {
  const input = document.createElement("input");
  input.type = "hidden";
  input.name = name;
  input.value = value;
  form.appendChild(input);
}

/**
 * Content of the index.js file
 */
function getIndexFile() {
  return `import React from "react";
import ReactDOM from "react-dom";
import { Graph } from "react-d3-graph";

import config from "./config";
import data from "./data";

const rootElement = document.getElementById("root");
ReactDOM.render(<Graph id="graph" config={config} data={data} />, rootElement);`.trim();
}

/**
 * Formatting file into a sendable string
 * @param {*} json object to send
 */
function formatFile(json) {
  return `module.exports = ${JSON.stringify(json)}`;
}

/**
 * Create and send the code sandbox from the current sandbox data
 * @param {*} config current sandbox config
 * @param {*} data current sandbox data
 */
export function createCodeSandbox(config, data) {
  const parameters = compress({
    files: {
      "package.json": {
        content: {
          title: "react-d3-graph demo",
          dependencies: {
            "react-dom": "latest",
            react: "latest",
            "react-d3-graph": "latest",
            d3: "5.5.0",
          },
        },
      },
      "index.js": { content: getIndexFile() },
      "config.js": { content: formatFile(config) },
      "data.js": { content: formatFile(data) },
    },
  });

  const form = document.createElement("form");
  form.method = "POST";
  form.target = "_blank";
  form.action = "https://codeSandbox.io/api/v1/sandboxes/define";
  addHiddenInput(form, "parameters", parameters);
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}

/**
 * We deactivate code sandboxes link generation for sandboxes that
 * have a view generator
 * See : https://github.com/danielcaldas/react-d3-graph/pull/417#issuecomment-763051874
 */
export function deactivateCodeSandboxLink(config) {
  return config.node?.viewGenerator;
}
<commit_msg>docs: some nit details on jsdoc for new module createCodeSandbox<commit_after>import LZString from "lz-string";

/**
 * Compressing an object into a sendable string
 * lz-string API: https://pieroxy.net/blog/pages/lz-string/index.html
 * @param {Object} object object to compress
 * @returns {string} base64 encoded string
 */
function compress(object) {
  return LZString.compressToBase64(JSON.stringify(object))
    .replace(/\+/g, "-") // Convert '+' to '-'
    .replace(/\//g, "_") // Convert '/' to '_'
    .replace(/=+$/, ""); // Remove ending '='
}

/**
 * Creating an hidden input to send the codesandbox
 * @param {HTMLFormElement} form target to add the hidden input
 * @param {string} name input name
 * @param {string} value input value
 * @returns {undefined}
 */
function addHiddenInput(form, name, value) {
  const input = document.createElement("input");
  input.type = "hidden";
  input.name = name;
  input.value = value;
  form.appendChild(input);
}

/**
 * Content of the index.js file
 * @returns {string} index file code in a string
 */
function getIndexFile() {
  return `import React from "react";
import ReactDOM from "react-dom";
import { Graph } from "react-d3-graph";

import config from "./config";
import data from "./data";

const rootElement = document.getElementById("root");
ReactDOM.render(<Graph id="graph" config={config} data={data} />, rootElement);`.trim();
}

/**
 * Formatting file into a sendable string
 * @param {Object} json object to send
 * @returns {string} exports statement
 */
function formatFile(json) {
  return `module.exports = ${JSON.stringify(json)}`;
}

/**
 * Create and send the code sandbox from the current sandbox data
 * @param {Object} config current sandbox config
 * @param {Object} data current sandbox data
 * @returns {undefined}
 */
export function createCodeSandbox(config, data) {
  const parameters = compress({
    files: {
      "package.json": {
        content: {
          title: "react-d3-graph demo",
          dependencies: {
            "react-dom": "latest",
            react: "latest",
            "react-d3-graph": "latest",
            d3: "5.5.0",
          },
        },
      },
      "index.js": { content: getIndexFile() },
      "config.js": { content: formatFile(config) },
      "data.js": { content: formatFile(data) },
    },
  });

  const form = document.createElement("form");
  form.method = "POST";
  form.target = "_blank";
  form.action = "https://codeSandbox.io/api/v1/sandboxes/define";
  addHiddenInput(form, "parameters", parameters);
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}

/**
 * We deactivate code sandboxes link generation for sandboxes that
 * have a view generator
 * See : https://github.com/danielcaldas/react-d3-graph/pull/417#issuecomment-763051874
 * @param {Object} config react-d3-graph config
 * @returns {boolean} true if the code sandbox link should not apply
 */
export function deactivateCodeSandboxLink(config) {
  return !!config.node?.viewGenerator;
}
<|endoftext|>


<commit_before>chrome.runtime.onInstalled.addListener(() => {
  chrome.alarms.create("checkmessages", {
    periodInMinutes: 1
  })

  chrome.storage.sync.get(["fixedNavbar", "notify", "bbDiscuss", "bbwiki", "badge", "searchEngine"], (v) => {
    if (v["fixedNavbar"] == null || v["fixedNavbar"] == undefined) {
      chrome.storage.sync.set({fixedNavbar: true}, () => {});
    }
    if (v["notify"] == null || v["notify"] == undefined) {
      chrome.storage.sync.set({notify: true}, () => {});
    }
    if (v["bbDiscuss"] == null || v["bbDiscuss"] == undefined) {
      chrome.storage.sync.set({bbDiscuss: true}, () => {});
    }
    if (v["bbWiki"] == null || v["bbWiki"] == undefined) {
      chrome.storage.sync.set({bbWiki: false}, () => {});
    }
    if (v["badge"] == null || v["badge"] == undefined) {
      chrome.storage.sync.set({badge: true}, () => {});
    }
    if (v["searchEngine"] == null || v["searchEngine"] == undefined) {
      chrome.storage.sync.set({searchEngine: "google"}, () => {});
    }
  });
});

chrome.alarms.onAlarm.addListener(a => {
  console.log("Alarm recieved.");
  chrome.storage.sync.get(["username", "notify", "prevNotificationAmt"], ({username, notify, prevNotificationAmt}) => {
    if (a.name === "checkmessages" && notify) {
      console.log("Check recieved.");
      if (username !== "") {
        console.log("Checking messages...");
        fetch(`https://api.scratch.mit.edu/proxy/users/${username}/activity/count`).then(r => r.json()).then(({msg_count}) => {
          console.log("Diff n, o, in", msg_count, prevNotificationAmt, msg_count > prevNotificationAmt);
          if (msg_count > 0) {
            if (msg_count > prevNotificationAmt) {
              chrome.notifications.create({
                type: "basic",
                iconUrl: "icon128x128.png",
                title: "New Scratch Message" + (msg_count - prevNotificationAmt > 1 ? "s" : "") + "!",
                message: "You now have " + msg_count + " message" + (msg_count === 1 ? "" : "s") + " on Scratch, click to view."
              });
            }
            chrome.browserAction.setBadgeText({text: (badge ? msg_count : "") + ""});
          }else{
            chrome.browserAction.setBadgeText({text: ""});
          }
          chrome.storage.sync.set({prevNotificationAmt: msg_count}, () => {});
        });
      }
    }
  });
});

chrome.notifications.onClicked.addListener(id => {
  chrome.tabs.create({
    url: "https://scratch.mit.edu/messages"
  });
});

chrome.storage.onChanged.addListener((c, n) => {
  if (n === "sync") {
    username = (c.username || {newValue: username}).newValue;
    notify = (c.notify || {newValue: notify}).newValue;
    badge = (c.badge || {newValue: badge}).newValue;
  }
});

chrome.browserAction.onClicked.addListener(() => {
  chrome.tabs.create({
    url: "https://scratch.mit.edu/messages"
  });
});
<commit_msg>Didn't save<commit_after>chrome.runtime.onInstalled.addListener(() => {
  chrome.alarms.create("checkmessages", {
    periodInMinutes: 1
  })

  chrome.storage.sync.get(["fixedNavbar", "notify", "bbDiscuss", "bbwiki", "badge", "searchEngine"], (v) => {
    if (v["fixedNavbar"] == null || v["fixedNavbar"] == undefined) {
      chrome.storage.sync.set({fixedNavbar: true}, () => {});
    }
    if (v["notify"] == null || v["notify"] == undefined) {
      chrome.storage.sync.set({notify: true}, () => {});
    }
    if (v["bbDiscuss"] == null || v["bbDiscuss"] == undefined) {
      chrome.storage.sync.set({bbDiscuss: true}, () => {});
    }
    if (v["bbWiki"] == null || v["bbWiki"] == undefined) {
      chrome.storage.sync.set({bbWiki: false}, () => {});
    }
    if (v["badge"] == null || v["badge"] == undefined) {
      chrome.storage.sync.set({badge: true}, () => {});
    }
    if (v["searchEngine"] == null || v["searchEngine"] == undefined) {
      chrome.storage.sync.set({searchEngine: "google"}, () => {});
    }
  });
});

chrome.alarms.onAlarm.addListener(a => {
  console.log("Alarm recieved.");
  chrome.storage.sync.get(["username", "notify", "prevNotificationAmt", "badge"], ({username, notify, prevNotificationAmt, badge}) => {
    if (a.name === "checkmessages" && notify) {
      console.log("Check recieved.");
      if (username !== "") {
        console.log("Checking messages...");
        fetch(`https://api.scratch.mit.edu/proxy/users/${username}/activity/count`).then(r => r.json()).then(({msg_count}) => {
          console.log("Diff n, o, in", msg_count, prevNotificationAmt, msg_count > prevNotificationAmt);
          if (msg_count > 0) {
            if (msg_count > prevNotificationAmt) {
              chrome.notifications.create({
                type: "basic",
                iconUrl: "icon128x128.png",
                title: "New Scratch Message" + (msg_count - prevNotificationAmt > 1 ? "s" : "") + "!",
                message: "You now have " + msg_count + " message" + (msg_count === 1 ? "" : "s") + " on Scratch, click to view."
              });
            }
            chrome.browserAction.setBadgeText({text: (badge ? msg_count : "") + ""});
          }else{
            chrome.browserAction.setBadgeText({text: ""});
          }
          chrome.storage.sync.set({prevNotificationAmt: msg_count}, () => {});
        });
      }
    }
  });
});

chrome.notifications.onClicked.addListener(id => {
  chrome.tabs.create({
    url: "https://scratch.mit.edu/messages"
  });
});

chrome.browserAction.onClicked.addListener(() => {
  chrome.tabs.create({
    url: "https://scratch.mit.edu/messages"
  });
});
<|endoftext|>


<commit_before>import React from 'react'
import { connect } from 'react-redux'

const LeadDetail = (props) => {
  if (props.lead) {
    return (

Lead Details

        {props.lead.name}

    )
  } else {
    return null
  }
}

export default connect((state, ownProps) => {
  const id = ownProps.match.params.id
  const lead = state.households.find(h => h.id === id)
  return {
    lead
  }
})(LeadDetail)
<commit_msg>Add parseInt to find method<commit_after>import React from 'react'
import { connect } from 'react-redux'

const LeadDetail = (props) => {
  if (props.lead) {
    return (

Lead Details

        {props.lead.name}

    )
  } else {
    return null
  }
}

export default connect((state, ownProps) => {
  const id = parseInt(ownProps.match.params.id, 10)
  const lead = state.households.find(h => h.id === id)
  return {
    lead
  }
})(LeadDetail)
<|endoftext|>


<commit_before>/*
 * Carries out actions for the error messages component
 */

import { ERROR_MESSAGE_DELAY, ERROR_CLOSE_TIME } from '../misc/config';

export const rErrorMessageOpen = (reduction, msg) => {
  const errorMsg = reduction.getIn(['appState', 'errorMsg']);
  const item = msg.set('id', errorMsg.size)
  .set('time', new Date().getTime());

  return reduction.setIn(['appState', 'errorMsg'], errorMsg.push(item));
};
export const rErrorMessageClose = (reduction, msgId) => {
  return reduction.setIn(
    ['appState', 'errorMsg'], reduction.getIn(['appState', 'errorMsg']).map(msg => {
      if (msg.get('id') === msgId) {
        return msg.set('closed', true);
      }
      return msg;
    }));
};
export const rErrorMessageRemove = (reduction, msgId) => {
  return reduction.setIn(
    ['appState', 'errorMsg'], reduction.getIn(['appState', 'errorMsg']).filter(
      msg => msg.get('id') !== msgId
    ));
};

export const rErrorMessageClearOld = reduction => {
  // automatically clear any messages which are older than the timeout period
  const msgs = reduction.getIn(['appState', 'errorMsg']);
  const now = new Date().getTime();
  let newReduction = reduction;

  msgs.forEach((msg, key) => {
    const closed = msg.get('closed');
    const age = now - msg.get('time');
    if (!closed) {
      // check if we need to close it
      if (age >= ERROR_MESSAGE_DELAY) {
        newReduction = newReduction.setIn(
          ['appState', 'errorMsg', key, 'closed'], true
        ).setIn(
          ['appState', 'errorMsg', key, 'time'], now
        );
      }
    }
    else {
      // check if we need to delete it
      if (age > ERROR_CLOSE_TIME) {
        newReduction = rErrorMessageRemove(newReduction, msg.get('id'));
      }
    }
  });

  return newReduction;
};

<commit_msg>Fix error message close time import<commit_after>/*
 * Carries out actions for the error messages component
 */

import { ERROR_MESSAGE_DELAY } from '../misc/config';
import { ERROR_CLOSE_TIME } from '../misc/const';

export const rErrorMessageOpen = (reduction, msg) => {
  const errorMsg = reduction.getIn(['appState', 'errorMsg']);
  const item = msg.set('id', errorMsg.size)
  .set('time', new Date().getTime());

  return reduction.setIn(['appState', 'errorMsg'], errorMsg.push(item));
};
export const rErrorMessageClose = (reduction, msgId) => {
  return reduction.setIn(
    ['appState', 'errorMsg'], reduction.getIn(['appState', 'errorMsg']).map(msg => {
      if (msg.get('id') === msgId) {
        return msg.set('closed', true);
      }
      return msg;
    }));
};
export const rErrorMessageRemove = (reduction, msgId) => {
  return reduction.setIn(
    ['appState', 'errorMsg'], reduction.getIn(['appState', 'errorMsg']).filter(
      msg => msg.get('id') !== msgId
    ));
};

export const rErrorMessageClearOld = reduction => {
  // automatically clear any messages which are older than the timeout period
  const msgs = reduction.getIn(['appState', 'errorMsg']);
  const now = new Date().getTime();
  let newReduction = reduction;

  msgs.forEach((msg, key) => {
    const closed = msg.get('closed');
    const age = now - msg.get('time');
    if (!closed) {
      // check if we need to close it
      if (age >= ERROR_MESSAGE_DELAY) {
        newReduction = newReduction.setIn(
          ['appState', 'errorMsg', key, 'closed'], true
        ).setIn(
          ['appState', 'errorMsg', key, 'time'], now
        );
      }
    }
    else {
      // check if we need to delete it
      if (age > ERROR_CLOSE_TIME) {
        newReduction = rErrorMessageRemove(newReduction, msg.get('id'));
      }
    }
  });

  return newReduction;
};

<|endoftext|>


<commit_before>var dashboardView = Backbone.View.extend({
  el: '#content',
  updateInterval: 1000, // 1 second, constant
  updateFrequency: 5, // the actual update rate (5 s)
  updateCounter: 0,
  arraySize: 99, // how many values will we keep per figure?
  seriesData: {},
  charts: {},
  units: [],
  detailGraph: "userTime",

  initialize: function () {
    var self = this;

    this.initUnits();

    this.collection.fetch({
      success: function() {
        self.calculateSeries();
        self.renderCharts();

        window.setInterval(function() {
          self.updateCounter++;

          if (self.updateCounter < self.updateFrequency) {
            return false;
          }

          self.updateCounter = 0;
          self.collection.fetch({
            success: function() {
              self.calculateSeries();
              self.renderCharts();
            },
            error: function() {
              // need to flush previous values
              self.calculateSeries(true);
              self.renderCharts();
              arangoHelper.arangoError("Lost connection to Database!");
            }
          });

        }, self.updateInterval);
      }
    });
  },

  events: {
    "click .dashboard-dropdown li" : "checkEnabled",
    "click .interval-dropdown li" : "checkInterval",
    "click .db-zoom" : "renderDetailChart",
    "click .db-minimize" : "checkDetailChart",
    "click .db-hide" : "hideChart"
  },

  template: new EJS({url: 'js/templates/dashboardView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);

    //Client calculated charts
    self.genCustomCategories();
    self.genCustomChartDescription(
      "userTime + systemTime",
      "custom",
      "totalTime2",
      "Total Time (User+System)",
      "accumulated",
      "seconds"
    );

    $.each(this.options.description.models[0].attributes.groups, function () {
      $('.thumbnails').append(
        '
' +
        '
' + this.name + '
' +
        '
');
      $('#menuGroups').append(
        '
' + this.name + '
' +
        '

'
      );
    });

    $.each(this.options.description.models[0].attributes.figures, function () {
      self.renderFigure(this);
    });

    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    if (this.collection.models[0] === undefined) {
      this.collection.fetch({
        success: function() {
          self.calculateSeries();
          self.renderCharts();
        },
        error: function() {
          self.calculateSeries();
          self.renderCharts(flush);
        }
      });
    }
    else {
      self.calculateSeries();
      self.renderCharts();
    }
    return this;
  },
  //generate function for all custom categories
  genCustomCategories: function () {
    this.genCustomCategory("Client calculated charts", "custom", "Customized Charts");
  },
  //generate a custom category
  genCustomCategory: function(description, group, name) {
    this.options.description.models[0].attributes.groups.push({
      "description":description,
      "group":group,
      "name":name
    });
  },
  //generate a custom description
  genCustomChartDescription: function (description, group, identifier, name, type, units) {
    var figure = {
      "description" : description,
      "group" : group,
      "identifier" : identifier,
      "name" : name,
      "type" : type,
      "units" : units
    };
    this.options.description.models[0].attributes.figures.push(figure);
    this.renderFigure(figure);
  },
  //calculate customized chart value functions here
  updateCustomChartValues: function ( {
    this.totalTime2();
  },

  //custom chart value calculation for totalTime2
  totalTime2: function () {
    var val1 = this.collection.models[0].attributes.system.userTime;
    var val2 = this.collection.models[0].attributes.system.systemTime;
    var totalTime2Value = val1+val2;
    this.collection.models[0].attributes["custom"] = {"totalTime2":totalTime2Value};
  },

  checkInterval: function (a) {
    this.updateFrequency = a.target.value;
    self.calculateSeries();
    self.renderCharts();
  },

  checkEnabled: function (a) {
    var myId = a.target.id;
    var position = myId.search('Checkbox');
    var preparedId = myId.substring(0, position);
    var toCheck = $(a.target).is(':checked');
    if (toCheck === false) {
      $("#" + preparedId).hide();
    }
    else if (toCheck === true) {
      $("#" + preparedId).show();
    }
  },

  initUnits : function () {
    this.units = [ ];
    var i;
    var scale = 0.0001;

    for (i = 0; i < 12; ++i) {
      this.units.push(scale * 1);
      this.units.push(scale * 2);
      this.units.push(scale * 2.5);
      this.units.push(scale * 4);
      this.units.push(scale * 5);
      scale *= 10;
    }
  },

  getMaxValue : function (identifier) {
    var max = this.seriesData[identifier].max || 1;

    var i = 0, n = this.units.length;
    while (i < n) {
      var unit = this.units[i++];
      if (max > unit) {
        continue;
      }
      if (max == unit) {
        break;
      }
      return unit;
    }

    return max;
  },

  checkDetailChart: function (a) {
    if ($(a.target).hasClass('icon-minus') === true) {
      $('#detailGraph').height(43);
      $('#detailGraphChart').hide();
      $(a.target).removeClass('icon-minus');
      $(a.target).addClass('icon-plus');
    }
    else {
      $('#detailGraphChart').show();
      $('#detailGraph').height(300);
      $(a.target).removeClass('icon-plus');
      $(a.target).addClass('icon-minus');
    }
  },

  hideChart: function (a) {
    var figure = $(a.target).attr("value");
    $('#'+figure+'Checkbox').prop('checked', false);
    $('#'+figure).hide();
  },

  renderDetailChart: function (a) {
    var self = this;
    self.detailGraph = $(a.target).attr("value");
    $.each(this.options.description.models[0].attributes.figures, function () {
      if(this.identifier === self.detailGraph) {
        $('#detailGraphHeader').text(this.name);
        self.calculateSeries();
        self.renderCharts();
        $("html, body").animate({ scrollTop: 0 }, "slow");
        $('#detailGraphChart').show();
        $('#detailGraph').height(300);
        $('#dbHideSwitch').addClass('icon-minus');
        $('#dbHideSwitch').removeClass('icon-plus');
      }
    });
  },

  renderCharts: function () {
    var self = this;
    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;
      var chart;

      if (self.charts[identifier] === undefined) {
        chart = self.charts[identifier] = nv.models.lineChart();
        chart.xAxis.axisLabel('').tickFormat(function (d) {
          if (isNaN(d)) {
            return '';
          }

          function pad (value) {
            return (value < 10 ? "0" + String(value) : String(value));
          }

          var date = new Date(d / 10);

          return pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
        });

        var label = figure.units;

        if (figure.units === 'bytes') {
          label = "megabytes";
        }
        chart.yAxis.axisLabel(label);

        nv.addGraph (function () {
          nv.utils.windowResize(function () {
            d3.select('#' + identifier + 'Chart svg').call(chart);
          });

          return chart;
        });
      }
      else {
        chart = self.charts[identifier];
      }

      chart.yDomain([ 0, self.getMaxValue(identifier) ]);

      if (self.detailGraph === undefined) {
        self.detailGraph = "userTime";
      }
      if (self.detailGraph === identifier) {
        d3.select("#detailGraphChart svg")
          .call(chart)
          .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
          .transition().duration(500);

      }

      d3.select("#" + identifier + "Chart svg")
        .call(chart)
        .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
        .transition().duration(500);
    });
  },

  calculateSeries: function (flush) {
    var self = this;
    self.updateCustomChartValues();

    var timeStamp = Math.round(new Date() * 10);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;

      if (self.seriesData[identifier] === undefined) {
        self.seriesData[identifier] = { max: 0, values: [ ] };
      }

      while (self.seriesData[identifier].values.length > self.arraySize) {
        self.seriesData[identifier].values.shift();
      }

      if (flush) {
        self.seriesData[identifier].values.push({ x: timeStamp, y: undefined, value: undefined });
        return;
      }

      var responseValue = self.collection.models[0].attributes[figure.group][identifier];

      if (responseValue !== undefined && responseValue !== null) {
        if (responseValue.sum !== undefined) {
          responseValue = responseValue.sum;
        }
      }

      function sanitize (value, figure) {
        if (value < 0) {
          value = 0;
        }
        else {
          if (figure.units === 'bytes') {
            value /= (1024 * 1024);
          }
          value = Math.round(value * 100) / 100;
        }

        return value;
      }

      var newValue = 0;

      if (figure.type === 'current') {
        newValue = responseValue;
      }
      else {
        var n = self.seriesData[identifier].values.length;

        if (responseValue !== undefined && n > 0) {
          var previous = self.seriesData[identifier].values[n - 1];
          if (previous.value !== undefined) {
            newValue = responseValue - previous.value;
          }
        }
      }

      newValue = sanitize(newValue, figure);
      if (newValue > self.seriesData[identifier].max) {
        self.seriesData[identifier].max = newValue;
      }

      self.seriesData[identifier].values.push({ x: timeStamp, y: newValue, value: responseValue });
    });
  },

  renderFigure: function (figure) {
    $('#' + figure.group).append(
      '
' +
      '

' + figure.name +
      '
'+
      '' +
      '' +
      '' +
      '
' +
      '
<svg class="svgClass"/>
' +
      '
'
    );

    $('#' + figure.group + 'Divider').before(
      '
'+
      '<input type="checkbox" id=' + figure.identifier + 'Checkbox checked>' + figure.name + '
'
    );
    $('.db-info').tooltip({
      placement: "top"
    });
  }

});
<commit_msg>syntaax error<commit_after>var dashboardView = Backbone.View.extend({
  el: '#content',
  updateInterval: 1000, // 1 second, constant
  updateFrequency: 5, // the actual update rate (5 s)
  updateCounter: 0,
  arraySize: 99, // how many values will we keep per figure?
  seriesData: {},
  charts: {},
  units: [],
  detailGraph: "userTime",

  initialize: function () {
    var self = this;

    this.initUnits();

    this.collection.fetch({
      success: function() {
        self.calculateSeries();
        self.renderCharts();

        window.setInterval(function() {
          self.updateCounter++;

          if (self.updateCounter < self.updateFrequency) {
            return false;
          }

          self.updateCounter = 0;
          self.collection.fetch({
            success: function() {
              self.calculateSeries();
              self.renderCharts();
            },
            error: function() {
              // need to flush previous values
              self.calculateSeries(true);
              self.renderCharts();
              arangoHelper.arangoError("Lost connection to Database!");
            }
          });

        }, self.updateInterval);
      }
    });
  },

  events: {
    "click .dashboard-dropdown li" : "checkEnabled",
    "click .interval-dropdown li" : "checkInterval",
    "click .db-zoom" : "renderDetailChart",
    "click .db-minimize" : "checkDetailChart",
    "click .db-hide" : "hideChart"
  },

  template: new EJS({url: 'js/templates/dashboardView.ejs'}),

  render: function() {
    var self = this;
    $(this.el).html(this.template.text);

    //Client calculated charts
    self.genCustomCategories();
    self.genCustomChartDescription(
      "userTime + systemTime",
      "custom",
      "totalTime2",
      "Total Time (User+System)",
      "accumulated",
      "seconds"
    );

    $.each(this.options.description.models[0].attributes.groups, function () {
      $('.thumbnails').append(
        '
' +
        '
' + this.name + '
' +
        '
');
      $('#menuGroups').append(
        '
' + this.name + '
' +
        '

'
      );
    });

    $.each(this.options.description.models[0].attributes.figures, function () {
      self.renderFigure(this);
    });

    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    if (this.collection.models[0] === undefined) {
      this.collection.fetch({
        success: function() {
          self.calculateSeries();
          self.renderCharts();
        },
        error: function() {
          self.calculateSeries();
          self.renderCharts(flush);
        }
      });
    }
    else {
      self.calculateSeries();
      self.renderCharts();
    }
    return this;
  },
  //generate function for all custom categories
  genCustomCategories: function () {
    this.genCustomCategory("Client calculated charts", "custom", "Customized Charts");
  },
  //generate a custom category
  genCustomCategory: function(description, group, name) {
    this.options.description.models[0].attributes.groups.push({
      "description":description,
      "group":group,
      "name":name
    });
  },
  //generate a custom description
  genCustomChartDescription: function (description, group, identifier, name, type, units) {
    var figure = {
      "description" : description,
      "group" : group,
      "identifier" : identifier,
      "name" : name,
      "type" : type,
      "units" : units
    };
    this.options.description.models[0].attributes.figures.push(figure);
    this.renderFigure(figure);
  },
  //calculate customized chart value functions here
  updateCustomChartValues: function () {
    this.totalTime2();
  },

  //custom chart value calculation for totalTime2
  totalTime2: function () {
    var val1 = this.collection.models[0].attributes.system.userTime;
    var val2 = this.collection.models[0].attributes.system.systemTime;
    var totalTime2Value = val1+val2;
    this.collection.models[0].attributes["custom"] = {"totalTime2":totalTime2Value};
  },

  checkInterval: function (a) {
    this.updateFrequency = a.target.value;
    self.calculateSeries();
    self.renderCharts();
  },

  checkEnabled: function (a) {
    var myId = a.target.id;
    var position = myId.search('Checkbox');
    var preparedId = myId.substring(0, position);
    var toCheck = $(a.target).is(':checked');
    if (toCheck === false) {
      $("#" + preparedId).hide();
    }
    else if (toCheck === true) {
      $("#" + preparedId).show();
    }
  },

  initUnits : function () {
    this.units = [ ];
    var i;
    var scale = 0.0001;

    for (i = 0; i < 12; ++i) {
      this.units.push(scale * 1);
      this.units.push(scale * 2);
      this.units.push(scale * 2.5);
      this.units.push(scale * 4);
      this.units.push(scale * 5);
      scale *= 10;
    }
  },

  getMaxValue : function (identifier) {
    var max = this.seriesData[identifier].max || 1;

    var i = 0, n = this.units.length;
    while (i < n) {
      var unit = this.units[i++];
      if (max > unit) {
        continue;
      }
      if (max == unit) {
        break;
      }
      return unit;
    }

    return max;
  },

  checkDetailChart: function (a) {
    if ($(a.target).hasClass('icon-minus') === true) {
      $('#detailGraph').height(43);
      $('#detailGraphChart').hide();
      $(a.target).removeClass('icon-minus');
      $(a.target).addClass('icon-plus');
    }
    else {
      $('#detailGraphChart').show();
      $('#detailGraph').height(300);
      $(a.target).removeClass('icon-plus');
      $(a.target).addClass('icon-minus');
    }
  },

  hideChart: function (a) {
    var figure = $(a.target).attr("value");
    $('#'+figure+'Checkbox').prop('checked', false);
    $('#'+figure).hide();
  },

  renderDetailChart: function (a) {
    var self = this;
    self.detailGraph = $(a.target).attr("value");
    $.each(this.options.description.models[0].attributes.figures, function () {
      if(this.identifier === self.detailGraph) {
        $('#detailGraphHeader').text(this.name);
        self.calculateSeries();
        self.renderCharts();
        $("html, body").animate({ scrollTop: 0 }, "slow");
        $('#detailGraphChart').show();
        $('#detailGraph').height(300);
        $('#dbHideSwitch').addClass('icon-minus');
        $('#dbHideSwitch').removeClass('icon-plus');
      }
    });
  },

  renderCharts: function () {
    var self = this;
    $('#every'+self.updateFrequency+'seconds').prop('checked',true);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;
      var chart;

      if (self.charts[identifier] === undefined) {
        chart = self.charts[identifier] = nv.models.lineChart();
        chart.xAxis.axisLabel('').tickFormat(function (d) {
          if (isNaN(d)) {
            return '';
          }

          function pad (value) {
            return (value < 10 ? "0" + String(value) : String(value));
          }

          var date = new Date(d / 10);

          return pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
        });

        var label = figure.units;

        if (figure.units === 'bytes') {
          label = "megabytes";
        }
        chart.yAxis.axisLabel(label);

        nv.addGraph (function () {
          nv.utils.windowResize(function () {
            d3.select('#' + identifier + 'Chart svg').call(chart);
          });

          return chart;
        });
      }
      else {
        chart = self.charts[identifier];
      }

      chart.yDomain([ 0, self.getMaxValue(identifier) ]);

      if (self.detailGraph === undefined) {
        self.detailGraph = "userTime";
      }
      if (self.detailGraph === identifier) {
        d3.select("#detailGraphChart svg")
          .call(chart)
          .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
          .transition().duration(500);

      }

      d3.select("#" + identifier + "Chart svg")
        .call(chart)
        .datum([ { values: self.seriesData[identifier].values, key: identifier, color: "#8AA051" } ])
        .transition().duration(500);
    });
  },

  calculateSeries: function (flush) {
    var self = this;
    self.updateCustomChartValues();

    var timeStamp = Math.round(new Date() * 10);

    $.each(self.options.description.models[0].attributes.figures, function () {
      var figure = this;
      var identifier = figure.identifier;

      if (self.seriesData[identifier] === undefined) {
        self.seriesData[identifier] = { max: 0, values: [ ] };
      }

      while (self.seriesData[identifier].values.length > self.arraySize) {
        self.seriesData[identifier].values.shift();
      }

      if (flush) {
        self.seriesData[identifier].values.push({ x: timeStamp, y: undefined, value: undefined });
        return;
      }

      var responseValue = self.collection.models[0].attributes[figure.group][identifier];

      if (responseValue !== undefined && responseValue !== null) {
        if (responseValue.sum !== undefined) {
          responseValue = responseValue.sum;
        }
      }

      function sanitize (value, figure) {
        if (value < 0) {
          value = 0;
        }
        else {
          if (figure.units === 'bytes') {
            value /= (1024 * 1024);
          }
          value = Math.round(value * 100) / 100;
        }

        return value;
      }

      var newValue = 0;

      if (figure.type === 'current') {
        newValue = responseValue;
      }
      else {
        var n = self.seriesData[identifier].values.length;

        if (responseValue !== undefined && n > 0) {
          var previous = self.seriesData[identifier].values[n - 1];
          if (previous.value !== undefined) {
            newValue = responseValue - previous.value;
          }
        }
      }

      newValue = sanitize(newValue, figure);
      if (newValue > self.seriesData[identifier].max) {
        self.seriesData[identifier].max = newValue;
      }

      self.seriesData[identifier].values.push({ x: timeStamp, y: newValue, value: responseValue });
    });
  },

  renderFigure: function (figure) {
    $('#' + figure.group).append(
      '
' +
      '

' + figure.name +
      '
'+
      '' +
      '' +
      '' +
      '
' +
      '
<svg class="svgClass"/>
' +
      '
'
    );

    $('#' + figure.group + 'Divider').before(
      '
'+
      '<input type="checkbox" id=' + figure.identifier + 'Checkbox checked>' + figure.name + '
'
    );
    $('.db-info').tooltip({
      placement: "top"
    });
  }

});
<|endoftext|>


<commit_before>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP

export { default as Accordion } from './components/Accordion';
export { default as AccordionPanel } from './components/AccordionPanel';
export { default as Anchor } from './components/Anchor';
export { default as Animate } from './components/Animate';
export { default as App } from './components/App';
export { default as Article } from './components/Article';
export { default as Box } from './components/Box';
export { default as Button } from './components/Button';
export { default as Card } from './components/Card';
export { default as Carousel } from './components/Carousel';
export * from './components/chart';
export { default as CheckBox } from './components/CheckBox';
export { default as Columns } from './components/Columns';
export { default as DateTime } from './components/DateTime';
export { default as Distribution } from './components/Distribution';
export { default as Footer } from './components/Footer';
export { default as Form } from './components/Form';
export { default as FormattedMessage } from './components/FormattedMessage';
export { default as FormField } from './components/FormField';
export { default as FormFields } from './components/FormFields';
export { default as Grommet } from './components/Grommet';
export { default as Header } from './components/Header';
export { default as Heading } from './components/Heading';
export { default as Headline } from './components/Headline';
export { default as Hero } from './components/Hero';
export { default as Image } from './components/Image';
export { default as Label } from './components/Label';
export { default as Layer } from './components/Layer';
export { default as Legend } from './components/Legend';
export { default as List } from './components/List';
export { default as ListItem } from './components/ListItem';
export { default as LoginForm } from './components/LoginForm';
export { default as Map } from './components/Map';
export { default as Markdown } from './components/Markdown';
export { default as Menu } from './components/Menu';
export { default as Meter } from './components/Meter';
export { default as Notification } from './components/Notification';
export { default as NumberInput } from './components/NumberInput';
export { default as Object } from './components/Object';
export { default as Paragraph } from './components/Paragraph';
export { default as Quote } from './components/Quote';
export { default as RadioButton } from './components/RadioButton';
export { default as Search } from './components/Search';
export { default as SearchInput } from './components/SearchInput';
export { default as Section } from './components/Section';
export { default as Select } from './components/Select';
export { default as Sidebar } from './components/Sidebar';
export { default as SkipLinkAnchor } from './components/SkipLinkAnchor';
export { default as SkipLinks } from './components/SkipLinks';
export { default as SocialShare } from './components/SocialShare';
export { default as Split } from './components/Split';
export { default as SunBurst } from './components/SunBurst';
export { default as SVGIcon } from './components/SVGIcon';
export { default as Tab } from './components/Tab';
export { default as Table } from './components/Table';
export { default as TableHeader } from './components/TableHeader';
export { default as TableRow } from './components/TableRow';
export { default as Tabs } from './components/Tabs';
export { default as TBD } from './components/TBD';
export { default as TextInput } from './components/TextInput';
export { default as Tile } from './components/Tile';
export { default as Tiles } from './components/Tiles';
export { default as Timestamp } from './components/Timestamp';
export { default as Tip } from './components/Tip';
export { default as Title } from './components/Title';
export { default as Toast } from './components/Toast';
export { default as Topology } from './components/Topology';
export { default as Value } from './components/Value';
export { default as Video } from './components/Video';
export { default as WorldMap } from './components/WorldMap';
export * from './components/icons';
export { default as Cookies }from './utils/Cookies';
export { default as DOM } from './utils/DOM';
export { default as KeyboardAccelerators } from './utils/KeyboardAccelerators';
export { default as Locale } from './utils/Locale';
export { default as Rest } from './utils/Rest';
export { default as Validator } from './utils/Validator';
<commit_msg>Fixed import of Grommet to be backwards compatible<commit_after>// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import Grommet from './index-commonjs';
import * as IconSet from './components/icons';

export const Icons = IconSet;

export { default as Accordion } from './components/Accordion';
export { default as AccordionPanel } from './components/AccordionPanel';
export { default as Anchor } from './components/Anchor';
export { default as Animate } from './components/Animate';
export { default as App } from './components/App';
export { default as Article } from './components/Article';
export { default as Box } from './components/Box';
export { default as Button } from './components/Button';
export { default as Card } from './components/Card';
export { default as Carousel } from './components/Carousel';
export * from './components/chart';
export { default as CheckBox } from './components/CheckBox';
export { default as Columns } from './components/Columns';
export { default as DateTime } from './components/DateTime';
export { default as Distribution } from './components/Distribution';
export { default as Footer } from './components/Footer';
export { default as Form } from './components/Form';
export { default as FormattedMessage } from './components/FormattedMessage';
export { default as FormField } from './components/FormField';
export { default as FormFields } from './components/FormFields';
export { default as Grommet } from './components/Grommet';
export { default as Header } from './components/Header';
export { default as Heading } from './components/Heading';
export { default as Headline } from './components/Headline';
export { default as Hero } from './components/Hero';
export { default as Image } from './components/Image';
export { default as Label } from './components/Label';
export { default as Layer } from './components/Layer';
export { default as Legend } from './components/Legend';
export { default as List } from './components/List';
export { default as ListItem } from './components/ListItem';
export { default as LoginForm } from './components/LoginForm';
export { default as Map } from './components/Map';
export { default as Markdown } from './components/Markdown';
export { default as Menu } from './components/Menu';
export { default as Meter } from './components/Meter';
export { default as Notification } from './components/Notification';
export { default as NumberInput } from './components/NumberInput';
export { default as Object } from './components/Object';
export { default as Paragraph } from './components/Paragraph';
export { default as Quote } from './components/Quote';
export { default as RadioButton } from './components/RadioButton';
export { default as Search } from './components/Search';
export { default as SearchInput } from './components/SearchInput';
export { default as Section } from './components/Section';
export { default as Select } from './components/Select';
export { default as Sidebar } from './components/Sidebar';
export { default as SkipLinkAnchor } from './components/SkipLinkAnchor';
export { default as SkipLinks } from './components/SkipLinks';
export { default as SocialShare } from './components/SocialShare';
export { default as Split } from './components/Split';
export { default as SunBurst } from './components/SunBurst';
export { default as SVGIcon } from './components/SVGIcon';
export { default as Tab } from './components/Tab';
export { default as Table } from './components/Table';
export { default as TableHeader } from './components/TableHeader';
export { default as TableRow } from './components/TableRow';
export { default as Tabs } from './components/Tabs';
export { default as TBD } from './components/TBD';
export { default as TextInput } from './components/TextInput';
export { default as Tile } from './components/Tile';
export { default as Tiles } from './components/Tiles';
export { default as Timestamp } from './components/Timestamp';
export { default as Tip } from './components/Tip';
export { default as Title } from './components/Title';
export { default as Toast } from './components/Toast';
export { default as Topology } from './components/Topology';
export { default as Value } from './components/Value';
export { default as Video } from './components/Video';
export { default as WorldMap } from './components/WorldMap';
export * from './components/icons';
export { default as Cookies }from './utils/Cookies';
export { default as DOM } from './utils/DOM';
export { default as KeyboardAccelerators } from './utils/KeyboardAccelerators';
export { default as Locale } from './utils/Locale';
export { default as Rest } from './utils/Rest';
export { default as Validator } from './utils/Validator';

export default { Grommet };
<|endoftext|>


<commit_before>Game.Screen = {};

Game.Screen.effects = {};

Game.Screen.addEffect = function(tile, pos, color, time) {
  var key = pos.x + "," + pos.y;
  Game.Screen.effects[key] = {x: pos.x, y: pos.y, tile: tile, color: color};
  setTimeout(function() {
    delete Game.Screen.effects[key];
    Game.refresh();
  }, time);
};

Game.Screen.drawTile = function(container, tileIndex, pos, color) {
  var textures = PIXI.loader.resources["assets/i/tileset.json"].textures;
  var tile = new PIXI.Sprite(textures[tileIndex]);
  tile.tint = color || 0xFFFFFF;
  tile.position.x = Math.floor(pos.x * Game.tileSize.x);
  tile.position.y = Math.floor((pos.y + 2) * Game.tileSize.y);
  container.addChild(tile);
};

Game.Screen.titleScreen = {
  enter: function() {    console.log("Entered start screen."); },
  exit: function() { console.log("Exited start screen."); },
  render: function(display) {
    // Render title screen
  },
  handleInput: function(inputType, inputData) {
    Game.switchScreen(Game.Screen.playScreen);
  }
};

Game.Screen.playScreen = {
  player: null,
  level: 1,
  gameEnded: false,
  inputLocked: false,
  inputBuffer: [],
  enter: function() {
    this.player = Object.create(Game.Entity).init(Game.Entity.templates.player);
    Game.Crates.init();
    this.newLevel(this.level);
  },
  everyTurn: function() {

  },
  exit: function() {
    console.log("Exited play screen.");
  },
  nextLevel: function() {
    this.level += 1;
    if (Game.levels[this.level]) {
      this.newLevel(this.level);
      console.log('level ' + this.level)
    } else {
      Game.switchScreen(Game.Screen.winScreen);
    }
  },
  newLevel: function(level) {
    var width = Game.mapSize.x;
    var height = Game.mapSize.y;
    this.levelOptions = Game.levels[level - 1];
    var generator = Game.Map.Generators.Basic;
    this.map = generator.create(width, height, this.levelOptions);
    this.map.screen = this;
    this.player.items.energy = 0;
    this.player.items.datachip = 0;
    generator.placeWalls(this.map);
    generator.addPlayer(this.map, this.player);
    generator.placeItems(this.map);
    generator.digPaths(this.map);
    generator.populate(this.map);
    this.grid = this.map.grid;
    this.map.engine.start();
  },
  render: function(display) {
    this.renderTiles(display);
    this.renderItems(display);
    this.renderEntities(display);
    this.renderEffects(display);
    this.renderStatus(display);
    Game.display.render(Game.stage);
  },
  renderTiles: function(display) {
    Game.display.backgroundColor = this.map.color;
    var map = this.map;
    this.map.grid.eachCell( function(cell) {
      drawCell(Game.stage, cell);
    });
    function drawCell(container, cell) {
      var x = cell.x;
      var y = cell.y;
      var pos = {x: x, y: y};
      if (cell.impassable) {
        Game.Screen.drawTile(container, "wall", pos, map.color);
      } else if (cell.dug) {
        if (cell.east  && cell.east.dug && cell.linked(cell.east))  { Game.Screen.drawTile(container, "dugeast", pos); }
        if (cell.west  && cell.west.dug && cell.linked(cell.west))  { Game.Screen.drawTile(container, "dugwest", pos); }
        if (cell.north && cell.north.dug && cell.linked(cell.north)) { Game.Screen.drawTile(container, "dugnorth", pos); }
        if (cell.south && cell.south.dug && cell.linked(cell.south)) { Game.Screen.drawTile(container, "dugsouth", pos); }
      }
    }
  },
  renderStatus: function(display) {
    var graphics = new PIXI.Graphics();
    graphics.beginFill(0x000000);
    graphics.drawRect(0, 0, Game.stage.width, Game.tileSize.y * 2);
    Game.stage.addChild(graphics);

    if (this.gameEnded) {
      var levelLabel = new PIXI.Text("LEVEL B" + (8 - this.level), {font:"20px Audiowide", fill:"#888888"});
      levelLabel.x = Game.stage.width - 10;
      levelLabel.y = 2;
      levelLabel.anchor.set(1, 0);
      Game.stage.addChild(levelLabel);

      var gameOverLabel = new PIXI.Text("GAME OVER", {font:"30px Audiowide", fill:"white"});
      gameOverLabel.x = Game.stage.width / 2;
      gameOverLabel.y = 0;
      gameOverLabel.anchor.set(0.5, 0);
      Game.stage.addChild(gameOverLabel);

      var pressKeyLabel = new PIXI.Text("Press any key to restart.", {font:"20px Audiowide", fill:"white"});
      pressKeyLabel.x = Game.stage.width / 2;
      pressKeyLabel.y = Game.tileSize.y;
      pressKeyLabel.anchor.set(0.5, 0);
      Game.stage.addChild(pressKeyLabel);

    } else {
      var levelLabel = new PIXI.Text("LEVEL B" + (8 - this.level), {font:"20px Audiowide", fill:"white"});
      levelLabel.x = Game.stage.width - 10;
      levelLabel.y = 2;
      levelLabel.anchor.set(1, 0);
      Game.stage.addChild(levelLabel);

      Game.Screen.drawTile(Game.stage, Game.Item.templates.energy.tile, {x: 0, y: -2}, Game.Item.templates.energy.color );
      Game.Screen.drawTile(Game.stage, Game.Item.templates.datachip.tile, {x: 0, y: -1}, Game.Item.templates.datachip.color );

      var energyCounter = new PIXI.Text("x " + this.player.items.energy + " / " + this.levelOptions.energyNeeded,
        {font:"20px Audiowide", fill:"white"});
      energyCounter.x = Game.tileSize.x;
      energyCounter.y = 2;
      Game.stage.addChild(energyCounter);

      var datachipCounter = new PIXI.Text("x " + this.player.items.datachip + " / " + this.levelOptions.datachipsNeeded,
        {font:"20px Audiowide", fill:"white"});
      datachipCounter.x = Game.tileSize.x;
      datachipCounter.y = Game.tileSize.y + 2;
      Game.stage.addChild(datachipCounter);
    }

  },
  renderEntities: function(display) {
    for (var key in this.map.entities) {
      var entity = this.map.entities[key];
      Game.Screen.drawTile(Game.stage, entity.getTile(), {x: entity.slidingX || entity.x, y: entity.slidingY || entity.y}, entity.getColor() );
    }
  },
  renderItems: function(display) {
    for (var key in this.map.items) {
      var item = this.map.items[key];
      Game.Screen.drawTile(Game.stage, item.tile, {x: item.x, y: item.y}, item.color );
    }
  },
  renderEffects: function(display) {
    for (var key in Game.Screen.effects) {
      var effect = Game.Screen.effects[key];
      Game.Screen.drawTile(Game.stage, effect.tile, {x: effect.x, y: effect.y}, effect.color );
    }
  },
  lockInput:  function() {
    this.inputLocked = true;
  },
  unlockInput:  function() {
    this.inputLocked = false;
    this.nextInput();
  },
  nextInput: function() {
    if (this.inputBuffer.length > 0) {
      var input = this.inputBuffer.pop();
      this.handleInput(input.type, input.data);
    };
  },
  bufferInput: function(inputType, inputData) {
    this.inputBuffer.push({type: inputType, data: inputData})
  },
  handleInput: function(inputType, inputData) {
    // If the game is over, enter will bring the user to the losing screen.
    if (this.gameEnded) {
      document.location.reload();
      return;
    }
    if (inputType === 'keydown') {
      if (this.inputLocked) {
        this.bufferInput(inputType, inputData);
      } else if (inputData.keyCode === ROT.VK_LEFT ||
        inputData.keyCode === ROT.VK_H ||
        inputData.keyCode === ROT.VK_NUMPAD4 ||
        inputData.keyCode === ROT.VK_A) {
        this.lockInput();
        this.move(-1, 0);
      } else if (inputData.keyCode === ROT.VK_RIGHT ||
                 inputData.keyCode === ROT.VK_L ||
                 inputData.keyCode === ROT.VK_NUMPAD6 ||
                 inputData.keyCode === ROT.VK_D) {
        this.lockInput();
        this.move(1, 0);
      } else if (inputData.keyCode === ROT.VK_UP ||
                 inputData.keyCode === ROT.VK_K ||
                 inputData.keyCode === ROT.VK_NUMPAD8 ||
                 inputData.keyCode === ROT.VK_W) {
        this.lockInput();
        this.move(0, -1);
      } else if (inputData.keyCode === ROT.VK_DOWN ||
                 inputData.keyCode === ROT.VK_J ||
                 inputData.keyCode === ROT.VK_NUMPAD2 ||
                 inputData.keyCode === ROT.VK_S) {
        this.lockInput();
        this.move(0, 1);
      // } else if (inputData.keyCode === ROT.VK_SPACE ||
      //            inputData.keyCode === ROT.VK_PERIOD) {
      //   this.move(0, 0);
      } else {
        // Not a valid key
        return;
      }
    }
  },
  move: function(dX, dY) {
    var newX = this.player.x + dX;
    var newY = this.player.y + dY;
    // Try to move to the new cell
    var self = this;
    this.player.tryMove(newX, newY, this.player.map)
    .then(function(didMove) {
      if (didMove) {
        //collect items
        var item = self.player.map.itemAt(newX, newY);
        if (item) {
          var itemname = item.collect();
          if (self.player.items[itemname]) {
            self.player.items[itemname] += 1;
          } else {
            self.player.items[itemname] = 1;
          }
          var doorPos;
          if (self.map.energyDoor && self.player.items.energy >= self.levelOptions.energyNeeded) {
            doorPos = {x: self.map.energyDoor.x, y: self.map.energyDoor.y};
            self.map.removeEntity(self.map.energyDoor);
            self.map.energyDoor = undefined;
            var openEnergyDoor = Object.create(Game.Entity).init(Game.Entity.templates.openEnergyDoor, doorPos.x, doorPos.y);
            self.map.addEntity(openEnergyDoor);
          }
          if (self.map.datachipDoor && self.player.items.datachip >= self.levelOptions.datachipsNeeded) {
            doorPos = {x: self.map.datachipDoor.x, y: self.map.datachipDoor.y};
            self.map.removeEntity(self.map.datachipDoor);
            self.map.datachipDoor = undefined;
            var openDatachipDoor = Object.create(Game.Entity).init(Game.Entity.templates.openDatachipDoor, doorPos.x, doorPos.y);
            self.map.addEntity(openDatachipDoor);
          }
        }
        self.player.map.engine.unlock();
      } else {
        self.unlockInput();
      }
    });
  },
};

Game.Screen.winScreen = {
  enter: function() {
    console.log("Entered win screen.");
  },
  exit: function() {
    console.log("Exited win screen.");
  },
  render: function(display) {
    Game.display.backgroundColor = 0x01579B;
    for (var x = 0; x < 13; x++) {
      Game.Screen.drawTile(Game.stage, 'wall', {x: x, y: 14}, 0xffffff );
    }
    Game.Screen.drawTile(Game.stage, 'playerbot', {x: 3, y: 13}, 0xffffff);

    var congrats = new PIXI.Text("CONGRATULATIONS!", {font:"35px Audiowide", fill:"#ffffff"});
    congrats.x = Game.stage.width / 2;
    congrats.y = 200;
    congrats.anchor.set(0.5, 0.5);
    Game.stage.addChild(congrats);

    var message = new PIXI.Text("YOU MADE IT TO THE SURFACE", {font:"16px Audiowide", fill:"#ffffff"});
    message.x = Game.stage.width / 2;
    message.y = 260;
    message.anchor.set(0.5, 0.5);
    Game.stage.addChild(message);

    Game.display.render(Game.stage);
  },
  handleInput: function(inputType, inputData) {

  }
};

Game.Screen.loseScreen = {
  enter: function() {
    console.log("Entered lose screen.");
  },
  exit: function() { console.log("Exited lose screen."); },
  render: function(display) {
    //render lose screen
  },
  handleInput: function(inputType, inputData) {

  }
};<commit_msg>Fix off-by-one bug that skips final level<commit_after>Game.Screen = {};

Game.Screen.effects = {};

Game.Screen.addEffect = function(tile, pos, color, time) {
  var key = pos.x + "," + pos.y;
  Game.Screen.effects[key] = {x: pos.x, y: pos.y, tile: tile, color: color};
  setTimeout(function() {
    delete Game.Screen.effects[key];
    Game.refresh();
  }, time);
};

Game.Screen.drawTile = function(container, tileIndex, pos, color) {
  var textures = PIXI.loader.resources["assets/i/tileset.json"].textures;
  var tile = new PIXI.Sprite(textures[tileIndex]);
  tile.tint = color || 0xFFFFFF;
  tile.position.x = Math.floor(pos.x * Game.tileSize.x);
  tile.position.y = Math.floor((pos.y + 2) * Game.tileSize.y);
  container.addChild(tile);
};

Game.Screen.titleScreen = {
  enter: function() {    console.log("Entered start screen."); },
  exit: function() { console.log("Exited start screen."); },
  render: function(display) {
    // Render title screen
  },
  handleInput: function(inputType, inputData) {
    Game.switchScreen(Game.Screen.playScreen);
  }
};

Game.Screen.playScreen = {
  player: null,
  level: 1,
  gameEnded: false,
  inputLocked: false,
  inputBuffer: [],
  enter: function() {
    this.player = Object.create(Game.Entity).init(Game.Entity.templates.player);
    Game.Crates.init();
    this.newLevel(this.level);
  },
  everyTurn: function() {

  },
  exit: function() {
    console.log("Exited play screen.");
  },
  nextLevel: function() {
    this.level += 1;
    if (Game.levels[this.level - 1]) {
      this.newLevel(this.level);
      console.log('level ' + this.level)
    } else {
      Game.switchScreen(Game.Screen.winScreen);
    }
  },
  newLevel: function(level) {
    var width = Game.mapSize.x;
    var height = Game.mapSize.y;
    this.levelOptions = Game.levels[level - 1];
    var generator = Game.Map.Generators.Basic;
    this.map = generator.create(width, height, this.levelOptions);
    this.map.screen = this;
    this.player.items.energy = 0;
    this.player.items.datachip = 0;
    generator.placeWalls(this.map);
    generator.addPlayer(this.map, this.player);
    generator.placeItems(this.map);
    generator.digPaths(this.map);
    generator.populate(this.map);
    this.grid = this.map.grid;
    this.map.engine.start();
  },
  render: function(display) {
    this.renderTiles(display);
    this.renderItems(display);
    this.renderEntities(display);
    this.renderEffects(display);
    this.renderStatus(display);
    Game.display.render(Game.stage);
  },
  renderTiles: function(display) {
    Game.display.backgroundColor = this.map.color;
    var map = this.map;
    this.map.grid.eachCell( function(cell) {
      drawCell(Game.stage, cell);
    });
    function drawCell(container, cell) {
      var x = cell.x;
      var y = cell.y;
      var pos = {x: x, y: y};
      if (cell.impassable) {
        Game.Screen.drawTile(container, "wall", pos, map.color);
      } else if (cell.dug) {
        if (cell.east  && cell.east.dug && cell.linked(cell.east))  { Game.Screen.drawTile(container, "dugeast", pos); }
        if (cell.west  && cell.west.dug && cell.linked(cell.west))  { Game.Screen.drawTile(container, "dugwest", pos); }
        if (cell.north && cell.north.dug && cell.linked(cell.north)) { Game.Screen.drawTile(container, "dugnorth", pos); }
        if (cell.south && cell.south.dug && cell.linked(cell.south)) { Game.Screen.drawTile(container, "dugsouth", pos); }
      }
    }
  },
  renderStatus: function(display) {
    var graphics = new PIXI.Graphics();
    graphics.beginFill(0x000000);
    graphics.drawRect(0, 0, Game.stage.width, Game.tileSize.y * 2);
    Game.stage.addChild(graphics);

    if (this.gameEnded) {
      var levelLabel = new PIXI.Text("LEVEL B" + (8 - this.level), {font:"20px Audiowide", fill:"#888888"});
      levelLabel.x = Game.stage.width - 10;
      levelLabel.y = 2;
      levelLabel.anchor.set(1, 0);
      Game.stage.addChild(levelLabel);

      var gameOverLabel = new PIXI.Text("GAME OVER", {font:"30px Audiowide", fill:"white"});
      gameOverLabel.x = Game.stage.width / 2;
      gameOverLabel.y = 0;
      gameOverLabel.anchor.set(0.5, 0);
      Game.stage.addChild(gameOverLabel);

      var pressKeyLabel = new PIXI.Text("Press any key to restart.", {font:"20px Audiowide", fill:"white"});
      pressKeyLabel.x = Game.stage.width / 2;
      pressKeyLabel.y = Game.tileSize.y;
      pressKeyLabel.anchor.set(0.5, 0);
      Game.stage.addChild(pressKeyLabel);

    } else {
      var levelLabel = new PIXI.Text("LEVEL B" + (8 - this.level), {font:"20px Audiowide", fill:"white"});
      levelLabel.x = Game.stage.width - 10;
      levelLabel.y = 2;
      levelLabel.anchor.set(1, 0);
      Game.stage.addChild(levelLabel);

      Game.Screen.drawTile(Game.stage, Game.Item.templates.energy.tile, {x: 0, y: -2}, Game.Item.templates.energy.color );
      Game.Screen.drawTile(Game.stage, Game.Item.templates.datachip.tile, {x: 0, y: -1}, Game.Item.templates.datachip.color );

      var energyCounter = new PIXI.Text("x " + this.player.items.energy + " / " + this.levelOptions.energyNeeded,
        {font:"20px Audiowide", fill:"white"});
      energyCounter.x = Game.tileSize.x;
      energyCounter.y = 2;
      Game.stage.addChild(energyCounter);

      var datachipCounter = new PIXI.Text("x " + this.player.items.datachip + " / " + this.levelOptions.datachipsNeeded,
        {font:"20px Audiowide", fill:"white"});
      datachipCounter.x = Game.tileSize.x;
      datachipCounter.y = Game.tileSize.y + 2;
      Game.stage.addChild(datachipCounter);
    }

  },
  renderEntities: function(display) {
    for (var key in this.map.entities) {
      var entity = this.map.entities[key];
      Game.Screen.drawTile(Game.stage, entity.getTile(), {x: entity.slidingX || entity.x, y: entity.slidingY || entity.y}, entity.getColor() );
    }
  },
  renderItems: function(display) {
    for (var key in this.map.items) {
      var item = this.map.items[key];
      Game.Screen.drawTile(Game.stage, item.tile, {x: item.x, y: item.y}, item.color );
    }
  },
  renderEffects: function(display) {
    for (var key in Game.Screen.effects) {
      var effect = Game.Screen.effects[key];
      Game.Screen.drawTile(Game.stage, effect.tile, {x: effect.x, y: effect.y}, effect.color );
    }
  },
  lockInput:  function() {
    this.inputLocked = true;
  },
  unlockInput:  function() {
    this.inputLocked = false;
    this.nextInput();
  },
  nextInput: function() {
    if (this.inputBuffer.length > 0) {
      var input = this.inputBuffer.pop();
      this.handleInput(input.type, input.data);
    };
  },
  bufferInput: function(inputType, inputData) {
    this.inputBuffer.push({type: inputType, data: inputData})
  },
  handleInput: function(inputType, inputData) {
    // If the game is over, enter will bring the user to the losing screen.
    if (this.gameEnded) {
      document.location.reload();
      return;
    }
    if (inputType === 'keydown') {
      if (this.inputLocked) {
        this.bufferInput(inputType, inputData);
      } else if (inputData.keyCode === ROT.VK_LEFT ||
        inputData.keyCode === ROT.VK_H ||
        inputData.keyCode === ROT.VK_NUMPAD4 ||
        inputData.keyCode === ROT.VK_A) {
        this.lockInput();
        this.move(-1, 0);
      } else if (inputData.keyCode === ROT.VK_RIGHT ||
                 inputData.keyCode === ROT.VK_L ||
                 inputData.keyCode === ROT.VK_NUMPAD6 ||
                 inputData.keyCode === ROT.VK_D) {
        this.lockInput();
        this.move(1, 0);
      } else if (inputData.keyCode === ROT.VK_UP ||
                 inputData.keyCode === ROT.VK_K ||
                 inputData.keyCode === ROT.VK_NUMPAD8 ||
                 inputData.keyCode === ROT.VK_W) {
        this.lockInput();
        this.move(0, -1);
      } else if (inputData.keyCode === ROT.VK_DOWN ||
                 inputData.keyCode === ROT.VK_J ||
                 inputData.keyCode === ROT.VK_NUMPAD2 ||
                 inputData.keyCode === ROT.VK_S) {
        this.lockInput();
        this.move(0, 1);
      // } else if (inputData.keyCode === ROT.VK_SPACE ||
      //            inputData.keyCode === ROT.VK_PERIOD) {
      //   this.move(0, 0);
      } else {
        // Not a valid key
        return;
      }
    }
  },
  move: function(dX, dY) {
    var newX = this.player.x + dX;
    var newY = this.player.y + dY;
    // Try to move to the new cell
    var self = this;
    this.player.tryMove(newX, newY, this.player.map)
    .then(function(didMove) {
      if (didMove) {
        //collect items
        var item = self.player.map.itemAt(newX, newY);
        if (item) {
          var itemname = item.collect();
          if (self.player.items[itemname]) {
            self.player.items[itemname] += 1;
          } else {
            self.player.items[itemname] = 1;
          }
          var doorPos;
          if (self.map.energyDoor && self.player.items.energy >= self.levelOptions.energyNeeded) {
            doorPos = {x: self.map.energyDoor.x, y: self.map.energyDoor.y};
            self.map.removeEntity(self.map.energyDoor);
            self.map.energyDoor = undefined;
            var openEnergyDoor = Object.create(Game.Entity).init(Game.Entity.templates.openEnergyDoor, doorPos.x, doorPos.y);
            self.map.addEntity(openEnergyDoor);
          }
          if (self.map.datachipDoor && self.player.items.datachip >= self.levelOptions.datachipsNeeded) {
            doorPos = {x: self.map.datachipDoor.x, y: self.map.datachipDoor.y};
            self.map.removeEntity(self.map.datachipDoor);
            self.map.datachipDoor = undefined;
            var openDatachipDoor = Object.create(Game.Entity).init(Game.Entity.templates.openDatachipDoor, doorPos.x, doorPos.y);
            self.map.addEntity(openDatachipDoor);
          }
        }
        self.player.map.engine.unlock();
      } else {
        self.unlockInput();
      }
    });
  },
};

Game.Screen.winScreen = {
  enter: function() {
    console.log("Entered win screen.");
  },
  exit: function() {
    console.log("Exited win screen.");
  },
  render: function(display) {
    Game.display.backgroundColor = 0x01579B;
    for (var x = 0; x < 13; x++) {
      Game.Screen.drawTile(Game.stage, 'wall', {x: x, y: 14}, 0xffffff );
    }
    Game.Screen.drawTile(Game.stage, 'playerbot', {x: 3, y: 13}, 0xffffff);

    var congrats = new PIXI.Text("CONGRATULATIONS!", {font:"35px Audiowide", fill:"#ffffff"});
    congrats.x = Game.stage.width / 2;
    congrats.y = 200;
    congrats.anchor.set(0.5, 0.5);
    Game.stage.addChild(congrats);

    var message = new PIXI.Text("YOU MADE IT TO THE SURFACE", {font:"16px Audiowide", fill:"#ffffff"});
    message.x = Game.stage.width / 2;
    message.y = 260;
    message.anchor.set(0.5, 0.5);
    Game.stage.addChild(message);

    Game.display.render(Game.stage);
  },
  handleInput: function(inputType, inputData) {

  }
};

Game.Screen.loseScreen = {
  enter: function() {
    console.log("Entered lose screen.");
  },
  exit: function() { console.log("Exited lose screen."); },
  render: function(display) {
    //render lose screen
  },
  handleInput: function(inputType, inputData) {

  }
};<|endoftext|>


<commit_before>var q = require('q');
var extendContext = require('./extend-context');
var prepareParams = require('./prepare-params');
var validateParams = require('./validate-params');
var authenticate = require('./authenticate');
var authorize = require('./authorize');

module.exports = {

  handler: function (api, resourceName, actionName, controller) {
    var resource = api.resources[resourceName];
    var action = resource.actions[actionName];

    // execute the resource's initialize function
    if (controller._init || controller._initialize) {
      (controller._init || controller._initialize)();
    }

    // return the event handler
    return function (event, context) {
      // add the current api, resource and action to the context for use down stream
      context.api = api;
      context.resource = resource;
      context.action = action;

      // add convenience methods to context
      extendContext(event, context);

      // extract params from the current event
      var params = prepareParams(event, context);

      // validate params
      validateParams(params, context);

      // authenticate the event using the accessToken parameter
      if (!context.committed) { authenticate(params, context); }

      // authorize the event using the scope from the token and scope required for action
      if (!context.committed) { authorize(params, context); }

      // execute the resource' _pre function if available
      if (!context.committed && controller._pre) {
        controller._pre(params, context)
          .then(function () {
            // execute the action controller implementation
            return controller[actionName](params, context);
          })
          .catch(function (err) {
            context.fail(err);
          });
      } else if (!context.committed){
        // execute the action controller implementation
        q(controller[actionName](params, context))
          .catch(function (err) {
            context.fail(err);
          });
      }
    };
  },

  ApiDefinition: require('./api-definition')

};
<commit_msg>switches to fcall wrapper<commit_after>var q = require('q');
var extendContext = require('./extend-context');
var prepareParams = require('./prepare-params');
var validateParams = require('./validate-params');
var authenticate = require('./authenticate');
var authorize = require('./authorize');

module.exports = {

  handler: function (api, resourceName, actionName, controller) {
    var resource = api.resources[resourceName];
    var action = resource.actions[actionName];

    // execute the resource's initialize function
    if (controller._init || controller._initialize) {
      (controller._init || controller._initialize)();
    }

    // return the event handler
    return function (event, context) {
      // add the current api, resource and action to the context for use down stream
      context.api = api;
      context.resource = resource;
      context.action = action;

      // add convenience methods to context
      extendContext(event, context);

      // extract params from the current event
      var params = prepareParams(event, context);

      // validate params
      validateParams(params, context);

      // authenticate the event using the accessToken parameter
      if (!context.committed) { authenticate(params, context); }

      // authorize the event using the scope from the token and scope required for action
      if (!context.committed) { authorize(params, context); }

      // execute the resource' _pre function if available
      if (!context.committed && controller._pre) {
        controller._pre(params, context)
          .then(function () {
            // execute the action controller implementation
            return controller[actionName](params, context);
          })
          .catch(function (err) {
            context.fail(err);
          });
      } else if (!context.committed){
        // execute the action controller implementation
        q.fcall(controller[actionName](params, context))
          .catch(function (err) {
            context.fail(err);
          });
      }
    };
  },

  ApiDefinition: require('./api-definition')

};
<|endoftext|>