<commit_before>/*
 * PicasaHtml.js
 * @version 2.3.4
 * @author Toshiya NISHIO(http://www.toshiya240.com)
 */
function detectEnv() {
  var ua = navigator.userAgent;
  var mobile = ua.indexOf("Mobile") != -1;
  var safari = ua.indexOf("Safari") != -1;
  var env = "";
  if (mobile && safari) {
    env = "Mobile Safari";
  } else if (mobile) {
    env = "iOS in-app";
  } else if (safari) {
    env = "Safari";
  } else {
    env = "Automator";
  }
  return env;
}

var cookie = {
    set: function(key, obj) {
        var expires = new Date(2030, 1, 1);
        document.cookie = key + "=" + escape(obj) + ";expires=" + expires.toGMTString();
    },
    get: function(key) {
        var cookies = document.cookie.split("; ");
        for (var i = 0; i < cookies.length; ++i) {
            var pair = cookies[i].split("=");
            if (pair[0] == key) {
                return unescape(pair[1]);
            }
        }
        return "";
    },
    remove: function(key) {
        var expires = new Date(1900, 1, 1);
        document.cookie = key + "='';expires=" + expires.toGMTString();
    },
    clear: function() {
        var cookies = document.cookie.split("; ");
        for (var i = 0; i < cookies.length; ++i) {
            var pair = cookies[i].split("=");
            this.remove(pair[0]);
        }
    }
};

var storage = cookie;

var load_config = function() {
    var conf_userID = storage.get("conf_userID");
    var conf_tmp = storage.get("conf_tmp2");
    var conf_fmt = storage.get("conf_fmt");

    if (conf_tmp == "") conf_tmp = "http://dl.dropbox.com/u/529339/bookmarklet/PicasaTemplate2.csv";
    if (conf_fmt == "") conf_fmt = 1;

    $("#conf_userID").val(conf_userID);
    $("#conf_tmp").val(conf_tmp);
    $("#conf_fmt").val(conf_fmt);
};

var save_config = function() {
    if ($("#conf_userID").val() == "") {
        showError("ユーザID を入力してください。");
        return false;
    }
    storage.set("conf_userID", $("#conf_userID").val());
    storage.set("conf_tmp2", $("#conf_tmp").val());
    storage.set("conf_fmt", $("#conf_fmt").val());

    return true;
};

var clear_config = function() {
    //storage.clear();
    storage.set("conf_userID", "");
    storage.set("conf_tmp2", "");
    storage.set("conf_fmt", "");
    load_config();
    showError("データベースをクリアしました。");
};

var insert_to_draftpad = function() {
    insert_to_dp($("#ta").val());
};

var myProcess = function(objectFromDraftPad) {
    var original_text = '';
    if (objectFromDraftPad && objectFromDraftPad.text ) {
        original_text = objectFromDraftPad.text;
    };
    window.insert_to_dp = function(result_html) {
        var inserting_text = original_text + "\n" + result_html;
        draftpad.replace(inserting_text, inserting_text.length, 0);
    };
};

function showError(msg) {
    $("#error_msg").text(msg);
    $("").click().remove();
}

$(function() {
    var url = window.location.href;
    var env = detectEnv();
    if (env == "iOS in-app") {
        window.location.href = "draftpad:///webdelegate?load=myProcess";
        $("#ta").hide();
    } else {
        $("#dpbutton").hide();
    }
    load_config();
    var userID = $("#conf_userID").val();
    if (userID == "") {
        $.mobile.changePage("#conf", {transition:"flip"});
    } else {
        get_albums();
    }
});

var picasa_url_base = "http://picasaweb.google.com/data/feed/api/user/"

function get_albums() {
    var userID = $("#conf_userID").val();
    var url = picasa_url_base + userID + "?kind=album&alt=json"
        $.mobile.showPageLoadingMsg();
    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "GET",
        dataType: "json",
        success: function(data) {
            var items = data.feed.entry;
            if (items.length) {
                $("#album").empty();
                $("<option>").val("").text("All Albums").appendTo("#album");
                for (var i = 0; i < items.length; i++) {
                    title = items[i].title.$t;
                    albumid = items[i].gphoto$id.$t;
                    $("<option>").val(albumid).text(title).appendTo("#album");
                }
                $("#album").selectedIndex = 0;
                $("#album").selectmenu("refresh");
            }
            $.mobile.hidePageLoadingMsg();
            if (!items.length) {
                showError("No Albums.");
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $.mobile.hidePageLoadingMsg();
            showError(textStatus + ":" + errorThrown + "(1)");
        }
    });
}

function get_photos() {
    $.mobile.showPageLoadingMsg();

    var url = $("#conf_tmp").val();
    var fmt = $("#conf_fmt").val();
    var descformat = "";
    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "GET",
        dataType: "text",
        success: function(data) {
            var lines = data.split("\n");
            var index = parseInt(fmt) + 8;
            if (lines.length <= index) {
                index = 9;
            }
            descformat = lines[index];
            if (descformat == "") {
                $.mobile.hidePageLoadingMsg();
                return;
            }
            get_photos2(descformat);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $.mobile.hidePageLoadingMsg();
            showError(textStatus + ":" + errorThrown + "(2)");
        }
    });
}

function get_photos2(descformat) {
    var selected_album = $("#album option:selected").val();
    var url = picasa_url_base + $("#conf_userID").val();
    if (selected_album != "") {
        url = url + "/albumid/" + selected_album;
    }
    var max_results = $("#max").val();
    if (max_results == "") {
        max_results = "20";
    }
    url = url + "?kind=photo&alt=json&access=public&max-results="
        + (selected_album == "" ? max_results : "999");
    var tag = $("#tag").val();
    if (tag != "") {
        url = url + "&tag=" + encodeURIComponent(tag);
    }
    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "GET",
        dataType: "json",
        success: function(data) {
            var items = data.feed.entry;
            if (items && items.length) {
                var x = "";
                if (selected_album == "") {
                    items = items.reverse();
                }
                for (var i = 0; i < items.length; i++) {
                    var title = items[i].media$group.media$title.$t;
                    var content = items[i].media$group.media$content[0];
                    var imgURL = content.url;
                    var width = content.width;
                    var height = content.height;
                    var nickname = items[i].media$group.media$credit[0].$t;
                    var description = items[i].media$group.media$description.$t;
                    var y = String(descformat);
                    y = y.replace(/\${title}/g, title);
                    y = y.replace(/\${imgURL}/g, imgURL);
                    y = y.replace(/\${width}/g, width);
                    y = y.replace(/\${height}/g, height);
                    y = y.replace(/\${nickname}/g, nickname);
                    y = y.replace(/\${description}/g, description);
                    x = x + y + "\n\n";
                }
                var first = $("#ta").val().length == 0;
                $("#ta").val(x);
                var preview = $("#preview");
                preview.html(x);
                $.each(preview.children(), function(i) {
                    var li = $("
");
                    var link = $("").attr("href", "javascript:preview_img("+i+");");
                    /*
                     * サムネイル表示時のレンダリングがうまくいかないので
                     * 自前でクラスを設定する。
                     */
                    li.addClass("ui-li-has-thumb");
                    $(this).find("img").addClass("ui-li-thumb");

                    link.append($(this));
                    li.append(link);
                    preview.append(li);
                });
                if (items && items.length && !first) {
                    preview.listview('refresh');
                }
            }
            $.mobile.hidePageLoadingMsg();
            if (!items || !items.length) {
                showError("No Photos.");
                return;
            }
            $.mobile.changePage("#result", {transition:"pop"});
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $.mobile.hidePageLoadingMsg();
            showError(textStatus + ":" + errorThrown + "(3)");
        }
    });
}

function preview_img(index) {
    $.mobile.changePage("#preview_page", {transition:"slide"});
    var img_object = $("#preview").children().eq(index).find("img").clone();
    img_object.removeClass("ui-li-thumb");
    img_object.removeAttr("height");
    img_object.width("100%");
    $("#img_preview").html(img_object);
}
<commit_msg>* オリジナルサイズを取得するよう修正 2011年末くらいからサイズを指定しない場合のデフォルトサイズが 512px になったらしい。<commit_after>/*
 * PicasaHtml.js
 * @version 2.3.5
 * @author Toshiya NISHIO(http://www.toshiya240.com)
 */
function detectEnv() {
  var ua = navigator.userAgent;
  var mobile = ua.indexOf("Mobile") != -1;
  var safari = ua.indexOf("Safari") != -1;
  var env = "";
  if (mobile && safari) {
    env = "Mobile Safari";
  } else if (mobile) {
    env = "iOS in-app";
  } else if (safari) {
    env = "Safari";
  } else {
    env = "Automator";
  }
  return env;
}

var cookie = {
    set: function(key, obj) {
        var expires = new Date(2030, 1, 1);
        document.cookie = key + "=" + escape(obj) + ";expires=" + expires.toGMTString();
    },
    get: function(key) {
        var cookies = document.cookie.split("; ");
        for (var i = 0; i < cookies.length; ++i) {
            var pair = cookies[i].split("=");
            if (pair[0] == key) {
                return unescape(pair[1]);
            }
        }
        return "";
    },
    remove: function(key) {
        var expires = new Date(1900, 1, 1);
        document.cookie = key + "='';expires=" + expires.toGMTString();
    },
    clear: function() {
        var cookies = document.cookie.split("; ");
        for (var i = 0; i < cookies.length; ++i) {
            var pair = cookies[i].split("=");
            this.remove(pair[0]);
        }
    }
};

var storage = cookie;

var load_config = function() {
    var conf_userID = storage.get("conf_userID");
    var conf_tmp = storage.get("conf_tmp2");
    var conf_fmt = storage.get("conf_fmt");

    if (conf_tmp == "") conf_tmp = "http://dl.dropbox.com/u/529339/bookmarklet/PicasaTemplate2.csv";
    if (conf_fmt == "") conf_fmt = 1;

    $("#conf_userID").val(conf_userID);
    $("#conf_tmp").val(conf_tmp);
    $("#conf_fmt").val(conf_fmt);
};

var save_config = function() {
    if ($("#conf_userID").val() == "") {
        showError("ユーザID を入力してください。");
        return false;
    }
    storage.set("conf_userID", $("#conf_userID").val());
    storage.set("conf_tmp2", $("#conf_tmp").val());
    storage.set("conf_fmt", $("#conf_fmt").val());

    return true;
};

var clear_config = function() {
    //storage.clear();
    storage.set("conf_userID", "");
    storage.set("conf_tmp2", "");
    storage.set("conf_fmt", "");
    load_config();
    showError("データベースをクリアしました。");
};

var insert_to_draftpad = function() {
    insert_to_dp($("#ta").val());
};

var myProcess = function(objectFromDraftPad) {
    var original_text = '';
    if (objectFromDraftPad && objectFromDraftPad.text ) {
        original_text = objectFromDraftPad.text;
    };
    window.insert_to_dp = function(result_html) {
        var inserting_text = original_text + "\n" + result_html;
        draftpad.replace(inserting_text, inserting_text.length, 0);
    };
};

function showError(msg) {
    $("#error_msg").text(msg);
    $("").click().remove();
}

$(function() {
    var url = window.location.href;
    var env = detectEnv();
    if (env == "iOS in-app") {
        window.location.href = "draftpad:///webdelegate?load=myProcess";
        $("#ta").hide();
    } else {
        $("#dpbutton").hide();
    }
    load_config();
    var userID = $("#conf_userID").val();
    if (userID == "") {
        $.mobile.changePage("#conf", {transition:"flip"});
    } else {
        get_albums();
    }
});

var picasa_url_base = "http://picasaweb.google.com/data/feed/api/user/"

function get_albums() {
    var userID = $("#conf_userID").val();
    var url = picasa_url_base + userID + "?kind=album&alt=json"
        $.mobile.showPageLoadingMsg();
    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "GET",
        dataType: "json",
        success: function(data) {
            var items = data.feed.entry;
            if (items.length) {
                $("#album").empty();
                $("<option>").val("").text("All Albums").appendTo("#album");
                for (var i = 0; i < items.length; i++) {
                    title = items[i].title.$t;
                    albumid = items[i].gphoto$id.$t;
                    $("<option>").val(albumid).text(title).appendTo("#album");
                }
                $("#album").selectedIndex = 0;
                $("#album").selectmenu("refresh");
            }
            $.mobile.hidePageLoadingMsg();
            if (!items.length) {
                showError("No Albums.");
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $.mobile.hidePageLoadingMsg();
            showError(textStatus + ":" + errorThrown + "(1)");
        }
    });
}

function get_photos() {
    $.mobile.showPageLoadingMsg();

    var url = $("#conf_tmp").val();
    var fmt = $("#conf_fmt").val();
    var descformat = "";
    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "GET",
        dataType: "text",
        success: function(data) {
            var lines = data.split("\n");
            var index = parseInt(fmt) + 8;
            if (lines.length <= index) {
                index = 9;
            }
            descformat = lines[index];
            if (descformat == "") {
                $.mobile.hidePageLoadingMsg();
                return;
            }
            get_photos2(descformat);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $.mobile.hidePageLoadingMsg();
            showError(textStatus + ":" + errorThrown + "(2)");
        }
    });
}

function get_photos2(descformat) {
    var selected_album = $("#album option:selected").val();
    var url = picasa_url_base + $("#conf_userID").val();
    if (selected_album != "") {
        url = url + "/albumid/" + selected_album;
    }
    var max_results = $("#max").val();
    if (max_results == "") {
        max_results = "20";
    }
    url = url + "?kind=photo&alt=json&access=public&imgmax=d&max-results="
        + (selected_album == "" ? max_results : "999");
    var tag = $("#tag").val();
    if (tag != "") {
        url = url + "&tag=" + encodeURIComponent(tag);
    }
    $.ajax({
        url: url,
        async: true,
        cache: false,
        type: "GET",
        dataType: "json",
        success: function(data) {
            var items = data.feed.entry;
            if (items && items.length) {
                var x = "";
                if (selected_album == "") {
                    items = items.reverse();
                }
                for (var i = 0; i < items.length; i++) {
                    var title = items[i].media$group.media$title.$t;
                    var content = items[i].media$group.media$content[0];
                    var imgURL = content.url;
                    var width = content.width;
                    var height = content.height;
                    var nickname = items[i].media$group.media$credit[0].$t;
                    var description = items[i].media$group.media$description.$t;
                    var y = String(descformat);
                    y = y.replace(/\${title}/g, title);
                    y = y.replace(/\${imgURL}/g, imgURL);
                    y = y.replace(/\${width}/g, width);
                    y = y.replace(/\${height}/g, height);
                    y = y.replace(/\${nickname}/g, nickname);
                    y = y.replace(/\${description}/g, description);
                    x = x + y + "\n\n";
                }
                var first = $("#ta").val().length == 0;
                $("#ta").val(x);
                var preview = $("#preview");
                preview.html(x);
                $.each(preview.children(), function(i) {
                    var li = $("
");
                    var link = $("").attr("href", "javascript:preview_img("+i+");");
                    /*
                     * サムネイル表示時のレンダリングがうまくいかないので
                     * 自前でクラスを設定する。
                     */
                    li.addClass("ui-li-has-thumb");
                    $(this).find("img").addClass("ui-li-thumb");

                    link.append($(this));
                    li.append(link);
                    preview.append(li);
                });
                if (items && items.length && !first) {
                    preview.listview('refresh');
                }
            }
            $.mobile.hidePageLoadingMsg();
            if (!items || !items.length) {
                showError("No Photos.");
                return;
            }
            $.mobile.changePage("#result", {transition:"pop"});
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $.mobile.hidePageLoadingMsg();
            showError(textStatus + ":" + errorThrown + "(3)");
        }
    });
}

function preview_img(index) {
    $.mobile.changePage("#preview_page", {transition:"slide"});
    var img_object = $("#preview").children().eq(index).find("img").clone();
    img_object.removeClass("ui-li-thumb");
    img_object.removeAttr("height");
    img_object.width("100%");
    $("#img_preview").html(img_object);
}
<|endoftext|>


<commit_before>var cdb = require('cartodb.js');
var _ = require('underscore');
var StyleLabelsPropertiesFormView = require('./style-labels-properties-form-view');
var StyleAnimatedPropertiesFormView = require('./style-animated-properties-form-view');
var StyleShapePropertiesFormView = require('./style-shape-properties-form-view');
var template = require('./style-properties-form.tpl');

module.exports = cdb.core.View.extend({

  initialize: function (opts) {
    if (!opts.layerDefinitionsCollection) throw new Error('layerDefinitionsCollection is required');
    if (!opts.querySchemaModel) throw new Error('querySchemaModel is required');
    if (!opts.styleModel) throw new Error('styleModel is required');

    this._layerDefinitionsCollection = opts.layerDefinitionsCollection;
    this._querySchemaModel = opts.querySchemaModel;
    this._styleModel = opts.styleModel;
  },

  render: function () {
    this.clearSubViews();
    var stepNumber = this._styleModel.isAggregatedType() ? 3 : 2;
    this.$el.html(
      template({
        stepNumber: stepNumber
      })
    );
    this._initViews();
    return this;
  },

  _initViews: function () {
    var currentGeometry = this._querySchemaModel.getGeometry();
    var styleType = this._styleModel.get('type');

    var shapeFormView = new StyleShapePropertiesFormView({
      styleModel: this._styleModel,
      querySchemaModel: this._querySchemaModel
    });
    this.addView(shapeFormView);
    this.$('.js-propertiesForm').append(shapeFormView.render().el);

    if (styleType !== 'heatmap') {
      var labelsFormView = new StyleLabelsPropertiesFormView({
        styleModel: this._styleModel,
        querySchemaModel: this._querySchemaModel
      });
      this.addView(labelsFormView);
      this.$('.js-propertiesForm').append(labelsFormView.render().el);
    }

    if (currentGeometry && currentGeometry.getSimpleType() === 'point') {
      var animatedFormView = new StyleAnimatedPropertiesFormView({
        layerDefinitionsCollection: this._layerDefinitionsCollection,
        styleModel: this._styleModel,
        querySchemaModel: this._querySchemaModel
      });
      this.addView(animatedFormView);
      this.$('.js-propertiesForm').append(animatedFormView.render().el);
    }
  }

});
<commit_msg>merhed<commit_after>var cdb = require('cartodb.js');
var StyleLabelsPropertiesFormView = require('./style-labels-properties-form-view');
var StyleAnimatedPropertiesFormView = require('./style-animated-properties-form-view');
var StyleShapePropertiesFormView = require('./style-shape-properties-form-view');
var template = require('./style-properties-form.tpl');

module.exports = cdb.core.View.extend({

  initialize: function (opts) {
    if (!opts.layerDefinitionsCollection) throw new Error('layerDefinitionsCollection is required');
    if (!opts.querySchemaModel) throw new Error('querySchemaModel is required');
    if (!opts.styleModel) throw new Error('styleModel is required');

    this._layerDefinitionsCollection = opts.layerDefinitionsCollection;
    this._querySchemaModel = opts.querySchemaModel;
    this._styleModel = opts.styleModel;
  },

  render: function () {
    this.clearSubViews();
    var stepNumber = this._styleModel.isAggregatedType() ? 3 : 2;
    this.$el.html(
      template({
        stepNumber: stepNumber
      })
    );
    this._initViews();
    return this;
  },

  _initViews: function () {
    var currentGeometry = this._querySchemaModel.getGeometry();
    var styleType = this._styleModel.get('type');

    var shapeFormView = new StyleShapePropertiesFormView({
      styleModel: this._styleModel,
      querySchemaModel: this._querySchemaModel
    });
    this.addView(shapeFormView);
    this.$('.js-propertiesForm').append(shapeFormView.render().el);

    if (styleType !== 'heatmap') {
      var labelsFormView = new StyleLabelsPropertiesFormView({
        styleModel: this._styleModel,
        querySchemaModel: this._querySchemaModel
      });
      this.addView(labelsFormView);
      this.$('.js-propertiesForm').append(labelsFormView.render().el);
    }

    if (currentGeometry && currentGeometry.getSimpleType() === 'point') {
      var animatedFormView = new StyleAnimatedPropertiesFormView({
        layerDefinitionsCollection: this._layerDefinitionsCollection,
        styleModel: this._styleModel,
        querySchemaModel: this._querySchemaModel
      });
      this.addView(animatedFormView);
      this.$('.js-propertiesForm').append(animatedFormView.render().el);
    }
  }

});
<|endoftext|>


<commit_before>/**
 * This <server-gardu-reporter> project created by :
 * Name         : syafiq
 * Date / Time  : 30 June 2017, 4:15 PM.
 * Email        : syafiq.rezpector@gmail.com
 * Github       : syafiqq
 */
<commit_msg>Add form submission function<commit_after>/**
 * This <server-gardu-reporter> project created by :
 * Name         : syafiq
 * Date / Time  : 30 June 2017, 4:15 PM.
 * Email        : syafiq.rezpector@gmail.com
 * Github       : syafiqq
 */

(function ($)
{
    $(function ()
    {
        NProgress.configure({
            showSpinner: false,
            template: '

'
        });

        $('form#register').on('submit', function (event)
        {
            event.preventDefault();
            let form = $(this);

            let input = form.serializeObject();

            NProgress.start();
            $.post(
                form.attr('action'),
                input,
                null,
                'json')
                .done(function (response)
                {
                    let status = ['danger', 'info', 'warning', 'success'];
                    let type = ['notify', 'validation'];
                    if (response['data'] !== undefined)
                    {
                        if (response['data']['message'] !== undefined)
                        {
                            for (let i = -1, is = type.length; ++i < is;)
                            {
                                if (response['data']['message'][type[i]] !== undefined)
                                {
                                    for (let j = -1, js = status.length; ++j < js;)
                                    {
                                        if (response['data']['message'][type[i]][status[j]] !== undefined)
                                        {
                                            if (type[i] === 'notify')
                                            {
                                                for (let k = -1, ks = response['data']['message'][type[i]][status[j]].length; ++k < ks;)
                                                {
                                                    $.notify({
                                                        message: response['data']['message'][type[i]][status[j]][k]
                                                    }, {
                                                        type: status[j]
                                                    });
                                                }
                                            }
                                            else
                                            {
                                                let template = '
'
                                                    + '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>'
                                                    + '
';
                                                for (let k = -1, ks = response['data']['message'][type[i]][status[j]].length; ++k < ks;)
                                                {
                                                    template += '
' + response['data']['message'][type[i]][status[j]][k] + '
'
                                                }
                                                template += '
'
                                                    + '
';
                                                $("div#form-message-container").empty().append(template);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        if (response['data']['redirect'] !== undefined)
                        {
                            location.href = response['data']['redirect'];
                        }
                    }
                })
                .fail(function ()
                {
                })
                .always(function ()
                {
                    NProgress.done();
                });
        });

        if ((sessionFlashdata !== undefined) && (sessionFlashdata !== null))
        {
            for (let i = -1, is = sessionFlashdata.length; ++i < is;)
            {
                $.notify({
                    message: sessionFlashdata[i]
                }, {
                    type: 'info'
                });
            }
        }
    });
    /*
     * Run right away
     * */
})(jQuery);
<|endoftext|>


<commit_before>import React from 'react';
import {mount} from 'enzyme';
import moment from 'moment';
import {toMomentFromTimestamp} from '../../helpers/toMoment';
import {withNowMoment} from '../../testing/NowContainer';
import PerDistrictContainer from '../../components/PerDistrictContainer';
import {
  createStudents,
  testSchool,
  testHighSchool
} from '../DashboardTestData';
import SchoolDisciplineDashboard from './SchoolDisciplineDashboard';

jest.mock('react-virtualized'); // doesn't work in test without a real DOM

function testContext(context = {}) {
  const nowMoment = toMomentFromTimestamp('2018-09-22T17:03:06.123Z');
  return {
    districtKey: 'somerville',
    nowFn() { return nowMoment; },
    ...context
  };
}

function testEl(moreProps = {}) {
  const props = {
    dashboardStudents: createStudents(moment.utc()),
    ...moreProps
  };
  return <SchoolDisciplineDashboard {...props} />;
}

// mount doesn't support passing context directly, and shallow doesn't
// work with wrapper components, that's why there's extra setup to translate
// between
function elWrappedInContext(el, context) {
  const {districtKey, nowFn} = context;
  return withNowMoment(nowFn(), (
    <PerDistrictContainer districtKey={districtKey}>{el}</PerDistrictContainer>
  ));
}

it('displays house for SHS', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testHighSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectHouse').length > 0).toEqual(true);
});

it('does not display house for Healy', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectHouse').length > 0).toEqual(false);
});

it('displays counselor for SHS', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testHighSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectCounselor').length > 0).toEqual(true);
});

it('does not display counselor for Healy', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectCounselor').length > 0).toEqual(false);
});

it('displays grade for SHS', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testHighSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectGrade').length > 0).toEqual(true);
});

it('displays grade for Healy', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectGrade').length > 0).toEqual(true);
});

it('renders at least one bar chart', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('DashboardBarChart').length > 0).toEqual(true);
});

it('renders a student list', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('StudentsTable').length > 0).toEqual(true);
});

it('renders a date range selector', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectTimeRange').length > 0).toEqual(true);
});
<commit_msg>spellcheck<commit_after>import React from 'react';
import {mount} from 'enzyme';
import moment from 'moment';
import {toMomentFromTimestamp} from '../../helpers/toMoment';
import {withNowMoment} from '../../testing/NowContainer';
import PerDistrictContainer from '../../components/PerDistrictContainer';
import {
  createStudents,
  testSchool,
  testHighSchool
} from '../DashboardTestData';
import SchoolDisciplineDashboard from './SchoolDisciplineDashboard';

jest.mock('react-virtualized'); // doesn't work in test without a real DOM

function testContext(context = {}) {
  const nowMoment = toMomentFromTimestamp('2018-09-22T17:03:06.123Z');
  return {
    districtKey: 'somerville',
    nowFn() { return nowMoment; },
    ...context
  };
}

function testEl(moreProps = {}) {
  const props = {
    dashboardStudents: createStudents(moment.utc()),
    ...moreProps
  };
  return <SchoolDisciplineDashboard {...props} />;
}

// mount doesn't support passing context directly, and shallow doesn't
// work with wrapper components, that's why there's extra setup to translate
// between
function elWrappedInContext(el, context) {
  const {districtKey, nowFn} = context;
  return withNowMoment(nowFn(), (
    <PerDistrictContainer districtKey={districtKey}>{el}</PerDistrictContainer>
  ));
}

it('displays house for SHS', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testHighSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectHouse').length > 0).toEqual(true);
});

it('does not display house for Healey', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectHouse').length > 0).toEqual(false);
});

it('displays counselor for SHS', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testHighSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectCounselor').length > 0).toEqual(true);
});

it('does not display counselor for Healey', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectCounselor').length > 0).toEqual(false);
});

it('displays grade for SHS', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testHighSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectGrade').length > 0).toEqual(true);
});

it('displays grade for Healey', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectGrade').length > 0).toEqual(true);
});

it('renders at least one bar chart', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('DashboardBarChart').length > 0).toEqual(true);
});

it('renders a student list', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('StudentsTable').length > 0).toEqual(true);
});

it('renders a date range selector', () => {
  const context = testContext({districtKey: 'somerville'});
  const props = {school: testSchool};
  const el = testEl(props);
  const dash = mount(elWrappedInContext(el, context));
  expect(dash.find('SelectTimeRange').length > 0).toEqual(true);
});
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
// dojo.provide allows pages use all types declared in this resource
dojo.provide("demo.LayoutManager");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ComboBox");
dojo.require("dojo.data.ItemFileWriteStore");

//LayoutManager
// looks after the loading & saving of arrangements of bundles on the surface.
// stores configurations by name, by provider.
//
// listens for provider change notifications to know what the current provider is,
// when a provider is selected, all current layouts are discarded, and the layout
// set for the new provider is setup.
//
// the list of layouts for a provider is stored in a cookie as
//    "ozzy.demo.ui.layouts.<providerName>"
// the layout data for each layout is stored in a cookie as
//    "ozzy.demo.ui.coords.<providerName>.<layoutName>"
//
// both are stored as a json encoded array.
//
// if a provider is selected that we havent seen before, a new cookie is created
// with a layout entry of 'default'.
//
// coord save load is now based over bundle name & version, not id.
// load will only move bundles it is able to match,
// if a provider gives back different bundles to the ones saved with coords, the
// mismatches are ignored.
//
// TODO:
//   - delete Layout.
//   - (possible) remove load button & trigger off of selection of dropdown.
//   - writeProtect 'default' so it is always the one seen 1st time.
//   - activate loadCoords after provider change.
//   - store 'active' layout to reload on switching to provider
//   - allow dynamic contributions to layout from layout plugins
//     these would add fixed entries to the layout dropdown, and would
//     arrange the layout according to logic rather than a saved layout.
//     these could live server side, or client side, and be added via ajax.
dojo.declare("demo.LayoutManager", [], {
	loadButton:null,
	saveButton:null,
	switchButton:null,
	layoutSelector:null,
	disabled:true,
	items:[],
	layouts:null,

	constructor : function(where) {
	  var _this=this;
	  this.loadButton = new dijit.form.Button(
			  {label: "Load Coords", onClick: function(){_this.loadCoords();} });
	  this.saveButton = new dijit.form.Button(
			  {label: "Save Coords", onClick: function(){_this.saveCoords();} });

	  this.switchButton = new dijit.form.Button(
			  {label: "Show/Hide", onClick: function(){_this.switchVisibility();} });

      this.layouts = new dojo.data.ItemFileWriteStore( {data : {identifier: 'name', items: this.items }});

	  this.layoutSelector = new dijit.form.ComboBox( {id: "BundleLayoutSelector",  store: this.layouts} );

	  this.layoutSelector.attr('value',"default");

	  dojo.byId(where).appendChild(this.layoutSelector.domNode);
	  dojo.byId(where).appendChild(this.loadButton.domNode);
	  dojo.byId(where).appendChild(this.saveButton.domNode);
	  dojo.byId(where).appendChild(this.switchButton.domNode);

	  this.disable();

	  dojo.subscribe("demo.provider.change", this, this.onProviderChange);
	},
	switchVisibility: function() {
		console.log("Switching visibility");
		dojo.forEach(bundles, function(bundle){
			if(bundle!=null){
				bundle.toggleHidden();
			}
	    });
	},
	onProviderChange: function(evt){
		  console.log("OnProviderChange");
		  console.log(evt);
		  this.enable();

		  this.removeAllLayoutsFromMenu();

		  console.log("Adding default if missing");
		  this.addDefaultLayoutIfMissing(providerSelector.getProvider());
		  this.getLayoutsForProvider(providerSelector.getProvider());

		  this.layoutSelector.attr('value',"default");
	},
	removeAllLayoutsFromMenu: function(){
		  this.layoutSelector.attr('value',"");
		  var _this=this;
			function deleteItems(items, request){
				console.log("total removal query");
				console.log(items);
				console.log(request);
				dojo.forEach(items, function(item){
					console.log("deleting "+item.name);
					_this.layouts.deleteItem(item);
				});
			    console.log("end process");
			}
			this.layouts.fetch({query:{}, onComplete: deleteItems});
			this.layouts.save();

			this.items=[];
			this.layouts.close();
	},
	enable: function(){
		this.loadButton.attr('disabled',false);
		this.saveButton.attr('disabled',false);
		this.layoutSelector.attr('disabled',false);
	},
	disable: function(){
		this.loadButton.attr('disabled',true);
		this.saveButton.attr('disabled',true);
		this.layoutSelector.attr('disabled',true);
	},
	addDefaultLayoutIfMissing: function(provider){
		  var bundle_layouts_str = dojo.cookie("ozzy.demo.ui.layouts."+provider);
		  if(bundle_layouts_str==null){
			    console.log("No cookie found listing layouts.. adding default & creating one.");
				this.layouts.newItem({name: "default"});
				this.layouts.save();
				this.saveLayoutsToCookie();
				this.layoutSelector.attr('value',"default");
				this.saveCoords();
				this.removeAllLayoutsFromMenu();
		  }
	},
	saveLayoutsToCookie: function(){
		var name = "ozzy.demo.ui.layouts."+providerSelector.getProvider();
		console.log("Saving layouts to "+name);
		var names = new Array();

		var _this=this;
		function process(items, request){
			console.log("total namegather query");
			console.log(items);
			console.log(request);
			dojo.forEach(items, function(item){
				var name = _this.layouts.getValue(item, 'name');
				console.log("name "+name);
				names.push(name);
			});
		    console.log("end process");
		}
		this.layouts.fetch({query:{}, onComplete: process});

		//dojo.forEach(this.items, function(item){ console.log(item); console.log(item.name[0]); names.push(item.name[0])});
		console.log("Names to save..")
		console.log(names);
		dojo.cookie(name, dojo.toJson(names));
		console.log("Saved");
	},
	getLayoutsForProvider: function(provider){
	  var bundle_layouts_str = dojo.cookie("ozzy.demo.ui.layouts."+provider);
	  if(bundle_layouts_str!=null){
		  var names = dojo.fromJson(bundle_layouts_str);
		  console.log("Loaded for provider"+provider);
		  console.log(bundle_layouts_str);
		  console.log(names);
		  var _this=this;
		  dojo.forEach(names, function(name){
			  _this.layouts.newItem({name: name});
		  });
		  this.layouts.save();
		  this.layoutSelector.attr('value',"default");
	  }else{
		  //do-nothng.
	  }

	},
	saveCoords: function() {
		console.log("Save coords");
		var bundle_coords = new Array();
		var idx=0;
		var coords_cookie="";

		var coord_data = new Array();

		dojo.forEach(bundles, function(bundle){
			if(bundle!=null){
				var x=bundle.x;
				var y=bundle.y;
				var h=bundle.hidden ? 1 : 0;

				coord_data.push( {name:bundle.name, ver:bundle.version, x: x, y: y, h: h});
			}
		});
		var coords_json = dojo.toJson(coord_data);

		dojo.cookie("ozzy.demo.ui.coords."+providerSelector.getProvider()+"."+this.layoutSelector.attr('value'), coords_json);

		var match=false;
		var name = this.layoutSelector.attr('value');
		console.log("checking layouts for "+name);
	    this.layouts.fetch({query: { name: name }, onComplete: function(item){
	    	if(item!=null && item.length>0){
	    		console.log("Found it");
	    		console.log(item);
	    		match=true;
	    	}
	    }});
	    console.log("adding if needed");
	    if(!match){
	    	console.log("adding "+name);
			this.layouts.newItem({name: name});
			this.layouts.save();
			console.log("pushing to cookie");
			this.saveLayoutsToCookie();
	    }

		//dwr.util.setValue("coords_status", "Done");
	},
	loadCoords: function() {
		console.log("Load coords");
		var bundle_coords_str = dojo.cookie("ozzy.demo.ui.coords."+providerSelector.getProvider()+"."+this.layoutSelector.attr('value'));
		if(bundle_coords_str != null){
			var bundle_coord_data = dojo.fromJson(bundle_coords_str);
			dojo.forEach(bundle_coord_data, function(bi){
				var id=-1;
				dojo.forEach(bundles, function(b){
						if(b!=null){
							console.log(b);
							console.log("Inside foreach");
							if((b.name==bi.name) && (b.version==bi.ver)){
								id=b.id;
							}
						}
					});

				console.log("id "+id)

				//we may not know the bundle yet.. just ignore it for now.
				if(bundles[id]!=null){
					bundles[id].x = bi.x;
					bundles[id].y = bi.y;
					moveBundle(bundles[id], bi.x, bi.y);

					var h2=bundles[id].hidden ? 1 : 0;
					//	console.log("Bundle "+id+" had hidden flag of "+h+" ("+h2+") and current state of "+bundles[id].hidden);
					if( bi.h!=h2 ){
						//console.log("Flipping hidden state on bundle..");
						bundles[id].toggleHidden();
					}
				}
			});

			//dwr.util.setValue("coords_status", "Done");
		}else{
			//dwr.util.setValue("coords_status", "No cookie found");
		}
	}
});
<commit_msg>ARIES-314 Make showAll and hideAll separate buttons<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
// dojo.provide allows pages use all types declared in this resource
dojo.provide("demo.LayoutManager");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.ComboBox");
dojo.require("dojo.data.ItemFileWriteStore");

//LayoutManager
// looks after the loading & saving of arrangements of bundles on the surface.
// stores configurations by name, by provider.
//
// listens for provider change notifications to know what the current provider is,
// when a provider is selected, all current layouts are discarded, and the layout
// set for the new provider is setup.
//
// the list of layouts for a provider is stored in a cookie as
//    "ozzy.demo.ui.layouts.<providerName>"
// the layout data for each layout is stored in a cookie as
//    "ozzy.demo.ui.coords.<providerName>.<layoutName>"
//
// both are stored as a json encoded array.
//
// if a provider is selected that we havent seen before, a new cookie is created
// with a layout entry of 'default'.
//
// coord save load is now based over bundle name & version, not id.
// load will only move bundles it is able to match,
// if a provider gives back different bundles to the ones saved with coords, the
// mismatches are ignored.
//
// TODO:
//   - delete Layout.
//   - (possible) remove load button & trigger off of selection of dropdown.
//   - writeProtect 'default' so it is always the one seen 1st time.
//   - activate loadCoords after provider change.
//   - store 'active' layout to reload on switching to provider
//   - allow dynamic contributions to layout from layout plugins
//     these would add fixed entries to the layout dropdown, and would
//     arrange the layout according to logic rather than a saved layout.
//     these could live server side, or client side, and be added via ajax.
dojo.declare("demo.LayoutManager", [], {
	loadButton:null,
	saveButton:null,
	switchButton:null,
	layoutSelector:null,
	disabled:true,
	items:[],
	layouts:null,

	constructor : function(where) {
	  var _this=this;
	  this.loadButton = new dijit.form.Button(
			  {label: "Load Coords", onClick: function(){_this.loadCoords();} });
	  this.saveButton = new dijit.form.Button(
			  {label: "Save Coords", onClick: function(){_this.saveCoords();} });

	  this.hideButton = new dijit.form.Button(
			  {label: "Hide All", onClick: function(){_this.hideAll();} });

	  this.showButton = new dijit.form.Button(
			  {label: "Show All", onClick: function(){_this.showAll();} });

      this.layouts = new dojo.data.ItemFileWriteStore( {data : {identifier: 'name', items: this.items }});

	  this.layoutSelector = new dijit.form.ComboBox( {id: "BundleLayoutSelector",  store: this.layouts} );

	  this.layoutSelector.attr('value',"default");

	  dojo.byId(where).appendChild(this.layoutSelector.domNode);
	  dojo.byId(where).appendChild(this.loadButton.domNode);
	  dojo.byId(where).appendChild(this.saveButton.domNode);
	  dojo.byId(where).appendChild(this.hideButton.domNode);
	  dojo.byId(where).appendChild(this.showButton.domNode);

	  this.disable();

	  dojo.subscribe("demo.provider.change", this, this.onProviderChange);
	},

	hideAll: function() {
		console.log("Hiding all bundles");
		dojo.forEach(bundles, function(bundle){
			if(bundle!=null){
				//If it isn't hidden already
				if(!bundle.hidden) {
					bundle.toggleHidden();
				}
			}
	    });
	},

	showAll: function() {
		console.log("Showing all bundles");
		dojo.forEach(bundles, function(bundle){
			if(bundle!=null){
				//If bundle is hidden make it visible
				if(bundle.hidden) {
					bundle.toggleHidden();
				}
			}
	    });
	},
	onProviderChange: function(evt){
		  console.log("OnProviderChange");
		  console.log(evt);
		  this.enable();

		  this.removeAllLayoutsFromMenu();

		  console.log("Adding default if missing");
		  this.addDefaultLayoutIfMissing(providerSelector.getProvider());
		  this.getLayoutsForProvider(providerSelector.getProvider());

		  this.layoutSelector.attr('value',"default");
	},
	removeAllLayoutsFromMenu: function(){
		  this.layoutSelector.attr('value',"");
		  var _this=this;
			function deleteItems(items, request){
				console.log("total removal query");
				console.log(items);
				console.log(request);
				dojo.forEach(items, function(item){
					console.log("deleting "+item.name);
					_this.layouts.deleteItem(item);
				});
			    console.log("end process");
			}
			this.layouts.fetch({query:{}, onComplete: deleteItems});
			this.layouts.save();

			this.items=[];
			this.layouts.close();
	},
	enable: function(){
		this.loadButton.attr('disabled',false);
		this.saveButton.attr('disabled',false);
		this.layoutSelector.attr('disabled',false);
	},
	disable: function(){
		this.loadButton.attr('disabled',true);
		this.saveButton.attr('disabled',true);
		this.layoutSelector.attr('disabled',true);
	},
	addDefaultLayoutIfMissing: function(provider){
		  var bundle_layouts_str = dojo.cookie("ozzy.demo.ui.layouts."+provider);
		  if(bundle_layouts_str==null){
			    console.log("No cookie found listing layouts.. adding default & creating one.");
				this.layouts.newItem({name: "default"});
				this.layouts.save();
				this.saveLayoutsToCookie();
				this.layoutSelector.attr('value',"default");
				this.saveCoords();
				this.removeAllLayoutsFromMenu();
		  }
	},
	saveLayoutsToCookie: function(){
		var name = "ozzy.demo.ui.layouts."+providerSelector.getProvider();
		console.log("Saving layouts to "+name);
		var names = new Array();

		var _this=this;
		function process(items, request){
			console.log("total namegather query");
			console.log(items);
			console.log(request);
			dojo.forEach(items, function(item){
				var name = _this.layouts.getValue(item, 'name');
				console.log("name "+name);
				names.push(name);
			});
		    console.log("end process");
		}
		this.layouts.fetch({query:{}, onComplete: process});

		//dojo.forEach(this.items, function(item){ console.log(item); console.log(item.name[0]); names.push(item.name[0])});
		console.log("Names to save..")
		console.log(names);
		dojo.cookie(name, dojo.toJson(names));
		console.log("Saved");
	},
	getLayoutsForProvider: function(provider){
	  var bundle_layouts_str = dojo.cookie("ozzy.demo.ui.layouts."+provider);
	  if(bundle_layouts_str!=null){
		  var names = dojo.fromJson(bundle_layouts_str);
		  console.log("Loaded for provider"+provider);
		  console.log(bundle_layouts_str);
		  console.log(names);
		  var _this=this;
		  dojo.forEach(names, function(name){
			  _this.layouts.newItem({name: name});
		  });
		  this.layouts.save();
		  this.layoutSelector.attr('value',"default");
	  }else{
		  //do-nothng.
	  }

	},
	saveCoords: function() {
		console.log("Save coords");
		var bundle_coords = new Array();
		var idx=0;
		var coords_cookie="";

		var coord_data = new Array();

		dojo.forEach(bundles, function(bundle){
			if(bundle!=null){
				var x=bundle.x;
				var y=bundle.y;
				var h=bundle.hidden ? 1 : 0;

				coord_data.push( {name:bundle.name, ver:bundle.version, x: x, y: y, h: h});
			}
		});
		var coords_json = dojo.toJson(coord_data);

		dojo.cookie("ozzy.demo.ui.coords."+providerSelector.getProvider()+"."+this.layoutSelector.attr('value'), coords_json);

		var match=false;
		var name = this.layoutSelector.attr('value');
		console.log("checking layouts for "+name);
	    this.layouts.fetch({query: { name: name }, onComplete: function(item){
	    	if(item!=null && item.length>0){
	    		console.log("Found it");
	    		console.log(item);
	    		match=true;
	    	}
	    }});
	    console.log("adding if needed");
	    if(!match){
	    	console.log("adding "+name);
			this.layouts.newItem({name: name});
			this.layouts.save();
			console.log("pushing to cookie");
			this.saveLayoutsToCookie();
	    }

		//dwr.util.setValue("coords_status", "Done");
	},
	loadCoords: function() {
		console.log("Load coords");
		var bundle_coords_str = dojo.cookie("ozzy.demo.ui.coords."+providerSelector.getProvider()+"."+this.layoutSelector.attr('value'));
		if(bundle_coords_str != null){
			var bundle_coord_data = dojo.fromJson(bundle_coords_str);
			dojo.forEach(bundle_coord_data, function(bi){
				var id=-1;
				dojo.forEach(bundles, function(b){
						if(b!=null){
							console.log(b);
							console.log("Inside foreach");
							if((b.name==bi.name) && (b.version==bi.ver)){
								id=b.id;
							}
						}
					});

				console.log("id "+id)

				//we may not know the bundle yet.. just ignore it for now.
				if(bundles[id]!=null){
					bundles[id].x = bi.x;
					bundles[id].y = bi.y;
					moveBundle(bundles[id], bi.x, bi.y);

					var h2=bundles[id].hidden ? 1 : 0;
					//	console.log("Bundle "+id+" had hidden flag of "+h+" ("+h2+") and current state of "+bundles[id].hidden);
					if( bi.h!=h2 ){
						//console.log("Flipping hidden state on bundle..");
						bundles[id].toggleHidden();
					}
				}
			});

			//dwr.util.setValue("coords_status", "Done");
		}else{
			//dwr.util.setValue("coords_status", "No cookie found");
		}
	}
});
<|endoftext|>


<commit_before>/* **************************************************************

   Copyright 2013 Zoovy, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

************************************************************** */

//    !!! ->   TODO: replace 'username' in the line below with the merchants username.     <- !!!

var pogs_cubworld = function() {
	var r = {
////////////////////////////////////   CALLBACKS    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

		callbacks : {
	//executed when extension is loaded. should include any validation that needs to occur.
			init : {
				onSuccess : function()	{
					var r = false; //return false if extension won't load for some reason (account config, dependencies, etc).
					//if there is any functionality required for this extension to load, put it here. such as a check for async google, the FB object, etc. return false if dependencies are not present. don't check for other extensions.
					r = true;

					return r;
					},
				onError : function()	{
	//errors will get reported for this callback as part of the extensions loading.  This is here for extra error handling purposes.
	//you may or may not need it.
					app.u.dump('BEGIN app.ext.cubworld.callbacks.init.onError');
					}
				},

			startExtension : {
				onSuccess : function() {
					//app.u.dump(typeof jQuery.fn.cycle);
					if(app.ext.myRIA && app.ext.myRIA.template && handlePogs){
						app.u.dump("Extending Pogs");

						app.ext.myRIA.template.productTemplate.onCompletes.push(function(P) {
							app.ext.pogs_cubworld.vars.prodContext = $(app.u.jqSelector('#',P.parentID));
							});
						if($("#appView .productPage").length > 0){
							app.ext.pogs_cubworld.vars.prodContext = $("#appView .productPage:visible");
							}
						$.extend(handlePogs.prototype,app.ext.pogs_cubworld.variations);
						UpdateMLBIcons = app.ext.pogs_cubworld.a.updateMLBIcons;
						}
					else {
						app.u.dump("Retrying Pog Extension");
						setTimeout(function(){app.ext.cubworld.callbacks.startExtension.onSuccess()},250);
						}
					},
				onError : function() {
					app.u.dump('BEGIN app.ext.cubworld.callbacks.startExtension.onError');
					}
				}
			}, //callbacks

		variations : {
			renderOptionLABELDADDYLIST : function(pog){
				app.u.dump(pog);
				var $option = $('

')
				var $input = $('<input type="hidden" name="'+pog.id+'"/>');
				var $teamlist = $("

");
				var $optionlist= $("

");
				$option.append($input);
				$option.append($teamlist);
				$option.append($optionlist);

				$teamlist.append($('
Baltimore Orioles
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('orioles',$optionlist);}))
						.append($('
Boston Red Sox
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('redsox',$optionlist);}))
						.append($('
Chicago White Sox
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('whitesox',$optionlist);}))
						.append($('
Cleveland Indians
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('indians',$optionlist);}))
						.append($('
Detroit Tigers
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('tigers',$optionlist);}))
						.append($('
Kansas City Royals
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('royals',$optionlist);}))
						.append($('
LA Angels of Anaheim
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('LAA',$optionlist);}))
						.append($('
Minnesota Twins
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('twins',$optionlist);}))
						.append($('
New York Yankees
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('yankees',$optionlist);}))
						.append($('
Oakland Athletics
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('athletics',$optionlist);}))
						.append($('
Seattle Mariners
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('mariners',$optionlist);}))
						.append($('
Tampa Bay Rays
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('bayrays',$optionlist);}))
						.append($('
Toronto Blue Jays
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('bluejays',$optionlist);}))
						.append($('
Texas Rangers
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('rangers',$optionlist);}))
						.append($('
Arizona Diamondbacks
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('arizona',$optionlist);}))
						.append($('
Atlanta Braves
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('braves',$optionlist);}))
						.append($('
Chicago Cubs
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('cubs',$optionlist);}))
						.append($('
Cincinnati Reds
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('reds',$optionlist);}))
						.append($('
Colorado Rockies
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('rockies',$optionlist);}))
						.append($('
Houston Astros
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('houston',$optionlist);}))
						.append($('
Los Angeles Dodgers
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('dodgers',$optionlist);}))
						.append($('
Miami Marlins
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('marlins',$optionlist);}))
						.append($('
Milwaukee Brewers
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('brewers',$optionlist);}))
						.append($('
New York Mets
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('mets',$optionlist);}))
						.append($('
Philadelphia Phillies
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('phillies',$optionlist);}))
						.append($('
Pittsburgh Pirates
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('pirates',$optionlist);}))
						.append($('
St. Louis Cardinals
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('cardinals',$optionlist);}))
						.append($('
San Diego Padres
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('padres',$optionlist);}))
						.append($('
San Francisco Giants
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('giants',$optionlist);}))
						.append($('
Washington Nationals
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('nationals',$optionlist);}));

				$option.append('

')
				return $option;
				},
			renderOptionCUSTOMIZERNOTICE : function(pog){
				$option = $("<input type='hidden' name='AK'/>");

				$atcForm = $('.prodViewerAddToCartForm', (app.ext.pogs_cubworld.vars.prodContext ? app.ext.pogs_cubworld.vars.prodContext : $('#mainContentArea')))
				$atcForm.unbind('submit').attr('onSubmit','');
				$atcForm.bind('submit', function(){
					var $notice = $('
'+pog.prompt+'
');

					var $button = $('<button>I agree</button>');
					$button.bind('click',function(){
						$notice.dialog('close');
						$option.val("ON");
						app.ext.myRIA.u.addItemToCart($atcForm,{'action':'modal'});
						return false;
						});

					$notice.append($button);

					$notice.dialog({'modal':'true','title':'Custom Product Agreement'});
					return false;
				});

				return $option
				},
			xinit : function(){
				this.addHandler("pogid","CH","renderOptionLABELDADDYLIST");
				this.addHandler("pogid","AK","renderOptionCUSTOMIZERNOTICE");
				}
			},

////////////////////////////////////   ACTION    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//actions are functions triggered by a user interaction, such as a click/tap.
//these are going the way of the do do, in favor of app events. new extensions should have few (if any) actions.
		a : {
			openIconDetails : function(team, $target){
				var queryString = "?iconname=" + team ;
				var jsonp_url = "http://www.labeldaddy.com/widget/getIcons.php" + queryString + "&jsoncallback=?";
				$.getJSON(jsonp_url, function(data) {
					$target.empty().append($(data.html));
					});
				return false;
				},
			updateMLBIcons : function(iconset){
				$('input[name=CH]', app.ext.pogs_cubworld.vars.prodContext).val(iconset);
				app.ext.pogs_cubworld.u.showLabelPreview();
				}
			}, //Actions

////////////////////////////////////   RENDERFORMATS    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//renderFormats are what is used to actually output data.
//on a data-bind, format: is equal to a renderformat. extension: tells the rendering engine where to look for the renderFormat.
//that way, two render formats named the same (but in different extensions) don't overwrite each other.
		renderFormats : {
			}, //renderFormats
////////////////////////////////////   UTIL [u]   \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//utilities are typically functions that are exected by an event or action.
//any functions that are recycled should be here.
		u : {
			showLabelPreview : function(){

				var labelName = $('input[name=CJ]', app.ext.pogs_cubworld.vars.prodContext).val();
				var labelLastName = $('input[name=CK]', app.ext.pogs_cubworld.vars.prodContext).val();
				var labelIcon = $('input[name=CH]', app.ext.pogs_cubworld.vars.prodContext).val();

				var queryString = "?labelName=" + labelName + "&labellastName=" + labelLastName + "&labelicon=" + labelIcon ;
				var jsonp_url = "http://www.labeldaddy.com/widget/MLBPackWidget.php" + queryString + "&jsoncallback=?";
				$.getJSON(jsonp_url, function(data) {
					$('.labelPreview', app.ext.pogs_cubworld.vars.prodContext).html(data.html);
					});
				}
			}, //u [utilities]

//app-events are added to an element through data-app-event="extensionName|functionName"
//right now, these are not fully supported, but they will be going forward.
//they're used heavily in the admin.html file.
//while no naming convention is stricly forced,
//when adding an event, be sure to do off('click.appEventName') and then on('click.appEventName') to ensure the same event is not double-added if app events were to get run again over the same template.
		e : {
			}, //e [app Events]
		vars : {
			prodContext : undefined
			}
		} //r object.

	return r;
	}<commit_msg>Customizer notice styling<commit_after>/* **************************************************************

   Copyright 2013 Zoovy, Inc.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

************************************************************** */

//    !!! ->   TODO: replace 'username' in the line below with the merchants username.     <- !!!

var pogs_cubworld = function() {
	var r = {
////////////////////////////////////   CALLBACKS    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

		callbacks : {
	//executed when extension is loaded. should include any validation that needs to occur.
			init : {
				onSuccess : function()	{
					var r = false; //return false if extension won't load for some reason (account config, dependencies, etc).
					//if there is any functionality required for this extension to load, put it here. such as a check for async google, the FB object, etc. return false if dependencies are not present. don't check for other extensions.
					r = true;

					return r;
					},
				onError : function()	{
	//errors will get reported for this callback as part of the extensions loading.  This is here for extra error handling purposes.
	//you may or may not need it.
					app.u.dump('BEGIN app.ext.cubworld.callbacks.init.onError');
					}
				},

			startExtension : {
				onSuccess : function() {
					//app.u.dump(typeof jQuery.fn.cycle);
					if(app.ext.myRIA && app.ext.myRIA.template && handlePogs){
						app.u.dump("Extending Pogs");

						app.ext.myRIA.template.productTemplate.onCompletes.push(function(P) {
							app.ext.pogs_cubworld.vars.prodContext = $(app.u.jqSelector('#',P.parentID));
							});
						if($("#appView .productPage").length > 0){
							app.ext.pogs_cubworld.vars.prodContext = $("#appView .productPage:visible");
							}
						$.extend(handlePogs.prototype,app.ext.pogs_cubworld.variations);
						UpdateMLBIcons = app.ext.pogs_cubworld.a.updateMLBIcons;
						}
					else {
						app.u.dump("Retrying Pog Extension");
						setTimeout(function(){app.ext.cubworld.callbacks.startExtension.onSuccess()},250);
						}
					},
				onError : function() {
					app.u.dump('BEGIN app.ext.cubworld.callbacks.startExtension.onError');
					}
				}
			}, //callbacks

		variations : {
			renderOptionLABELDADDYLIST : function(pog){
				app.u.dump(pog);
				var $option = $('

')
				var $input = $('<input type="hidden" name="'+pog.id+'"/>');
				var $teamlist = $("

");
				var $optionlist= $("

");
				$option.append($input);
				$option.append($teamlist);
				$option.append($optionlist);

				$teamlist.append($('
Baltimore Orioles
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('orioles',$optionlist);}))
						.append($('
Boston Red Sox
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('redsox',$optionlist);}))
						.append($('
Chicago White Sox
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('whitesox',$optionlist);}))
						.append($('
Cleveland Indians
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('indians',$optionlist);}))
						.append($('
Detroit Tigers
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('tigers',$optionlist);}))
						.append($('
Kansas City Royals
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('royals',$optionlist);}))
						.append($('
LA Angels of Anaheim
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('LAA',$optionlist);}))
						.append($('
Minnesota Twins
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('twins',$optionlist);}))
						.append($('
New York Yankees
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('yankees',$optionlist);}))
						.append($('
Oakland Athletics
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('athletics',$optionlist);}))
						.append($('
Seattle Mariners
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('mariners',$optionlist);}))
						.append($('
Tampa Bay Rays
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('bayrays',$optionlist);}))
						.append($('
Toronto Blue Jays
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('bluejays',$optionlist);}))
						.append($('
Texas Rangers
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('rangers',$optionlist);}))
						.append($('
Arizona Diamondbacks
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('arizona',$optionlist);}))
						.append($('
Atlanta Braves
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('braves',$optionlist);}))
						.append($('
Chicago Cubs
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('cubs',$optionlist);}))
						.append($('
Cincinnati Reds
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('reds',$optionlist);}))
						.append($('
Colorado Rockies
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('rockies',$optionlist);}))
						.append($('
Houston Astros
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('houston',$optionlist);}))
						.append($('
Los Angeles Dodgers
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('dodgers',$optionlist);}))
						.append($('
Miami Marlins
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('marlins',$optionlist);}))
						.append($('
Milwaukee Brewers
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('brewers',$optionlist);}))
						.append($('
New York Mets
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('mets',$optionlist);}))
						.append($('
Philadelphia Phillies
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('phillies',$optionlist);}))
						.append($('
Pittsburgh Pirates
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('pirates',$optionlist);}))
						.append($('
St. Louis Cardinals
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('cardinals',$optionlist);}))
						.append($('
San Diego Padres
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('padres',$optionlist);}))
						.append($('
San Francisco Giants
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('giants',$optionlist);}))
						.append($('
Washington Nationals
').bind('click',function(){app.ext.pogs_cubworld.a.openIconDetails('nationals',$optionlist);}));

				$option.append('

')
				return $option;
				},
			renderOptionCUSTOMIZERNOTICE : function(pog){
				$option = $("<input type='hidden' name='AK'/>");

				$atcForm = $('.prodViewerAddToCartForm', (app.ext.pogs_cubworld.vars.prodContext ? app.ext.pogs_cubworld.vars.prodContext : $('#mainContentArea')))
				$atcForm.unbind('submit').attr('onSubmit','');
				$atcForm.bind('submit', function(){
					var $notice = $('

'+pog.prompt+'

');

					var $button = $('
<button class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only">I agree</button>
');
					$button.bind('click',function(){
						$notice.dialog('close');
						$option.val("ON");
						app.ext.myRIA.u.addItemToCart($atcForm,{'action':'modal'});
						return false;
						});

					$notice.append($button);

					$notice.dialog({'modal':'true','title':'Custom Product Agreement'});
					return false;
				});

				return $option
				},
			xinit : function(){
				this.addHandler("pogid","CH","renderOptionLABELDADDYLIST");
				this.addHandler("pogid","AK","renderOptionCUSTOMIZERNOTICE");
				}
			},

////////////////////////////////////   ACTION    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//actions are functions triggered by a user interaction, such as a click/tap.
//these are going the way of the do do, in favor of app events. new extensions should have few (if any) actions.
		a : {
			openIconDetails : function(team, $target){
				var queryString = "?iconname=" + team ;
				var jsonp_url = "http://www.labeldaddy.com/widget/getIcons.php" + queryString + "&jsoncallback=?";
				$.getJSON(jsonp_url, function(data) {
					$target.empty().append($(data.html));
					});
				return false;
				},
			updateMLBIcons : function(iconset){
				$('input[name=CH]', app.ext.pogs_cubworld.vars.prodContext).val(iconset);
				app.ext.pogs_cubworld.u.showLabelPreview();
				}
			}, //Actions

////////////////////////////////////   RENDERFORMATS    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//renderFormats are what is used to actually output data.
//on a data-bind, format: is equal to a renderformat. extension: tells the rendering engine where to look for the renderFormat.
//that way, two render formats named the same (but in different extensions) don't overwrite each other.
		renderFormats : {
			}, //renderFormats
////////////////////////////////////   UTIL [u]   \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//utilities are typically functions that are exected by an event or action.
//any functions that are recycled should be here.
		u : {
			showLabelPreview : function(){

				var labelName = $('input[name=CJ]', app.ext.pogs_cubworld.vars.prodContext).val();
				var labelLastName = $('input[name=CK]', app.ext.pogs_cubworld.vars.prodContext).val();
				var labelIcon = $('input[name=CH]', app.ext.pogs_cubworld.vars.prodContext).val();

				var queryString = "?labelName=" + labelName + "&labellastName=" + labelLastName + "&labelicon=" + labelIcon ;
				var jsonp_url = "http://www.labeldaddy.com/widget/MLBPackWidget.php" + queryString + "&jsoncallback=?";
				$.getJSON(jsonp_url, function(data) {
					$('.labelPreview', app.ext.pogs_cubworld.vars.prodContext).html(data.html);
					});
				}
			}, //u [utilities]

//app-events are added to an element through data-app-event="extensionName|functionName"
//right now, these are not fully supported, but they will be going forward.
//they're used heavily in the admin.html file.
//while no naming convention is stricly forced,
//when adding an event, be sure to do off('click.appEventName') and then on('click.appEventName') to ensure the same event is not double-added if app events were to get run again over the same template.
		e : {
			}, //e [app Events]
		vars : {
			prodContext : undefined
			}
		} //r object.

	return r;
	}<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { AutoSizer, List } from 'react-virtualized';
import type { Addresses } from '../../../../api/addresses/types';
import styles from './VirtualAddressesList.scss';

type Props = {
  rows: Addresses,
  renderRow: Function,
  showUsed: boolean,
};

@observer
export class VirtualAddressesList extends Component<Props> {

  /**
   * Since the transaction addresses are pretty long, they break into the next line on smaller
   * window sizes and the height of expanded tx rows in the list must be adjusted accordingly.
   * @param width
   */
  onResize = ({ width }: { width: number }) => {
    console.log('width', width);
  };

  rowRenderer = ({
    index, // Index of row
    key, // Unique key within array of rendered rows
    style // Style object to be applied to row (to position it);
  }: { key: string, index: number, style: string }) => {
    const { rows, renderRow, showUsed } = this.props;
    console.log('showUsed', showUsed);
    const address = rows[index];
    const isAddressVisible = !address.used || showUsed;
    console.log('isAddressVisible', isAddressVisible);
    if (!isAddressVisible) return null;
    return (

        {renderRow(address, index)}

    );
  }

  render() {
    const { rows } = this.props;

    return (

        <AutoSizer onResize={this.onResize}>
          {({ width, height }) => (
            <List
              className={styles.list}
              width={width}
              height={height}
              rowCount={rows.length}
              rowHeight={68}
              rowRenderer={this.rowRenderer}
            />
          )}
        </AutoSizer>

    );
  }
}
<commit_msg>[DDW-565] Simplistic row height calculation<commit_after>// @flow
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { AutoSizer, List } from 'react-virtualized';
import type { Addresses } from '../../../../api/addresses/types';
import styles from './VirtualAddressesList.scss';

type Props = {
  rows: Addresses,
  renderRow: Function,
  showUsed: boolean,
};

const ADDRESS_LINE_HEIGHT = 30;
const ADDRESS_TWO_LINES_BREAKPOINT = 1198;
const ADDRESS_THREE_LINES_BREAKPOINT = 668;

@observer
export class VirtualAddressesList extends Component<Props> {

  rowHeight: number = 0;

  updateRowHeight = (width: number) => {
    let lines = 1;
    let padding = 10;
    if (width <= ADDRESS_TWO_LINES_BREAKPOINT) lines = 2;
    if (width <= ADDRESS_THREE_LINES_BREAKPOINT) lines = 3;
    if (lines > 1) padding = 0;
    this.rowHeight = (ADDRESS_LINE_HEIGHT * lines) + padding;
  }

  rowRenderer = ({
    index, // Index of row
    key, // Unique key within array of rendered rows
    style // Style object to be applied to row (to position it);
  }: { key: string, index: number, style: string }) => {
    const { rows, renderRow, showUsed } = this.props;
    const address = rows[index];
    const isAddressVisible = !address.used || showUsed;
    if (!isAddressVisible) return null;
    return (

        {renderRow(address, index)}

    );
  }

  render() {
    const { rows } = this.props;

    return (

        <AutoSizer onResize={({ width }) => this.updateRowHeight(width)}>
          {({ width, height }) => {
            this.updateRowHeight(width);
            return (
              <List
                className={styles.list}
                width={width}
                height={height}
                rowCount={rows.length}
                rowHeight={this.rowHeight}
                rowRenderer={this.rowRenderer}
              />
            );
          }
        }
        </AutoSizer>

    );
  }
}
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import { isServerSide, ajax, console, fileUtil } from './../../../util';
import { HiGlassPlainContainer } from './HiGlassPlainContainer';

/** This class will pass the HiGlass Item's viewconfig to the HiGlassPlainContainer, possibly using AJAX to get the information.*/
export class HiGlassAjaxLoadContainer extends React.PureComponent {

    constructor(props){
        super(props);

        this.state = {
            'loading': false,
            'higlassItem' : null
        }

        this.getFullHiglassItem = this.getFullHiglassItem.bind(this);
    }

    componentDidMount(){
        this.getFullHiglassItem();
    }

    componentDidUpdate(pastProps){
        // After updating the component, load the new higlass component if it changed.
        if (pastProps.higlassItem !== this.props.higlassItem){
            this.getFullHiglassItem();
        }
    }

    /**
    * Makes an AJAX call to get the Higlass viewconfig resource.
    */
    getFullHiglassItem(){
        var { higlassItem } = this.props;

        if (!higlassItem) {
            return;
        }

        // If the viewconfig was loaded already, use that
        if ("viewconfig" in higlassItem) {
            this.setState({'higlassItem': higlassItem, 'loading': false});
        }
        else if ('@id' in higlassItem) {
            // Use the @id to make an AJAX request to get the HiGlass Item.
            this.setState({ 'loading': true }, ()=>{
                // Use the @id to get the item, then remove the loading message
                ajax.load(this.props.higlassItem['@id'], (r)=>{
                    this.setState({ 'higlassItem' : r, 'loading': false });
                });
            });
        }
    }
    render(){
        var { higlassItem, loading } = this.state;
        var { height } = this.props;

        // Use the height to make placeholder message when loading.
        var placeholderStyle = {};
        if (typeof height === 'number' && height >= 140){
            placeholderStyle.height = height;
            placeholderStyle.paddingTop = (height / 2) - 40;
        }
        else if(typeof height !== 'number'){
            // If no height is given, assume defaults
            placeholderStyle.height = 600;
            placeholderStyle.paddingTop = (placeholderStyle.height / 2) - 40;
        }

        // If we're loading, show a loading screen
        if (loading){
            return <React.Fragment>

                    Initializing

</React.Fragment>
        }

        // Raise an error if there is no viewconfig
        if (!higlassItem || !higlassItem.viewconfig) {
            return <React.Fragment>

                    No HiGlass content found. Please go back or try again later.

</React.Fragment>
        }

        // Pass the viewconfig to the HiGlassPlainContainer
        return <HiGlassPlainContainer {..._.omit(this.props, 'higlassItem')} viewConfig={higlassItem.viewconfig} />
    }
}
<commit_msg>higlass_ajax_loader: Fixed some spacing and semicolon work.<commit_after>'use strict';

import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import { isServerSide, ajax, console, fileUtil } from './../../../util';
import { HiGlassPlainContainer } from './HiGlassPlainContainer';

/** This class will pass the HiGlass Item's viewconfig to the HiGlassPlainContainer, possibly using AJAX to get the information.*/
export class HiGlassAjaxLoadContainer extends React.PureComponent {

    constructor(props){
        super(props);

        this.state = {
            'loading': false,
            'higlassItem' : null
        }

        this.getFullHiglassItem = this.getFullHiglassItem.bind(this);
    }

    componentDidMount(){
        this.getFullHiglassItem();
    }

    componentDidUpdate(pastProps){
        // After updating the component, load the new higlass component if it changed.
        if (pastProps.higlassItem !== this.props.higlassItem){
            this.getFullHiglassItem();
        }
    }

    /**
    * Makes an AJAX call to get the Higlass viewconfig resource.
    */
    getFullHiglassItem(){
        var { higlassItem } = this.props;

        if (!higlassItem) {
            return;
        }

        // If the viewconfig was loaded already, use that
        if ("viewconfig" in higlassItem) {
            this.setState({'higlassItem': higlassItem, 'loading': false});
        }
        else if ('@id' in higlassItem) {
            // Use the @id to make an AJAX request to get the HiGlass Item.
            this.setState({ 'loading': true }, ()=>{
                // Use the @id to get the item, then remove the loading message
                ajax.load(this.props.higlassItem['@id'], (r)=>{
                    this.setState({ 'higlassItem' : r, 'loading': false });
                });
            });
        }
    }
    render(){
        var { higlassItem, loading } = this.state;
        var { height } = this.props;

        // Use the height to make placeholder message when loading.
        var placeholderStyle = {};
        if (typeof height === 'number' && height >= 140){
            placeholderStyle.height = height;
            placeholderStyle.paddingTop = (height / 2) - 40;
        }
        else if(typeof height !== 'number'){
            // If no height is given, assume defaults
            placeholderStyle.height = 600;
            placeholderStyle.paddingTop = (placeholderStyle.height / 2) - 40;
        }

        // If we're loading, show a loading screen
        if (loading){
            return <React.Fragment>

                Initializing

</React.Fragment>;
        }

        // Raise an error if there is no viewconfig
        if (!higlassItem || !higlassItem.viewconfig) {
            return <React.Fragment>

                No HiGlass content found. Please go back or try again later.

</React.Fragment>;
        }

        // Pass the viewconfig to the HiGlassPlainContainer
        return <HiGlassPlainContainer {..._.omit(this.props, 'higlassItem')} viewConfig={higlassItem.viewconfig} />;
    }
}
<|endoftext|>


<commit_before>/**
    入驻小区
**/
(function(vc){
    var DEFAULT_PAGE = 1;
    var DEFAULT_ROWS = 10;
    vc.extends({
        data:{
            purchaseApplyManageInfo:{
                purchaseApplys:[],
                total:0,
                records:1,
                moreCondition:false,
                applyOrderId:'',
                states:'',
                conditions:{
                    state:'',
                    userName:''
                }
            }
        },
        _initMethod:function(){
            vc.component._listPurchaseApplys(DEFAULT_PAGE, DEFAULT_ROWS);
        },
        _initEvent:function(){
            vc.on('purchaseApplyManage','listPurchaseApply',function(_param){
                  vc.component._listPurchaseApplys(DEFAULT_PAGE, DEFAULT_ROWS);
            });
             vc.on('pagination','page_event',function(_currentPage){
                vc.component._listPurchaseApplys(_currentPage,DEFAULT_ROWS);
            });
        },
        methods:{
            _listPurchaseApplys:function(_page, _rows){

                vc.component.purchaseApplyManageInfo.conditions.page = _page;
                vc.component.purchaseApplyManageInfo.conditions.row = _rows;
                var param = {
                    params:vc.component.purchaseApplyManageInfo.conditions
               };

               //发送get请求
               vc.http.get('purchaseApplyManage',
                            'list',
                             param,
                             function(json,res){
                                var _purchaseApplyManageInfo=JSON.parse(json);
                                vc.component.purchaseApplyManageInfo.total = _purchaseApplyManageInfo.total;
                                vc.component.purchaseApplyManageInfo.records = _purchaseApplyManageInfo.records;
                                vc.component.purchaseApplyManageInfo.purchaseApplys = _purchaseApplyManageInfo.purchaseApplys;
                                vc.emit('pagination','init',{
                                     total:vc.component.purchaseApplyManageInfo.records,
                                     currentPage:_page
                                 });
                             },function(errInfo,error){
                                console.log('请求失败处理');
                             }
                           );
            },
            _openAddPurchaseApplyModal:function(){
                vc.jumpToPage("/flow/addPurchaseApplyStepFlow");
            },
            _openDetailPurchaseApplyModel:function(_purchaseApply){
                vc.jumpToPage("/flow/purchaseApplyDetailFlow?applyOrderId="+_purchaseApply.applyOrderId);
            },
            _openDeletePurchaseApplyModel:function(_purchaseApply){
                vc.emit('deletePurchaseApply','openDeletePurchaseApplyModal',_purchaseApply);
            },
            _queryPurchaseApplyMethod:function(){
                vc.component._listPurchaseApplys(DEFAULT_PAGE, DEFAULT_ROWS);

            },
            _moreCondition:function(){
                if(vc.component.purchaseApplyManageInfo.moreCondition){
                    vc.component.purchaseApplyManageInfo.moreCondition = false;
                }else{
                    vc.component.purchaseApplyManageInfo.moreCondition = true;
                }
            },
            _queryInspectionPlanMethod:function () {
                vc.component._listPurchaseApplys(DEFAULT_PAGE, DEFAULT_ROWS);
            }

        }
    });
})(window.vc);
<commit_msg>优化purchaseApplyManage.js<commit_after>/**
    入驻小区
**/
(function(vc){
    var DEFAULT_PAGE = 1;
    var DEFAULT_ROWS = 10;
    vc.extends({
        data:{
            purchaseApplyManageInfo:{
                purchaseApplys:[],
                total:0,
                records:1,
                moreCondition:false,
                applyOrderId:'',
                states:'',
                conditions:{
                    state:'',
                    userName:'',
                    resOrderType:'10000'
                }
            }
        },
        _initMethod:function(){
            vc.component._listPurchaseApplys(DEFAULT_PAGE, DEFAULT_ROWS);
        },
        _initEvent:function(){
            vc.on('purchaseApplyManage','listPurchaseApply',function(_param){
                  vc.component._listPurchaseApplys(DEFAULT_PAGE, DEFAULT_ROWS);
            });
             vc.on('pagination','page_event',function(_currentPage){
                vc.component._listPurchaseApplys(_currentPage,DEFAULT_ROWS);
            });
        },
        methods:{
            _listPurchaseApplys:function(_page, _rows){

                vc.component.purchaseApplyManageInfo.conditions.page = _page;
                vc.component.purchaseApplyManageInfo.conditions.row = _rows;
                var param = {
                    params:vc.component.purchaseApplyManageInfo.conditions
               };

               //发送get请求
               vc.http.get('purchaseApplyManage',
                            'list',
                             param,
                             function(json,res){
                                var _purchaseApplyManageInfo=JSON.parse(json);
                                vc.component.purchaseApplyManageInfo.total = _purchaseApplyManageInfo.total;
                                vc.component.purchaseApplyManageInfo.records = _purchaseApplyManageInfo.records;
                                vc.component.purchaseApplyManageInfo.purchaseApplys = _purchaseApplyManageInfo.purchaseApplys;
                                vc.emit('pagination','init',{
                                     total:vc.component.purchaseApplyManageInfo.records,
                                     currentPage:_page
                                 });
                             },function(errInfo,error){
                                console.log('请求失败处理');
                             }
                           );
            },
            _openAddPurchaseApplyModal:function(){
                vc.jumpToPage("/flow/addPurchaseApplyStepFlow");
            },
            _openDetailPurchaseApplyModel:function(_purchaseApply){
                vc.jumpToPage("/flow/purchaseApplyDetailFlow?applyOrderId="+_purchaseApply.applyOrderId);
            },
            _openDeletePurchaseApplyModel:function(_purchaseApply){
                vc.emit('deletePurchaseApply','openDeletePurchaseApplyModal',_purchaseApply);
            },
            _queryPurchaseApplyMethod:function(){
                vc.component._listPurchaseApplys(DEFAULT_PAGE, DEFAULT_ROWS);

            },
            _moreCondition:function(){
                if(vc.component.purchaseApplyManageInfo.moreCondition){
                    vc.component.purchaseApplyManageInfo.moreCondition = false;
                }else{
                    vc.component.purchaseApplyManageInfo.moreCondition = true;
                }
            },
            _queryInspectionPlanMethod:function () {
                vc.component._listPurchaseApplys(DEFAULT_PAGE, DEFAULT_ROWS);
            }

        }
    });
})(window.vc);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    testFormatDateTime:{
		attributes: {value : '2004-09-23T16:30:00.000Z'},
        test:function(cmp){
            aura.test.addWaitFor(true, function(){return $A.test.getText(cmp.getSuper().find('span').getElement()).length > 0;},function(){
                aura.test.assertEquals("+00:00 00:30:16 09 23 2004", $A.test.getText(cmp.getSuper().find('span').getElement()), "Format should be the one specified in the overridden method");
            });
        }
    }
})
<commit_msg>Fixing TF W-1793328<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
({
    testFormatDateTime:{
		attributes: {value : '2004-09-23T16:30:00.000Z', timezone : "GMT"},
        test:function(cmp){
            aura.test.addWaitFor(true, function(){return $A.test.getText(cmp.getSuper().find('span').getElement()).length > 0;},function(){
                aura.test.assertEquals("+00:00 00:30:16 09 23 2004", $A.test.getText(cmp.getSuper().find('span').getElement()), "Format should be the one specified in the overridden method");
            });
        }
    }
})
<|endoftext|>


<commit_before>Hogan.cache['hello'] = function(c,p,i){var _=this;_.b(i=i||"");_.b("Hello ");_.b(_.v(_.f("name",c,p,0)));_.b("! You have ");_.b(_.v(_.f("count",c,p,0)));_.b(" new messages.");_.b("\n");return _.fl();;}<commit_msg>fix failing HoganJsTest<commit_after>Hogan.cache['hello'] = function(c,p,i){var _=this;_.b(i=i||"");_.b("Hello ");_.b(_.v(_.f("name",c,p,0)));_.b("! You have ");_.b(_.v(_.f("count",c,p,0)));_.b(" new messages.");_.b("\n");return _.fl();;};<|endoftext|>