<commit_before>openerp.suvit_web_tree = function(instance, local) {
  var QWeb = instance.web.qweb;
  var _t = instance.web._t;
  var _lt = instance.web._lt;

  /********* Custom domain for List & Tree Views in same Action ********/
  instance.web.FormView.include({
      on_button_save: function(e) {
          var self = this;
          _.each(this.ViewManager.ActionManager.breadcrumbs, function(br){
            br.need_update = true;
          });

          return self._super(e).then(function(){
              if (self.ViewManager.views.tree)
                self.ViewManager.views.tree.controller.switch_mode()
          });
      },
      on_button_create: function() {
          var self = this;
          self._super();
          if (self.ViewManager.views.tree)
            self.ViewManager.views.tree.controller.switch_mode()
      }
  });

  instance.web.TreeView.include({
    init: function (parent, dataset, view_id, options) {
        if (parent.action && parent.action.context.tree_domain){
          var domain = new instance.web.CompoundDomain(dataset.domain, parent.action.context.tree_domain);
          dataset = new instance.web.DataSetSearch(this, parent.action.res_model, dataset.context, domain);
        }
        this._super(parent, dataset, view_id, options);
    },
    switch_mode: function () {
      this.$el.find(".oe-treeview-table > tbody").empty();
      _(this.fields_view.arch.children).each(function (field) {
          if (field.attrs.modifiers && typeof(field.attrs.modifiers) == 'object') {
              field.attrs.modifiers = JSON.stringify(field.attrs.modifiers);
          }
      });
      this.view_loading(this.fields_view);
    },
    hook_row_click: function () {
      this.$el.undelegate('.treeview-tr', 'click');
      this._super();
    },

    getdata: function (id, children_ids) {
        // do not getdata twice, this class stop loading
        this.$el.find('#treerow_' + id).addClass('oe_open');

        var self = this;

        self.dataset.read_ids(children_ids, this.fields_list()).done(function(records) {
            _(records).each(function (record) {
                self.records[record.id] = record;
            });
            var $curr_node = self.$el.find('#treerow_' + id);
            var children_rows = QWeb.render('TreeView.rows', {
                'records': records,
                'children_field': self.children_field,
                'fields_view': self.fields_view.arch.children,
                'fields': self.fields,
                'level': $curr_node.data('level') || 0,
                'render': instance.web.format_value,
                'color_for': self.color_for,
                'row_parent_id': id
            });
            if ($curr_node.length) {
                $curr_node.addClass('oe_open');
                $curr_node.after(children_rows);
            } else {
                self.$el.find('tbody').html(children_rows);
            }
        }).then(function(){
          if (self.ViewManager.action && self.ViewManager.action.id) {
            view_id = self.ViewManager.action.id;
            var open_trees = JSON.parse(localStorage.getItem('open_trees') || '{}');
                if (!open_trees[view_id]) {open_trees[view_id] = {};}
            open_trees[view_id][id] = true;
            localStorage["open_trees"] = JSON.stringify(open_trees);
            for(k in open_trees[view_id]){
              if (open_trees[view_id][k]) {
                $('#treerow_'+k+':not(.oe_open) .treeview-tr').click();
              }
            }
          }
        });
    },

    showcontent: function (curnode,record_id, show) {
      this._super(curnode,record_id, show);
      if (this.ViewManager && this.ViewManager.action) {
        view_id = this.ViewManager.action.id;
        var open_trees = JSON.parse(localStorage.getItem('open_trees') || '{}');
        if (!open_trees[view_id]) {open_trees[view_id] = {};}
        open_trees[view_id][record_id] = show;
        localStorage["open_trees"] = JSON.stringify(open_trees);
      }
    },
  });
  instance.web.ActionManager.include({
    select_breadcrumb: function(index, subindex) {
      var self = this;
      var item = this.breadcrumbs[index];
      if (item.widget.views.tree && item.need_update) {
        item.need_update=false;
        item.widget.views.tree.controller.switch_mode();
      }
      return this._super(index, subindex);
    },
  });

  /********* Many2Many Tree Field ********/
  local.Many2ManyTreeField = instance.web.form.FieldMany2Many.extend({
    initialize_content: function() {
        if (!(this.field.type == 'many2many' || this.field.type == 'one2many'))
            return this._super();
        this.list_view = new instance.web.TreeView(this, this.dataset, false, {
                    'addable': false,
                    'deletable': false,
                    'selectable': false,
                    'sortable': false,
                    'reorderable': false,
                    'import_enabled': false,
            });
        this.$el.empty();
        this.list_view.appendTo(this.$el);
    },
    render_value: function() {
      this.initialize_content();
      return this._super();
    }
  });

  instance.web.form.widgets.add('many2many_tree', 'instance.suvit_web_tree.Many2ManyTreeField');
};
<commit_msg>постраничник в дереве<commit_after>openerp.suvit_web_tree = function(instance, local) {
  var QWeb = instance.web.qweb;
  var _t = instance.web._t;
  var _lt = instance.web._lt;

  /********* Custom domain for List & Tree Views in same Action ********/
  instance.web.FormView.include({
      init: function(parent, dataset, view_id, options) {
        var self = this;
        this._super(parent, dataset, view_id, options);
        if (self.dataset.context && self.dataset.context.ids && self.dataset.context.ids.length) {
            self.dataset.ids = self.dataset.context.ids;
            self.dataset.index = self.dataset.ids.indexOf(self.dataset.context.active_id);
        }
      },
      on_button_save: function(e) {
          var self = this;
          _.each(this.ViewManager.ActionManager.breadcrumbs, function(br){
            br.need_update = true;
          });

          return self._super(e).then(function(){
              if (self.ViewManager.views.tree)
                self.ViewManager.views.tree.controller.switch_mode()
          });
      },
      on_button_create: function() {
          var self = this;
          self._super();
          if (self.ViewManager.views.tree)
            self.ViewManager.views.tree.controller.switch_mode()
      }
  });

  instance.web.TreeView.include({
    init: function (parent, dataset, view_id, options) {
        if (parent.action && parent.action.context.tree_domain){
          var domain = new instance.web.CompoundDomain(dataset.domain, parent.action.context.tree_domain);
          dataset = new instance.web.DataSetSearch(this, parent.action.res_model, dataset.context, domain);
        }
        this._super(parent, dataset, view_id, options);
    },
    switch_mode: function () {
      this.$el.find(".oe-treeview-table > tbody").empty();
      _(this.fields_view.arch.children).each(function (field) {
          if (field.attrs.modifiers && typeof(field.attrs.modifiers) == 'object') {
              field.attrs.modifiers = JSON.stringify(field.attrs.modifiers);
          }
      });
      this.view_loading(this.fields_view);
    },
    hook_row_click: function () {
      this.$el.undelegate('.treeview-tr', 'click');
      this._super();
    },

    getdata: function (id, children_ids) {
        // do not getdata twice, this class stop loading
        this.$el.find('#treerow_' + id).addClass('oe_open');

        var self = this;

        self.dataset.read_ids(children_ids, this.fields_list()).done(function(records) {
            _(records).each(function (record) {
                self.records[record.id] = record;
            });
            var $curr_node = self.$el.find('#treerow_' + id);
            var children_rows = QWeb.render('TreeView.rows', {
                'records': records,
                'children_field': self.children_field,
                'fields_view': self.fields_view.arch.children,
                'fields': self.fields,
                'level': $curr_node.data('level') || 0,
                'render': instance.web.format_value,
                'color_for': self.color_for,
                'row_parent_id': id
            });
            if ($curr_node.length) {
                $curr_node.addClass('oe_open');
                $curr_node.after(children_rows);
            } else {
                self.$el.find('tbody').html(children_rows);
            }
        }).then(function(){
          if (self.ViewManager.action && self.ViewManager.action.id) {
            view_id = self.ViewManager.action.id;
            var open_trees = JSON.parse(localStorage.getItem('open_trees') || '{}');
                if (!open_trees[view_id]) {open_trees[view_id] = {};}
            open_trees[view_id][id] = true;
            localStorage["open_trees"] = JSON.stringify(open_trees);
            for(k in open_trees[view_id]){
              if (open_trees[view_id][k]) {
                $('#treerow_'+k+':not(.oe_open) .treeview-tr').click();
              }
            }
          }
        });
    },

    showcontent: function (curnode,record_id, show) {
      this._super(curnode,record_id, show);
      if (this.ViewManager && this.ViewManager.action) {
        view_id = this.ViewManager.action.id;
        var open_trees = JSON.parse(localStorage.getItem('open_trees') || '{}');
        if (!open_trees[view_id]) {open_trees[view_id] = {};}
        open_trees[view_id][record_id] = show;
        localStorage["open_trees"] = JSON.stringify(open_trees);
      }
    },
  });
  instance.web.ActionManager.include({
    select_breadcrumb: function(index, subindex) {
      var self = this;
      var item = this.breadcrumbs[index];
      if (item.widget.views.tree && item.need_update) {
        item.need_update=false;
        item.widget.views.tree.controller.switch_mode();
      }
      return this._super(index, subindex);
    },
  });

  /********* Many2Many Tree Field ********/
  local.Many2ManyTreeField = instance.web.form.FieldMany2Many.extend({
    initialize_content: function() {
        if (!(this.field.type == 'many2many' || this.field.type == 'one2many'))
            return this._super();
        this.list_view = new instance.web.TreeView(this, this.dataset, false, {
                    'addable': false,
                    'deletable': false,
                    'selectable': false,
                    'sortable': false,
                    'reorderable': false,
                    'import_enabled': false,
            });
        this.$el.empty();
        this.list_view.appendTo(this.$el);
    },
    render_value: function() {
      this.initialize_content();
      return this._super();
    }
  });

  instance.web.form.widgets.add('many2many_tree', 'instance.suvit_web_tree.Many2ManyTreeField');
};
<|endoftext|>


<commit_before>/*
    Debug panels for javascript
    debug.js <https://github.com/davidfig/debug>
    Released under MIT license <https://github.com/davidfig/anglejs/license>
    Author: David Figatner
    Copyright (c) 2016 YOPEY YOPEY LLC
*/

var defaultDiv = null;
var sides = {
    'leftTop': {isMinimized: false, minimize: null, count: null, panels: [], minimized: [], dir: 'leftTop'},
    'leftBottom': {isMinimized: false, minimize: null, count: null, panels: [], minimized: [], dir: 'leftBottom'},
    'rightTop': {isMinimized: false, minimize: null, count: null, panels: [], minimized: [], dir: 'rightTop'},
    'rightBottom': {isMinimized: false, minimize: null, count: null, panels: [], minimized: [], dir: 'rightBottom'}
};

// options for the default debug panel (see add())
function init(options)
{
    options = options || {};
    if (!options.size)
    {
        options.size = 0.25;
    }
    if (!options.expandable)
    {
        options.expandable = 0.5;
    }
    add('debug', options);
    window.addEventListener('resize', resize);
    window.addEventListener('error', error);
    document.addEventListener('keypress', keypress);
}

// converts side
function getSide(side)
{
    if (!side)
    {
        return sides['rightBottom'];
    }
    var change = side.toUpperCase();
    if (change === 'LEFTBOTTOM' || change === 'BOTTOMLEFT')
    {
        return sides['leftBottom'];
    }
    else if (change === 'RIGHTBOTTOM' || change === 'BOTTOMRIGHT')
    {
        return sides['rightBottom'];
    }
    else if (change === 'LEFTTOP' || change === 'TOPLEFT')
    {
        return sides['leftTop'];
    }
    else if (change === 'RIGHTTOP' || change === 'TOPRIGHT')
    {
        return sides['rightTop'];
    }
    else
    {
        return sides['rightBottom'];
    }
}

// options {}
//  side: 'rightBottom' (default), 'leftBottom', 'leftTop', 'rightTop'
//  expandable: 0 (default) or percent size to expand
//  default: if true then this panel becomes default for calls to debug and debugOne
//  size: 0 (default) or percent size
//  style: object with CSS styles for the panel
function add(name, options)
{
    options = options || {};
    var div = document.createElement('div');
    document.body.appendChild(div);
    div.options = options;
    if (!defaultDiv || options.default)
    {
        defaultDiv = div;
    }
    var side = getSide(options.side);
    var s = div.style;
    s.fontFamily = "Helvetica Neue";
    s.position = "fixed";
    if (isLeft(side))
    {
        s.left = 0;
    }
    else
    {
        s.right = 0;
    }
    if (options.style)
    {
        for (var key in options.style)
        {
            s[key] = options.style[key];
        }
    }
    minimizeCreate(side);
    div.side = side;
    side.panels[name] = div;
    style(div, side);
    div.click = handleClick;
    click(div);
    if (options.text)
    {
        div.innerHTML = options.text;
    }
    resize();
    return div;
}

// options {}
//  side: 'leftBottom' (default), 'leftTop', 'rightBottom', 'rightTop'
//  width: defaults to 100px
//  height: default to 25px
function addMeter(name, options)
{
    options = options || {};
    var div = document.createElement('canvas');
    div.type = 'meter';
    div.width = options.width || 100;
    div.height = options.height || 25;
    div.style.width = div.width + 'px';
    div.style.height = div.height + 'px';
    document.body.appendChild(div);
    div.options = options;
    var side = getSide(options.side);
    var s = div.style;
    s.fontFamily = "Helvetica Neue";
    s.position = "fixed";
    if (isLeft(side))
    {
        s.left = 0;
    }
    else
    {
        s.right = 0;
    }
    minimizeCreate(side);
    div.side = side;
    side.panels[name] = div;
    style(div, side);
    div.click = handleClick;
    click(div);
    if (options.text)
    {
        div.innerHTML = options.text;
    }
    resize();
    return div;
}

// adds a line to the end of the meter and scrolls the meter as necessary
//      percent: between -1 to +1
//      name: name of panel
//      panel: panel returned from Debug.Add()
function meter(percent, options)
{
    var div;
    options = options || {};
    if (!options.panel && !options.name)
    {
        div = defaultDiv;
    }
    else
    {
        div = options.panel || left.panels[options.name] || right.panels[options.name];
    }
    c = div.getContext('2d');
    var data = c.getImageData(0, 0, div.width, div.height);
    c.putImageData(data, -1, 0);
    c.clearRect(div.width - 1, 0, div.width - 1, div.height);
    var height, middle = Math.round(div.height / 2);
    if (percent < 0)
    {
        c.fillStyle = 'red';
        percent = Math.abs(percent);
        height = (25 - middle) * -percent;
        c.fillRect(div.width - 1, middle, div.width - 1, middle + height);
    }
    else
    {
        c.fillStyle = 'white';
        height = middle * percent;
        c.fillRect(div.width - 1, height, div.width - 1, middle - height);
    }
}

function getDiv(options)
{
    var div;
    if (!options.panel && !options.name)
    {
        div = defaultDiv;
    }
    else if (options.panel)
    {
        div = options.panel;
    }
    else
    {
        for (var name in sides)
        {
            var panel = sides[name].panels[options.name];
            if (panel)
            {
                div = panel;
                break;
            }
        }
    }
    if (!div)
    {
        div = defaultDiv;
    }
    return div;
}

// adds text to the end of in the panel and scrolls the panel
// options:
//      color: background color for text
//      name: name of panel
//      panel: panel returned from Debug.Add()
function debug(text, options)
{
    options = options || {};
    var div = getDiv(options);
    if (options.color)
    {
        div.style.backgroundColor = options.color === 'error' ? 'red' : options.color;
    }
    else
    {
        div.style.backgroundColor = 'rgba(150,150,150,0.5)';
    }
    var error = false;
    var result = '
';
    if (text === null)
    {
        result += 'null';
    }
    else if (typeof text === 'object')
    {
        for (var i = 0; i < text.length; i++)
        {
            result += text[i] + ((i !== text.length -1) ? ', ' : '');
        }
    }
    else
    {
        result += text;
    }
    result += '
';
    div.innerHTML += result;
    div.scrollTop = div.scrollHeight;
    if (options.color === 'error')
    {
        defaultDiv.expanded = true;
        resize();
    }
}

// replaces all text in the panel
// options:
//      name: name of panel
//      panel: panel returned from Debug.Add()
function debugOne(text, options)
{
    options = options || {};
    var div = getDiv(options);
    if (options.color)
    {
        div.style.backgroundColor = options.color;
    }
    else
    {
        div.style.backgroundColor = 'rgba(150,150,150,0.5)';
    }
    var html = '';
    if (typeof text === 'object')
    {
        for (var i = 0, _i = text.length; i < _i; i++)
        {
            html += text[i] + ((i !== _i -1) ? ', ' : '');
        }
    }
    else
    {
        html += text;
    }
    html += '';
    div.innerHTML = html;
}

// adds a debug message showing who called the function
function caller(options)
{
    if (arguments.callee.caller)
    {
        debug('Called by: ' + arguments.callee.caller.arguments.callee.caller.name + ': ' + arguments.callee.caller.arguments.callee.caller.toString(), options);
    }
    else
    {
        debug('Called by: top level', options);
    }
}

// returns a panel based on its name
function get(name)
{
    for (side in sides)
    {
        if (sides[side].panels[name])
        {
            return sides[side].panels[name];
        }
    }
    return null;
}

function style(div, side)
{
    var s = div.style;
    s.fontFamily = "Helvetica Neue";
    s.position = "fixed";
    s.background = "rgba(150,150,150,0.5)";
    s.color = "white";
    s.margin = 0;
    s.padding = "5px";
    s.boxShadow = (isLeft(side) ? '' : '-') + '5px -5px 10px rgba(0,0,0,0.25)';
    s.cursor = 'pointer';
    s.wordWrap = 'break-word';
    s.overflow = 'auto';
    s.zIndex = 1000;
}

function minimizeCreate(side)
{
    if (side.minimize)
    {
        return;
    }
    var div = document.createElement('div');
    div.options = {};
    document.body.appendChild(div);
    var s = div.style;
    div.side = side;
    if (isLeft(side))
    {
        s.left = 0;
    }
    else
    {
        s.right = 0;
    }
    style(div, side);
    s.backgroundColor = 'transparent';
    s.boxShadow = null;
    s.padding = 0;
    side.minimize = div;
    var minimize = document.createElement('span');
    var count = document.createElement('span');
    minimize.click = handleMinimize;
    count.click = handleCount;
    if (isLeft(side))
    {
        div.appendChild(minimize);
        div.appendChild(count);
        count.style.marginLeft = '20px';
    }
    else
    {
        div.appendChild(count);
        div.appendChild(minimize);
        count.style.marginRight = '20px';
    }
    count.style.background = minimize.style.background = "rgba(150,150,150,0.5)";
    count.style.boxShadow = minimize.style.boxShadow = (isLeft ? '' : '-') + '5px -5px 10px rgba(0,0,0,0.25)';
    count.style.padding = minimize.style.padding = '5px';
    minimize.innerHTML = "—";
    count.style.display = 'none';
    minimize.style
    side.count = count;
    click(side.count, isLeft);
    click(minimize, isLeft);
}

// set click events for panel
function click(div, isLeft)
{
    div.addEventListener('click', div.click);
    div.addEventListener('touchstart', div.click);
    div.style.pointerEvents = 'auto';
    div.isLeft = isLeft;
}

function handleMinimize(e)
{
    var div = e.currentTarget;
    var side = e.currentTarget.offsetParent.side;
    side.isMinimized = !side.isMinimized;
    div.innerHTML = side.isMinimized ? "+" : '—';
    resize();
}

function handleCount(e)
{
    var side = e.currentTarget.offsetParent.side;
    side.minimized.pop();
    resize();
}

function handleClick(e)
{
    var div = e.currentTarget;
    if (div.options.expandable)
    {
        div.expanded = !div.expanded;
    }
    else
    {
        var index = div.side.minimized.indexOf(div);
        if (index === -1)
        {
            div.side.minimized.push(div);
        }
        else
        {
            div.side.minimized.splice(index, 1);
        }
    }
    resize();
}

function resizeSide(side)
{
    if (side.isMinimized)
    {
        for (var name in side.panels)
        {
            var panel = side.panels[name];
            panel.style.display = 'none';
        }
        if (isBottom(side))
        {
            side.minimize.style.bottom = window.innerHeight / 4 + 'px';
        }
        else
        {
            side.minimize.style.top = window.innerHeight / 4 + 'px';
        }
        side.count.style.display = 'none';
    }
    else
    {
        var count = 0;
        var divs = [];
        for (var name in side.panels)
        {
            var panel = side.panels[name];
            if (side.minimized.indexOf(panel) === -1)
            {
                panel.style.display = 'block';
                divs.push(panel);
            }
            else
            {
                panel.style.display = 'none';
                count++;
            }
        }
        divs.push(side.minimize);
        var max = Math.min(window.innerWidth, window.innerHeight);
        var current = 0;
        for (var i = 0; i < divs.length; i++)
        {
            var div = divs[i];
            if (isBottom(side))
            {
                div.style.bottom = current + 'px';
            }
            else
            {
                div.style.top = current + 'px';
            }
            if (div.options.size)
            {
                var size;
                if (div.options.expandable)
                {
                    size = max * (div.expanded ? div.options.expandable : div.options.size);
                }
                else
                {
                    size = max * div.options.size;
                }
                div.style.width = div.style.height = size + 'px';
                div.style.display = 'block';
            }
            div.scrollTop = div.scrollHeight;
            current += 10 + div.offsetHeight;
        }
        if (count === 0)
        {
            side.count.style.display = 'none';
        }
        else
        {
            side.count.style.display = 'inline';
            side.count.innerHTML = count;
        }
    }
}

function resize()
{
    function side(dir)
    {
        if (sides[dir].minimize)
        {
            resizeSide(sides[dir]);
        }
    }
    side('leftBottom');
    side('rightBottom');
    side('leftTop');
    side('rightTop');
}

function isLeft(side)
{
    return side.dir.indexOf('left') !== -1;
}

function isBottom(side)
{
    return side.dir.indexOf('Bottom') !== -1;
}

// Captures ` key to expand default debug box
function keypress(e)
{
    var code = (typeof e.which === "number") ? e.which : e.keyCode;
    if (code === 96)
    {
        handleClick({currentTarget: defaultDiv});
    }
}

function error(e)
{
    console.log(e);
    debug((e.message ? e.message : (e.error && e.error.message ? e.error.message : '')) + " at " + e.filename + " line " + e.lineno, {color: "error"});
}

// exports
var Debug = {
    init: init,
    add: add,
    addMeter: addMeter,
    meter: meter,
    get: get,
    resize: resize,
    caller: caller
};

// add support for AMD (Asynchronous Module Definition) libraries such as require.js.
if (typeof define === 'function' && define.amd)
{
    define(function()
    {
        return {
            Debug: Debug,
            debug: debug,
            debugOne: debugOne
        };
    });
}

// add support for CommonJS libraries such as browserify.
if (typeof exports !== 'undefined')
{
    exports.Debug = Debug;
    exports.debug = debug;
    exports.debugOne = debugOne;
}

// define globally in case AMD is not available or available but not used
if (typeof window !== 'undefined')
{
    window.Debug = Debug;
    window.debug = debug;
    window.debugOne = debugOne;
}<commit_msg>formatting<commit_after>// Debug panels for javascript
// debug.js <https://github.com/davidfig/debug>
// Released under MIT license <https://github.com/davidfig/anglejs/license>
// Author: David Figatner
// Copyright (c) 2016 YOPEY YOPEY LLC

var defaultDiv = null;
var sides = {
    'leftTop': {isMinimized: false, minimize: null, count: null, panels: [], minimized: [], dir: 'leftTop'},
    'leftBottom': {isMinimized: false, minimize: null, count: null, panels: [], minimized: [], dir: 'leftBottom'},
    'rightTop': {isMinimized: false, minimize: null, count: null, panels: [], minimized: [], dir: 'rightTop'},
    'rightBottom': {isMinimized: false, minimize: null, count: null, panels: [], minimized: [], dir: 'rightBottom'}
};

// options for the default debug panel (see add())
function init(options)
{
    options = options || {};
    if (!options.size)
    {
        options.size = 0.25;
    }
    if (!options.expandable)
    {
        options.expandable = 0.5;
    }
    add('debug', options);
    window.addEventListener('resize', resize);
    window.addEventListener('error', error);
    document.addEventListener('keypress', keypress);
}

// converts side
function getSide(side)
{
    if (!side)
    {
        return sides['rightBottom'];
    }
    var change = side.toUpperCase();
    if (change === 'LEFTBOTTOM' || change === 'BOTTOMLEFT')
    {
        return sides['leftBottom'];
    }
    else if (change === 'RIGHTBOTTOM' || change === 'BOTTOMRIGHT')
    {
        return sides['rightBottom'];
    }
    else if (change === 'LEFTTOP' || change === 'TOPLEFT')
    {
        return sides['leftTop'];
    }
    else if (change === 'RIGHTTOP' || change === 'TOPRIGHT')
    {
        return sides['rightTop'];
    }
    else
    {
        return sides['rightBottom'];
    }
}

// options {}
//  side: 'rightBottom' (default), 'leftBottom', 'leftTop', 'rightTop'
//  expandable: 0 (default) or percent size to expand
//  default: if true then this panel becomes default for calls to debug and debugOne
//  size: 0 (default) or percent size
//  style: object with CSS styles for the panel
function add(name, options)
{
    options = options || {};
    var div = document.createElement('div');
    document.body.appendChild(div);
    div.options = options;
    if (!defaultDiv || options.default)
    {
        defaultDiv = div;
    }
    var side = getSide(options.side);
    var s = div.style;
    s.fontFamily = "Helvetica Neue";
    s.position = "fixed";
    if (isLeft(side))
    {
        s.left = 0;
    }
    else
    {
        s.right = 0;
    }
    if (options.style)
    {
        for (var key in options.style)
        {
            s[key] = options.style[key];
        }
    }
    minimizeCreate(side);
    div.side = side;
    side.panels[name] = div;
    style(div, side);
    div.click = handleClick;
    click(div);
    if (options.text)
    {
        div.innerHTML = options.text;
    }
    resize();
    return div;
}

// options {}
//  side: 'leftBottom' (default), 'leftTop', 'rightBottom', 'rightTop'
//  width: defaults to 100px
//  height: default to 25px
function addMeter(name, options)
{
    options = options || {};
    var div = document.createElement('canvas');
    div.type = 'meter';
    div.width = options.width || 100;
    div.height = options.height || 25;
    div.style.width = div.width + 'px';
    div.style.height = div.height + 'px';
    document.body.appendChild(div);
    div.options = options;
    var side = getSide(options.side);
    var s = div.style;
    s.fontFamily = "Helvetica Neue";
    s.position = "fixed";
    if (isLeft(side))
    {
        s.left = 0;
    }
    else
    {
        s.right = 0;
    }
    minimizeCreate(side);
    div.side = side;
    side.panels[name] = div;
    style(div, side);
    div.click = handleClick;
    click(div);
    if (options.text)
    {
        div.innerHTML = options.text;
    }
    resize();
    return div;
}

// adds a line to the end of the meter and scrolls the meter as necessary
//      percent: between -1 to +1
//      name: name of panel
//      panel: panel returned from Debug.Add()
function meter(percent, options)
{
    var div;
    options = options || {};
    if (!options.panel && !options.name)
    {
        div = defaultDiv;
    }
    else
    {
        div = options.panel || left.panels[options.name] || right.panels[options.name];
    }
    c = div.getContext('2d');
    var data = c.getImageData(0, 0, div.width, div.height);
    c.putImageData(data, -1, 0);
    c.clearRect(div.width - 1, 0, div.width - 1, div.height);
    var height, middle = Math.round(div.height / 2);
    if (percent < 0)
    {
        c.fillStyle = 'red';
        percent = Math.abs(percent);
        height = (25 - middle) * -percent;
        c.fillRect(div.width - 1, middle, div.width - 1, middle + height);
    }
    else
    {
        c.fillStyle = 'white';
        height = middle * percent;
        c.fillRect(div.width - 1, height, div.width - 1, middle - height);
    }
}

function getDiv(options)
{
    var div;
    if (!options.panel && !options.name)
    {
        div = defaultDiv;
    }
    else if (options.panel)
    {
        div = options.panel;
    }
    else
    {
        for (var name in sides)
        {
            var panel = sides[name].panels[options.name];
            if (panel)
            {
                div = panel;
                break;
            }
        }
    }
    if (!div)
    {
        div = defaultDiv;
    }
    return div;
}

// adds text to the end of in the panel and scrolls the panel
// options:
//      color: background color for text
//      name: name of panel
//      panel: panel returned from Debug.Add()
function debug(text, options)
{
    options = options || {};
    var div = getDiv(options);
    if (options.color)
    {
        div.style.backgroundColor = options.color === 'error' ? 'red' : options.color;
    }
    else
    {
        div.style.backgroundColor = 'rgba(150,150,150,0.5)';
    }
    var error = false;
    var result = '
';
    if (text === null)
    {
        result += 'null';
    }
    else if (typeof text === 'object')
    {
        for (var i = 0; i < text.length; i++)
        {
            result += text[i] + ((i !== text.length -1) ? ', ' : '');
        }
    }
    else
    {
        result += text;
    }
    result += '
';
    div.innerHTML += result;
    div.scrollTop = div.scrollHeight;
    if (options.color === 'error')
    {
        defaultDiv.expanded = true;
        resize();
    }
}

// replaces all text in the panel
// options:
//      name: name of panel
//      panel: panel returned from Debug.Add()
function debugOne(text, options)
{
    options = options || {};
    var div = getDiv(options);
    if (options.color)
    {
        div.style.backgroundColor = options.color;
    }
    else
    {
        div.style.backgroundColor = 'rgba(150,150,150,0.5)';
    }
    var html = '';
    if (typeof text === 'object')
    {
        for (var i = 0, _i = text.length; i < _i; i++)
        {
            html += text[i] + ((i !== _i -1) ? ', ' : '');
        }
    }
    else
    {
        html += text;
    }
    html += '';
    div.innerHTML = html;
}

// adds a debug message showing who called the function
function caller(options)
{
    if (arguments.callee.caller)
    {
        debug('Called by: ' + arguments.callee.caller.arguments.callee.caller.name + ': ' + arguments.callee.caller.arguments.callee.caller.toString(), options);
    }
    else
    {
        debug('Called by: top level', options);
    }
}

// returns a panel based on its name
function get(name)
{
    for (side in sides)
    {
        if (sides[side].panels[name])
        {
            return sides[side].panels[name];
        }
    }
    return null;
}

function style(div, side)
{
    var s = div.style;
    s.fontFamily = "Helvetica Neue";
    s.position = "fixed";
    s.background = "rgba(150,150,150,0.5)";
    s.color = "white";
    s.margin = 0;
    s.padding = "5px";
    s.boxShadow = (isLeft(side) ? '' : '-') + '5px -5px 10px rgba(0,0,0,0.25)';
    s.cursor = 'pointer';
    s.wordWrap = 'break-word';
    s.overflow = 'auto';
    s.zIndex = 1000;
}

function minimizeCreate(side)
{
    if (side.minimize)
    {
        return;
    }
    var div = document.createElement('div');
    div.options = {};
    document.body.appendChild(div);
    var s = div.style;
    div.side = side;
    if (isLeft(side))
    {
        s.left = 0;
    }
    else
    {
        s.right = 0;
    }
    style(div, side);
    s.backgroundColor = 'transparent';
    s.boxShadow = null;
    s.padding = 0;
    side.minimize = div;
    var minimize = document.createElement('span');
    var count = document.createElement('span');
    minimize.click = handleMinimize;
    count.click = handleCount;
    if (isLeft(side))
    {
        div.appendChild(minimize);
        div.appendChild(count);
        count.style.marginLeft = '20px';
    }
    else
    {
        div.appendChild(count);
        div.appendChild(minimize);
        count.style.marginRight = '20px';
    }
    count.style.background = minimize.style.background = "rgba(150,150,150,0.5)";
    count.style.boxShadow = minimize.style.boxShadow = (isLeft ? '' : '-') + '5px -5px 10px rgba(0,0,0,0.25)';
    count.style.padding = minimize.style.padding = '5px';
    minimize.innerHTML = "—";
    count.style.display = 'none';
    minimize.style
    side.count = count;
    click(side.count, isLeft);
    click(minimize, isLeft);
}

// set click events for panel
function click(div, isLeft)
{
    div.addEventListener('click', div.click);
    div.addEventListener('touchstart', div.click);
    div.style.pointerEvents = 'auto';
    div.isLeft = isLeft;
}

function handleMinimize(e)
{
    var div = e.currentTarget;
    var side = e.currentTarget.offsetParent.side;
    side.isMinimized = !side.isMinimized;
    div.innerHTML = side.isMinimized ? "+" : '—';
    resize();
}

function handleCount(e)
{
    var side = e.currentTarget.offsetParent.side;
    side.minimized.pop();
    resize();
}

function handleClick(e)
{
    var div = e.currentTarget;
    if (div.options.expandable)
    {
        div.expanded = !div.expanded;
    }
    else
    {
        var index = div.side.minimized.indexOf(div);
        if (index === -1)
        {
            div.side.minimized.push(div);
        }
        else
        {
            div.side.minimized.splice(index, 1);
        }
    }
    resize();
}

function resizeSide(side)
{
    if (side.isMinimized)
    {
        for (var name in side.panels)
        {
            var panel = side.panels[name];
            panel.style.display = 'none';
        }
        if (isBottom(side))
        {
            side.minimize.style.bottom = window.innerHeight / 4 + 'px';
        }
        else
        {
            side.minimize.style.top = window.innerHeight / 4 + 'px';
        }
        side.count.style.display = 'none';
    }
    else
    {
        var count = 0;
        var divs = [];
        for (var name in side.panels)
        {
            var panel = side.panels[name];
            if (side.minimized.indexOf(panel) === -1)
            {
                panel.style.display = 'block';
                divs.push(panel);
            }
            else
            {
                panel.style.display = 'none';
                count++;
            }
        }
        divs.push(side.minimize);
        var max = Math.min(window.innerWidth, window.innerHeight);
        var current = 0;
        for (var i = 0; i < divs.length; i++)
        {
            var div = divs[i];
            if (isBottom(side))
            {
                div.style.bottom = current + 'px';
            }
            else
            {
                div.style.top = current + 'px';
            }
            if (div.options.size)
            {
                var size;
                if (div.options.expandable)
                {
                    size = max * (div.expanded ? div.options.expandable : div.options.size);
                }
                else
                {
                    size = max * div.options.size;
                }
                div.style.width = div.style.height = size + 'px';
                div.style.display = 'block';
            }
            div.scrollTop = div.scrollHeight;
            current += 10 + div.offsetHeight;
        }
        if (count === 0)
        {
            side.count.style.display = 'none';
        }
        else
        {
            side.count.style.display = 'inline';
            side.count.innerHTML = count;
        }
    }
}

function resize()
{
    function side(dir)
    {
        if (sides[dir].minimize)
        {
            resizeSide(sides[dir]);
        }
    }
    side('leftBottom');
    side('rightBottom');
    side('leftTop');
    side('rightTop');
}

function isLeft(side)
{
    return side.dir.indexOf('left') !== -1;
}

function isBottom(side)
{
    return side.dir.indexOf('Bottom') !== -1;
}

// Captures ` key to expand default debug box
function keypress(e)
{
    var code = (typeof e.which === "number") ? e.which : e.keyCode;
    if (code === 96)
    {
        handleClick({currentTarget: defaultDiv});
    }
}

function error(e)
{
    console.log(e);
    debug((e.message ? e.message : (e.error && e.error.message ? e.error.message : '')) + " at " + e.filename + " line " + e.lineno, {color: "error"});
}

// exports
var Debug = {
    init: init,
    add: add,
    addMeter: addMeter,
    meter: meter,
    get: get,
    resize: resize,
    caller: caller
};

// add support for AMD (Asynchronous Module Definition) libraries such as require.js.
if (typeof define === 'function' && define.amd)
{
    define(function()
    {
        return {
            Debug: Debug,
            debug: debug,
            debugOne: debugOne
        };
    });
}

// add support for CommonJS libraries such as browserify.
if (typeof exports !== 'undefined')
{
    exports.Debug = Debug;
    exports.debug = debug;
    exports.debugOne = debugOne;
}

// define globally in case AMD is not available or available but not used
if (typeof window !== 'undefined')
{
    window.Debug = Debug;
    window.debug = debug;
    window.debugOne = debugOne;
}<|endoftext|>


<commit_before>
export {default as LandingPage} from './landingPage';

export {default as OurNavbar} from './navbar';
export {default as OurCarousel} from './landingPageFeatured';
export {default as AllArtists} from './artists-all';
export {default as SingleArtist} from './artists-single';
export {default as AllGalleries} from './galleries-all';
export {default as SingleGallery} from './gallery-single';
export {default as GalleryCreate} from './gallery-create';
export {default as GalleryEdit} from './gallery-edit';
export {default as VRCube} from './VRCube';
export {default as VRNightScene} from './VRNightScene';
export {default as CanvasWrapper} from './CanvasWrapper';
export {default as VRWrapper} from './VRWrapper';
export {default as VRHub} from './vrhub';
export {default as SinglePainting} from './singlePainting';
export {default as Signup} from './signup';
export {default as Signin} from './signin';
// export {default as ArtistDashboard} from './artist-dashboard';
export {default as DisplayPaintings} from './display-paintings';
export {default as OurPageHeader} from './display-ourPageHeader';
export {default as OurJumbotron} from './display-ourJumbotron';
// export {default as DisplaySelectFromFS} from './display-selectFromFS';
export {default as DisplaySelectForm} from './display-selectForm';
export {default as PaintingDropdown} from  './display-paintingDropdown';
export {default as GalleryEditPageHeader} from './display-galleryEditPageHeader';
export {default as VRDesert} from './VRDesert';
export {default as VRStarry} from './VRStarry';
export {default as VRArtistHub} from './VRArtistHub';<commit_msg>Update index.js<commit_after>
export {default as LandingPage} from './landingPage';

export {default as OurNavbar} from './navbar';
export {default as OurCarousel} from './landingPageFeatured';
export {default as AllArtists} from './artists-all';
export {default as SingleArtist} from './artists-single';
export {default as AllGalleries} from './galleries-all';
export {default as SingleGallery} from './gallery-single';
export {default as GalleryCreate} from './gallery-create';
export {default as GalleryEdit} from './gallery-edit';
export {default as VRCube} from './VRCube';
export {default as VRNightScene} from './VRNightScene';
export {default as CanvasWrapper} from './CanvasWrapper';
export {default as VRWrapper} from './VRWrapper';
export {default as VRHub} from './vrhub';
export {default as SinglePainting} from './singlePainting';
export {default as Signup} from './signup';
export {default as Signin} from './signin';
export {default as DisplayPaintings} from './display-paintings';
export {default as OurPageHeader} from './display-ourPageHeader';
export {default as OurJumbotron} from './display-ourJumbotron';
// export {default as DisplaySelectFromFS} from './display-selectFromFS';
export {default as DisplaySelectForm} from './display-selectForm';
export {default as PaintingDropdown} from  './display-paintingDropdown';
export {default as GalleryEditPageHeader} from './display-galleryEditPageHeader';
export {default as VRDesert} from './VRDesert';
export {default as VRStarry} from './VRStarry';
export {default as VRArtistHub} from './VRArtistHub';
<|endoftext|>


<commit_before>"use strict";

var
    esPhinx;

(function ($) {

    $.extend({
        prototype: {

            html: function (content) {
                var
                    self = this;

                if (typeof content === "string") {
                    self.each(function (node) {
                        node.innerHTML = content;
                    });
                } else if (content instanceof Node) {
                    self.each(function (node) {
                        node.innerHTML = null;
                        node.appendChild(content);
                    });
                }

                return self;
            },

            rootText: function () {
                var
                    self = this,
                    text = "";

                Enumerator.each(self.first().childNodes, function (v) {
                    if (v.nodeType === Node.TEXT_NODE) {
                        text += v.textContent.trim();
                    }
                });

                return text;
            },

            // text
            //
|

            insertAfter: function(node) {
                var
                    self = this;

                if (node instanceof String) {
                    node = $(node).first();
                }

                if (!node instanceof HTMLElement) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node.nextSibling);

                return self;
            },

            first: function () {
                return this[0];
            },

            parent: function (query) {
                var
                    self = $(this),
                    parent = self.first().parentNode,
                    comparator;

                if (query) {
                    comparator = $(query).first();
                    while (true) {
                        if (parent.isEqualTo(comparator)) {
                            return $(parent);
                        } else if (!parent) {
                            break;
                        }
                        parent = parent.parentNode;
                    }
                } else {
                    return $(self.first().parentNode);
                }

                return $();
            },

            count: function () {
                return Object.keys(this).length;
            }

        }
    });

}(esPhinx));

/*$.prototype.ancestors = function (nodeName) {
        var _parents = []
            ,parent = null
        ;
        collection.forEach(function (e) {
            parent = e.parentNode;
            if (nodeName) {
                if (parent.nodeName.toLowerCase() === nodeName) {
                    _parents.push(parent);
                } else {
                    while(true) {
                        parent = parent.parentNode;
                        if(parent){
                            if(parent.nodeName.toLowerCase() === nodeName) {
                                _parents.push(parent);
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            } else {
                if(parent){
                    _parents.push(parent);
                }
            }
        });
        return _parents;
    }*/<commit_msg>refactor parent method<commit_after>"use strict";

var
    esPhinx;

(function ($) {

    $.extend({
        prototype: {

            parent: function (query) {
                var
                    self = this;

                if (query) {
                    return $(self.first().closest(query));
                } else {
                    return $(self.first().parentNode);
                }

                return $();
            },

            html: function (content) {
                var
                    self = this;

                if (typeof content === "string") {
                    self.each(function (node) {
                        node.innerHTML = content;
                    });
                } else if (content instanceof Node) {
                    self.each(function (node) {
                        node.innerHTML = null;
                        node.appendChild(content);
                    });
                }

                return self;
            },

            rootText: function () {
                var
                    self = this,
                    text = "";

                Enumerator.each(self.first().childNodes, function (v) {
                    if (v.nodeType === Node.TEXT_NODE) {
                        text += v.textContent.trim();
                    }
                });

                return text;
            },

            // text
            //
|

            insertAfter: function(node) {
                var
                    self = this;

                if (node instanceof String) {
                    node = $(node).first();
                }

                if (!node instanceof HTMLElement) {
                    throw new Error("An invalid or illegal node was specified.");
                }

                node.parentNode.insertBefore(self.first(), node.nextSibling);

                return self;
            },

            first: function () {
                return this[0];
            },

            count: function () {
                return Object.keys(this).length;
            }

        }
    });

}(esPhinx));

/*$.prototype.ancestors = function (nodeName) {
        var _parents = []
            ,parent = null
        ;
        collection.forEach(function (e) {
            parent = e.parentNode;
            if (nodeName) {
                if (parent.nodeName.toLowerCase() === nodeName) {
                    _parents.push(parent);
                } else {
                    while(true) {
                        parent = parent.parentNode;
                        if(parent){
                            if(parent.nodeName.toLowerCase() === nodeName) {
                                _parents.push(parent);
                                break;
                            }
                        } else {
                            break;
                        }
                    }
                }
            } else {
                if(parent){
                    _parents.push(parent);
                }
            }
        });
        return _parents;
    }*/<|endoftext|>


<commit_before>// icontains for text matching
$.expr[':'].icontains = function(a, i, m) {
    return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};

$(document).ready(function() {
    // only provide filter form if js is enabled
    $('#js-filter-form').show();
    var listFilter = $('#list-filter');
    var filteredList = $('#filterable-list');
    $(listFilter).change(function() {
        var filterVal = $(this).val();
        if (filterVal) {
            // hide items that don't have matching text, lists that don't have
            // visible items, and blocks that don't have visible lists
            $(filteredList).find('li:not(:icontains(' + filterVal + '))').hide();
            $(filteredList).find('.filter-list:not(:has(li:visible))').hide();
            $(filteredList).find('.filter-block:not(:has(li:visible))').hide();
            // show blocks/lists/items that contain matching text
            $(filteredList).find('.filter-block:has(li:icontains(' + filterVal + '))').show();
            $(filteredList).find('.filter-list:has(li:icontains(' + filterVal + '))').show();
            $(filteredList).find('li:icontains(' + filterVal + ')').show();
        } else {
            // nothing in filter form, so make sure everything is visible
            $(filteredList).find(".filter-block").show();
            $(filteredList).find(".filter-list").show();
            $(filteredList).find("li").show();
        }

        // show 'no results' message if we've removed all the items
        if ($('.filter-list > li:visible').length == 0) {
            $('#no-results').remove();
            $('#js-filter-form').after('
No matching results found.
');
        } else {
            $('#no-results').remove();
        }
        return false;
    }).keyup(function() {
        $(this).change();
    });
});
<commit_msg>more comments, explicit var names in listfilter.js. closes #65<commit_after>// custom jQuery filter selector `icontains` for text matching
// http://answers.oreilly.com/topic/1055-creating-a-custom-filter-selector-with-jquery/
$.expr[':'].icontains = function(element, index, match) {
    return (element.textContent || element.innerText || "").toUpperCase().indexOf(match[3].toUpperCase()) >= 0;
};

$(document).ready(function() {
    // only provide filter form if js is enabled
    $('#js-filter-form').show();
    var listFilter = $('#list-filter');
    var filteredList = $('#filterable-list');

    // after each keystroke in #list-filter input, do a case-insensitive
    // search against all the `li` elements inside #filterable-list
    $(listFilter).change(function() {
        var filterVal = $(this).val();
        if (filterVal) {
            // hide items that don't have matching text, lists that don't have
            // visible items, and blocks that don't have visible lists
            $(filteredList).find('li:not(:icontains(' + filterVal + '))').hide();
            $(filteredList).find('.filter-list:not(:has(li:visible))').hide();
            $(filteredList).find('.filter-block:not(:has(li:visible))').hide();
            // show blocks/lists/items that contain matching text
            $(filteredList).find('.filter-block:has(li:icontains(' + filterVal + '))').show();
            $(filteredList).find('.filter-list:has(li:icontains(' + filterVal + '))').show();
            $(filteredList).find('li:icontains(' + filterVal + ')').show();
        } else {
            // nothing in filter form, so make sure everything is visible
            $(filteredList).find(".filter-block").show();
            $(filteredList).find(".filter-list").show();
            $(filteredList).find("li").show();
        }

        // show 'no results' message if we've removed all the items
        if ($('.filter-list > li:visible').length == 0) {
            $('#no-results').remove();
            $('#js-filter-form').after('
No matching results found.
');
        } else {
            $('#no-results').remove();
        }
        return false;
    }).keyup(function() {
        $(this).change();
    });
});
<|endoftext|>


<commit_before>/**
 * This plugin requires jquery.json.js to be available, or at least the methods $.toJSON and
 * $.parseJSON.
 *
 * The plan is to make use of websockets if they are available, but work just as well with only
 * http if not.
 *
 * Usage example:
 *
 *   var foo = new $.JsonRpcClient({ ajaxUrl: '/backend/jsonrpc' });
 *   foo.call(
 *     'bar', [ 'A parameter', 'B parameter' ],
 *     function(result) { alert('Foo bar answered: ' + result.my_answer); },
 *     function(error)  { console.log('There was an error', error); }
 *   );
 *
 * More examples are available in README.md
 */
(function($) {
  /**
   * @fn new
   * @memberof $.JsonRpcClient
   *
   * @param options An object stating the backends:
   *                ajaxUrl    A url (relative or absolute) to a http(s) backend.
   *                socketUrl  A url (relative of absolute) to a ws(s) backend.
   *                onmessage  A socket message handler for other messages (non-responses).
   *                getSocket  A function returning a WebSocket or null.
   *                           It must take an onmessage_cb and bind it to the onmessage event
   *                           (or chain it before/after some other onmessage handler).
   *                           Or, it could return null if no socket is available.
   *                           The returned instance must have readyState <= 1, and if less than 1,
   *                           react to onopen binding.
   */
  $.JsonRpcClient = function(options) {
    var self = this;
    this.options = $.extend({
      ajaxUrl     : null,
      socketUrl   : null, ///< The ws-url for default getSocket.
      onmessage   : null, ///< Other onmessage-handler.
      getSocket   : function(onmessage_cb) { return self._getSocket(onmessage_cb); }
    }, options);

    // Declare an instance version of the onmessage callback to wrap 'this'.
    this.wsOnMessage = function(event) { self._wsOnMessage(event); };
  };

  /// Holding the WebSocket on default getsocket.
  $.JsonRpcClient.prototype._ws_socket = null;

  /// Object <id>: { success_cb: cb, error_cb: cb }
  $.JsonRpcClient.prototype._ws_callbacks = {};

  /// The next JSON-RPC request id.
  $.JsonRpcClient.prototype._current_id = 1;

  /**
   * @fn call
   * @memberof $.JsonRpcClient
   *
   * @param method     The method to run on JSON-RPC server.
   * @param params     The params; an array or object.
   * @param success_cb A callback for successful request.
   * @param error_cb   A callback for error.
   */
  $.JsonRpcClient.prototype.call = function(method, params, success_cb, error_cb) {
    // Construct the JSON-RPC 2.0 request.
    var request = {
      jsonrpc : '2.0',
      method  : method,
      params  : params,
      id      : this._current_id++  // Increase the id counter to match request/response
    };

    // Try making a WebSocket call.
    var socket = this.options.getSocket(this.wsOnMessage);
    if (socket !== null) {
      this._wsCall(socket, request, success_cb, error_cb);
      return;
    }

    // No WebSocket, and no HTTP backend?  This won't work.
    if (this.options.ajaxUrl === null) {
      throw "$.JsonRpcClient.call used with no websocket and no http endpoint.";
    }

    $.ajax({
      type     : 'POST',
      url      : this.options.ajaxUrl,
      data     : $.toJSON(request),
      dataType : 'json',
      cache    : false,

      success  : function(data) {
        if ('error' in data) error_cb(data.error);
        success_cb(data.result);
      },

      // JSON-RPC Server could return non-200 on error
      error    : function(jqXHR, textStatus, errorThrown) {
        try {
          var response = $.parseJSON(jqXHR.responseText);
          if ('console' in window) console.log(response);
          error_cb(response.error);
        }
        catch (err) {
          // Perhaps the responseText wasn't really a jsonrpc-error.
          error_cb({ error: jqXHR.responseText });
        }
      }
    });
  };

  /**
   * Notify sends a command to the server that won't need a response.  In http, there is probably
   * an empty response - that will be dropped, but in ws there should be no response at all.
   *
   * This is very similar to call, but has no id and no handling of callbacks.
   *
   * @fn notify
   * @memberof $.JsonRpcClient
   *
   * @param method     The method to run on JSON-RPC server.
   * @param params     The params; an array or object.
   */
  $.JsonRpcClient.prototype.notify = function(method, params) {
    // Construct the JSON-RPC 2.0 request.
    var request = {
      jsonrpc: '2.0',
      method:  method,
      params:  params
    };

    // Try making a WebSocket call.
    var socket = this.options.getSocket(this.wsOnMessage);
    if (socket !== null) {
      this._wsCall(socket, request);
      return;
    }

    // No WebSocket, and no HTTP backend?  This won't work.
    if (this.options.ajaxUrl === null) {
      throw "$.JsonRpcClient.notify used with no websocket and no http endpoint.";
    }

    $.ajax({
      type     : 'POST',
      url      : this.options.ajaxUrl,
      data     : $.toJSON(request),
      dataType : 'json',
      cache    : false
    });
  };

  /**
   * Make a batch-call by using a callback.
   *
   * The callback will get an object "batch" as only argument.  On batch, you can call the methods
   * "call" and "notify" just as if it was a normal $.JsonRpcClient object, and all calls will be
   * sent as a batch call then the callback is done.
   *
   * @fn batch
   * @memberof $.JsonRpcClient
   *
   * @param callback    The main function which will get a batch handler to run call and notify on.
   * @param all_done_cb A callback function to call after all results have been handled.
   * @param error_cb    A callback function to call if there is an error from the server.
   *                    Note, that batch calls should always get an overall success, and the
   *                    only error
   */
  $.JsonRpcClient.prototype.batch = function(callback, all_done_cb, error_cb) {
    var batch = new $.JsonRpcClient._batchObject(this, all_done_cb, error_cb);
    callback(batch);
    batch._execute();
  };

  /**
   * The default getSocket handler.
   *
   * @param onmessage_cb The callback to be bound to onmessage events on the socket.
   *
   * @fn _getSocket
   * @memberof $.JsonRpcClient
   */
  $.JsonRpcClient.prototype._getSocket = function(onmessage_cb) {
    // If there is no ws url set, we don't have a socket.
    // Likewise, if there is no window.WebSocket.
    if (this.options.socketUrl === null || !("WebSocket" in window)) return null;

    if (this._ws_socket === null || this._ws_socket.readyState > 1) {
      // No socket, or dying socket, let's get a new one.
      this._ws_socket = new WebSocket(this.options.socketUrl);

      // Set up onmessage handler.
      this._ws_socket.onmessage = onmessage_cb;
    }

    return this._ws_socket;
  };

  /**
   * Internal handler to dispatch a JRON-RPC request through a websocket.
   *
   * @fn _wsCall
   * @memberof $.JsonRpcClient
   */
  $.JsonRpcClient.prototype._wsCall = function(socket, request, success_cb, error_cb) {
    var request_json = $.toJSON(request);

    if (socket.readyState < 1) {
      // The websocket is not open yet; we have to set sending of the message in onopen.
      self = this; // In closure below, this is set to the WebSocket.  Use self instead.

      // Set up sending of message for when the socket is open.
      socket.onopen = function() {
        // Send the request.
        socket.send(request_json);
      };
    }
    else {
      // We have a socket and it should be ready to send on.
      socket.send(request_json);
    }

    // Setup callbacks.  If there is an id, this is a call and not a notify.
    if ('id' in request && typeof success_cb !== 'undefined') {
      this._ws_callbacks[request.id] = { success_cb: success_cb, error_cb: error_cb };
    }
  };

  /**
   * Internal handler for the websocket messages.  It determines if the message is a JSON-RPC
   * response, and if so, tries to couple it with a given callback.  Otherwise, it falls back to
   * given external onmessage-handler, if any.
   *
   * @param event The websocket onmessage-event.
   */
  $.JsonRpcClient.prototype._wsOnMessage = function(event) {
    // Check if this could be a JSON RPC message.
    try {
      var response = $.parseJSON(event.data);

      /// @todo Make using the jsonrcp 2.0 check optional, to use this on JSON-RPC 1 backends.

      if (typeof response === 'object'
          && 'jsonrpc' in response
          && response.jsonrpc === '2.0') {

        /// @todo Handle bad response (without id).

        // If this is an object with result, it is a response.
        if ('result' in response && this._ws_callbacks[response.id]) {
          // Get the success callback.
          var success_cb = this._ws_callbacks[response.id].success_cb;

          // Delete the callback from the storage.
          delete this._ws_callbacks[response.id];

          // Run callback with result as parameter.
          success_cb(response.result);
          return;
        }

        // If this is an object with error, it is an error response.
        else if ('error' in response && this._ws_callbacks[response.id]) {
          // Get the error callback.
          var error_cb = this._ws_callbacks[response.id].error_cb;

          // Delete the callback from the storage.
          delete this._ws_callbacks[response.id];

          // Run callback with the error object as parameter.
          error_cb(response.error);
          return;
        }
      }
    }
    catch (err) {
      // Probably an error while parsing a non json-string as json.  All real JSON-RPC cases are
      // handled above, and the fallback method is called below.
    }

    // This is not a JSON-RPC response.  Call the fallback message handler, if given.
    if (typeof this.options.onmessage === 'function') {
      this.options.onmessage(event);
    }
  };

  /************************************************************************************************
   * Batch object with methods
   ************************************************************************************************/

  /**
   * Handling object for batch calls.
   */
  $.JsonRpcClient._batchObject = function(jsonrpcclient, all_done_cb, error_cb) {
    // Array of objects to hold the call and notify requests.  Each objects will have the request
    // object, and unless it is a notify, success_cb and error_cb.
    this._requests   = [];

    this.jsonrpcclient = jsonrpcclient;
    this.all_done_cb = all_done_cb;
    this.error_cb    = typeof error_cb === 'function' ? error_cb : function() {};

  };

  /**
   * @sa $.JsonRpcClient.prototype.call
   */
  $.JsonRpcClient._batchObject.prototype.call = function(method, params, success_cb, error_cb) {
    this._requests.push({
      request    : {
        jsonrpc : '2.0',
        method  : method,
        params  : params,
        id      : this.jsonrpcclient._current_id++  // Use the client's id series.
      },
      success_cb : success_cb,
      error_cb   : error_cb
    });
  };

  /**
   * @sa $.JsonRpcClient.prototype.notify
   */
  $.JsonRpcClient._batchObject.prototype.notify = function(method, params) {
    this._requests.push({
      request    : {
        jsonrpc : '2.0',
        method  : method,
        params  : params
      }
    });
  };

  /**
   * Executes the batched up calls.
   */
  $.JsonRpcClient._batchObject.prototype._execute = function() {
    var self = this;

    if (this._requests.length === 0) return; // All done :P

    // Collect all request data and sort handlers by request id.
    var batch_request = [];
    var handlers = {};

    // If we have a WebSocket, just send the requests individually like normal calls.
    var socket = self.jsonrpcclient.options.getSocket(self.jsonrpcclient.wsOnMessage);
    if (socket !== null) {
      for (var i = 0; i < this._requests.length; i++) {
        var call = this._requests[i];
        var success_cb = ('success_cb' in call) ? call.success_cb : undefined;
        var error_cb   = ('error_cb'   in call) ? call.error_cb   : undefined;
        this._wsCall(socket, call.request, success_cb, error_cb);
      }
      if (typeof all_done_cb === 'function') all_done_cb(result);
      return;
    }

    for (var i = 0; i < this._requests.length; i++) {
      var call = this._requests[i];
      batch_request.push(call.request);

      // If the request has an id, it should handle returns (otherwise it's a notify).
      if ('id' in call.request) {
        handlers[call.request.id] = {
          success_cb : call.success_cb,
          error_cb   : call.error_cb
        };
      }
    }

    var success_cb = function(data) { self._batchCb(data, handlers, self.all_done_cb); };

    // No WebSocket, and no HTTP backend?  This won't work.
    if (self.jsonrpcclient.options.ajaxUrl === null) {
      throw "$.JsonRpcClient.batch used with no websocket and no http endpoint.";
    }

    // Send request
    $.ajax({
      url      : self.jsonrpcclient.options.ajaxUrl,
      data     : $.toJSON(batch_request),
      dataType : 'json',
      cache    : false,
      type     : 'POST',

      // Batch-requests should always return 200
      error    : function(jqXHR, textStatus, errorThrown) {
        self.error_cb(jqXHR, textStatus, errorThrown);
      },
      success  : success_cb
    });
  };

  /**
   * Internal helper to match the result array from a batch call to their respective callbacks.
   *
   * @fn _batchCb
   * @memberof $.JsonRpcClient
   */
  $.JsonRpcClient._batchObject.prototype._batchCb = function(result, handlers, all_done_cb) {
    for (var i = 0; i < result.length; i++) {
      var response = result[i];

      // Handle error
      if ('error' in response) {
        if (response.id === null || !(response.id in handlers)) {
          // An error on a notify?  Just log it to the console.
          if ('console' in window) console.log(response);
        }
        else handlers[response.id].error_cb(response.error);
      }
      else {
        // Here we should always have a correct id and no error.
        if (!(response.id in handlers) && 'console' in window) console.log(response);
        else handlers[response.id].success_cb(response.result);
      }
    }

    if (typeof all_done_cb === 'function') all_done_cb(result);
  };

})(jQuery);
<commit_msg>Adds onopen and onclose as options<commit_after>/**
 * This plugin requires jquery.json.js to be available, or at least the methods $.toJSON and
 * $.parseJSON.
 *
 * The plan is to make use of websockets if they are available, but work just as well with only
 * http if not.
 *
 * Usage example:
 *
 *   var foo = new $.JsonRpcClient({ ajaxUrl: '/backend/jsonrpc' });
 *   foo.call(
 *     'bar', [ 'A parameter', 'B parameter' ],
 *     function(result) { alert('Foo bar answered: ' + result.my_answer); },
 *     function(error)  { console.log('There was an error', error); }
 *   );
 *
 * More examples are available in README.md
 */
(function($) {
  /**
   * @fn new
   * @memberof $.JsonRpcClient
   *
   * @param options An object stating the backends:
   *                ajaxUrl    A url (relative or absolute) to a http(s) backend.
   *                socketUrl  A url (relative of absolute) to a ws(s) backend.
   *                onmessage  A socket message handler for other messages (non-responses).
   *                onopen     A socket onopen handler. (Not used for custom getSocket.)
   *                onclose    A socket onclose handler. (Not used for custom getSocket.)
   *                getSocket  A function returning a WebSocket or null.
   *                           It must take an onmessage_cb and bind it to the onmessage event
   *                           (or chain it before/after some other onmessage handler).
   *                           Or, it could return null if no socket is available.
   *                           The returned instance must have readyState <= 1, and if less than 1,
   *                           react to onopen binding.
   */
  $.JsonRpcClient = function(options) {
    var self = this;
    this.options = $.extend({
      ajaxUrl     : null,
      socketUrl   : null, ///< WebSocket URL. (Not used if a custom getSocket is supplied.)
      onmessage   : null, ///< Optional onmessage-handler for WebSocket.
      onopen      : null, ///< Optional onopen-handler for WebSocket.
      onclose     : null, ///< Optional onclose-handler for WebSocket.
      getSocket   : self._getSocket ///< Custom socket supplier for using an already existing socket
    }, options);

    // Declare an instance version of the onmessage callback to wrap 'this'.
    this.wsOnMessage = function(event) { self._wsOnMessage(event); };
  };

  /// Holding the WebSocket on default getsocket.
  $.JsonRpcClient.prototype._ws_socket = null;

  /// Object <id>: { success_cb: cb, error_cb: cb }
  $.JsonRpcClient.prototype._ws_callbacks = {};

  /// The next JSON-RPC request id.
  $.JsonRpcClient.prototype._current_id = 1;

  /**
   * @fn call
   * @memberof $.JsonRpcClient
   *
   * @param method     The method to run on JSON-RPC server.
   * @param params     The params; an array or object.
   * @param success_cb A callback for successful request.
   * @param error_cb   A callback for error.
   */
  $.JsonRpcClient.prototype.call = function(method, params, success_cb, error_cb) {
    // Construct the JSON-RPC 2.0 request.
    var request = {
      jsonrpc : '2.0',
      method  : method,
      params  : params,
      id      : this._current_id++  // Increase the id counter to match request/response
    };

    // Try making a WebSocket call.
    var socket = this.options.getSocket(this.wsOnMessage);
    if (socket !== null) {
      this._wsCall(socket, request, success_cb, error_cb);
      return;
    }

    // No WebSocket, and no HTTP backend?  This won't work.
    if (this.options.ajaxUrl === null) {
      throw "$.JsonRpcClient.call used with no websocket and no http endpoint.";
    }

    $.ajax({
      type     : 'POST',
      url      : this.options.ajaxUrl,
      data     : $.toJSON(request),
      dataType : 'json',
      cache    : false,

      success  : function(data) {
        if ('error' in data) error_cb(data.error);
        success_cb(data.result);
      },

      // JSON-RPC Server could return non-200 on error
      error    : function(jqXHR, textStatus, errorThrown) {
        try {
          var response = $.parseJSON(jqXHR.responseText);
          if ('console' in window) console.log(response);
          error_cb(response.error);
        }
        catch (err) {
          // Perhaps the responseText wasn't really a jsonrpc-error.
          error_cb({ error: jqXHR.responseText });
        }
      }
    });
  };

  /**
   * Notify sends a command to the server that won't need a response.  In http, there is probably
   * an empty response - that will be dropped, but in ws there should be no response at all.
   *
   * This is very similar to call, but has no id and no handling of callbacks.
   *
   * @fn notify
   * @memberof $.JsonRpcClient
   *
   * @param method     The method to run on JSON-RPC server.
   * @param params     The params; an array or object.
   */
  $.JsonRpcClient.prototype.notify = function(method, params) {
    // Construct the JSON-RPC 2.0 request.
    var request = {
      jsonrpc: '2.0',
      method:  method,
      params:  params
    };

    // Try making a WebSocket call.
    var socket = this.options.getSocket(this.wsOnMessage);
    if (socket !== null) {
      this._wsCall(socket, request);
      return;
    }

    // No WebSocket, and no HTTP backend?  This won't work.
    if (this.options.ajaxUrl === null) {
      throw "$.JsonRpcClient.notify used with no websocket and no http endpoint.";
    }

    $.ajax({
      type     : 'POST',
      url      : this.options.ajaxUrl,
      data     : $.toJSON(request),
      dataType : 'json',
      cache    : false
    });
  };

  /**
   * Make a batch-call by using a callback.
   *
   * The callback will get an object "batch" as only argument.  On batch, you can call the methods
   * "call" and "notify" just as if it was a normal $.JsonRpcClient object, and all calls will be
   * sent as a batch call then the callback is done.
   *
   * @fn batch
   * @memberof $.JsonRpcClient
   *
   * @param callback    The main function which will get a batch handler to run call and notify on.
   * @param all_done_cb A callback function to call after all results have been handled.
   * @param error_cb    A callback function to call if there is an error from the server.
   *                    Note, that batch calls should always get an overall success, and the
   *                    only error
   */
  $.JsonRpcClient.prototype.batch = function(callback, all_done_cb, error_cb) {
    var batch = new $.JsonRpcClient._batchObject(this, all_done_cb, error_cb);
    callback(batch);
    batch._execute();
  };

  /**
   * The default getSocket handler.
   *
   * @param onmessage_cb The callback to be bound to onmessage events on the socket.
   *
   * @fn _getSocket
   * @memberof $.JsonRpcClient
   */
  $.JsonRpcClient.prototype._getSocket = function(onmessage_cb) {
    // If there is no ws url set, we don't have a socket.
    // Likewise, if there is no window.WebSocket.
    if (this.options.socketUrl === null || !("WebSocket" in window)) return null;

    if (this._ws_socket === null || this._ws_socket.readyState > 1) {
      // No socket, or dying socket, let's get a new one.
      this._ws_socket = new WebSocket(this.options.socketUrl);

      // Set up onmessage handler.
      this._ws_socket.onmessage = onmessage_cb;

      // Set up onclose handler.
      if (typeof this.options.onclose === "function") {
        this._ws_socket.onclose = this.options.onclose;
      }
    }

    return this._ws_socket;
  };

  /**
   * Internal handler to dispatch a JRON-RPC request through a websocket.
   *
   * @fn _wsCall
   * @memberof $.JsonRpcClient
   */
  $.JsonRpcClient.prototype._wsCall = function(socket, request, success_cb, error_cb) {
    var request_json = $.toJSON(request);

    if (socket.readyState < 1) {
      // The websocket is not open yet; we have to set sending of the message in onopen.
      self = this; // In closure below, this is set to the WebSocket.  Use self instead.

      // Set up sending of message for when the socket is open.
      socket.onopen = function(event) {
        // Hook for extra onopen callback
        if (typeof self.options.onopen === "function") {
          self.options.onopen(event);
        }
        // Send the request.
        socket.send(request_json);
      };
    }
    else {
      // We have a socket and it should be ready to send on.
      socket.send(request_json);
    }

    // Setup callbacks.  If there is an id, this is a call and not a notify.
    if ('id' in request && typeof success_cb !== 'undefined') {
      this._ws_callbacks[request.id] = { success_cb: success_cb, error_cb: error_cb };
    }
  };

  /**
   * Internal handler for the websocket messages.  It determines if the message is a JSON-RPC
   * response, and if so, tries to couple it with a given callback.  Otherwise, it falls back to
   * given external onmessage-handler, if any.
   *
   * @param event The websocket onmessage-event.
   */
  $.JsonRpcClient.prototype._wsOnMessage = function(event) {
    // Check if this could be a JSON RPC message.
    try {
      var response = $.parseJSON(event.data);

      /// @todo Make using the jsonrcp 2.0 check optional, to use this on JSON-RPC 1 backends.

      if (typeof response === 'object'
          && 'jsonrpc' in response
          && response.jsonrpc === '2.0') {

        /// @todo Handle bad response (without id).

        // If this is an object with result, it is a response.
        if ('result' in response && this._ws_callbacks[response.id]) {
          // Get the success callback.
          var success_cb = this._ws_callbacks[response.id].success_cb;

          // Delete the callback from the storage.
          delete this._ws_callbacks[response.id];

          // Run callback with result as parameter.
          success_cb(response.result);
          return;
        }

        // If this is an object with error, it is an error response.
        else if ('error' in response && this._ws_callbacks[response.id]) {
          // Get the error callback.
          var error_cb = this._ws_callbacks[response.id].error_cb;

          // Delete the callback from the storage.
          delete this._ws_callbacks[response.id];

          // Run callback with the error object as parameter.
          error_cb(response.error);
          return;
        }
      }
    }
    catch (err) {
      // Probably an error while parsing a non json-string as json.  All real JSON-RPC cases are
      // handled above, and the fallback method is called below.
    }

    // This is not a JSON-RPC response.  Call the fallback message handler, if given.
    if (typeof this.options.onmessage === 'function') {
      this.options.onmessage(event);
    }
  };

  /************************************************************************************************
   * Batch object with methods
   ************************************************************************************************/

  /**
   * Handling object for batch calls.
   */
  $.JsonRpcClient._batchObject = function(jsonrpcclient, all_done_cb, error_cb) {
    // Array of objects to hold the call and notify requests.  Each objects will have the request
    // object, and unless it is a notify, success_cb and error_cb.
    this._requests   = [];

    this.jsonrpcclient = jsonrpcclient;
    this.all_done_cb = all_done_cb;
    this.error_cb    = typeof error_cb === 'function' ? error_cb : function() {};

  };

  /**
   * @sa $.JsonRpcClient.prototype.call
   */
  $.JsonRpcClient._batchObject.prototype.call = function(method, params, success_cb, error_cb) {
    this._requests.push({
      request    : {
        jsonrpc : '2.0',
        method  : method,
        params  : params,
        id      : this.jsonrpcclient._current_id++  // Use the client's id series.
      },
      success_cb : success_cb,
      error_cb   : error_cb
    });
  };

  /**
   * @sa $.JsonRpcClient.prototype.notify
   */
  $.JsonRpcClient._batchObject.prototype.notify = function(method, params) {
    this._requests.push({
      request    : {
        jsonrpc : '2.0',
        method  : method,
        params  : params
      }
    });
  };

  /**
   * Executes the batched up calls.
   */
  $.JsonRpcClient._batchObject.prototype._execute = function() {
    var self = this;

    if (this._requests.length === 0) return; // All done :P

    // Collect all request data and sort handlers by request id.
    var batch_request = [];
    var handlers = {};

    // If we have a WebSocket, just send the requests individually like normal calls.
    var socket = self.jsonrpcclient.options.getSocket(self.jsonrpcclient.wsOnMessage);
    if (socket !== null) {
      for (var i = 0; i < this._requests.length; i++) {
        var call = this._requests[i];
        var success_cb = ('success_cb' in call) ? call.success_cb : undefined;
        var error_cb   = ('error_cb'   in call) ? call.error_cb   : undefined;
        this._wsCall(socket, call.request, success_cb, error_cb);
      }
      if (typeof all_done_cb === 'function') all_done_cb(result);
      return;
    }

    for (var i = 0; i < this._requests.length; i++) {
      var call = this._requests[i];
      batch_request.push(call.request);

      // If the request has an id, it should handle returns (otherwise it's a notify).
      if ('id' in call.request) {
        handlers[call.request.id] = {
          success_cb : call.success_cb,
          error_cb   : call.error_cb
        };
      }
    }

    var success_cb = function(data) { self._batchCb(data, handlers, self.all_done_cb); };

    // No WebSocket, and no HTTP backend?  This won't work.
    if (self.jsonrpcclient.options.ajaxUrl === null) {
      throw "$.JsonRpcClient.batch used with no websocket and no http endpoint.";
    }

    // Send request
    $.ajax({
      url      : self.jsonrpcclient.options.ajaxUrl,
      data     : $.toJSON(batch_request),
      dataType : 'json',
      cache    : false,
      type     : 'POST',

      // Batch-requests should always return 200
      error    : function(jqXHR, textStatus, errorThrown) {
        self.error_cb(jqXHR, textStatus, errorThrown);
      },
      success  : success_cb
    });
  };

  /**
   * Internal helper to match the result array from a batch call to their respective callbacks.
   *
   * @fn _batchCb
   * @memberof $.JsonRpcClient
   */
  $.JsonRpcClient._batchObject.prototype._batchCb = function(result, handlers, all_done_cb) {
    for (var i = 0; i < result.length; i++) {
      var response = result[i];

      // Handle error
      if ('error' in response) {
        if (response.id === null || !(response.id in handlers)) {
          // An error on a notify?  Just log it to the console.
          if ('console' in window) console.log(response);
        }
        else handlers[response.id].error_cb(response.error);
      }
      else {
        // Here we should always have a correct id and no error.
        if (!(response.id in handlers) && 'console' in window) console.log(response);
        else handlers[response.id].success_cb(response.result);
      }
    }

    if (typeof all_done_cb === 'function') all_done_cb(result);
  };

})(jQuery);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  Button,
  Container,
  Divider,
  Grid,
  Header,
  Image,
  List,
  Menu,
  Segment,
  Visibility,
  Icon,
  Table,
  Form
} from 'semantic-ui-react';
import { Link, Redirect } from 'react-router-dom';
import FixedMenu from './fixedMenu';
import logo from './logo.png';
import { clientList } from './clientList';

class ClientIntakePage extends Component {

  state = {
    redirect: false,
    name: '',
    lastVisit: '',
    clientId: '',
    image: 'http://react.semantic-ui.com/assets/images/avatar/large/jenny.jpg',
    dob: '',
    zipCode: '',
    visits: [],
  };

  hideFixedMenu = () => this.setState({ visible: false })
  showFixedMenu = () => this.setState({ visible: true })

  handleInputChange = (e, { name, value }) => this.setState({ [name]: value })

  handleFormSubmit = e => {
    alert('Placeholder. Will save the client and take you to the client detail page')
    this.setState({redirect:true});
    // Take the current state and create a new client in the database
  }

  render() {
    const { visible } = this.state

    return (

        { visible ? <FixedMenu /> : null }
        {this.state.redirect ? (<Redirect to='/detail/54321'/>) : false}

        <Visibility
          onBottomPassed={this.showFixedMenu}
          onBottomVisible={this.hideFixedMenu}
          once={false}
        >
          <Segment
            inverted
            textAlign='center'
            style={{ padding: '1em 0em' }}
            vertical
            color='teal'
          >
            <Container>
              <Menu inverted secondary size='large'>
                <Menu.Item>
                  <Link to="/"><Image src={logo} size='tiny' /></Link>
                </Menu.Item>
                <Menu.Item><Link to="/">Home</Link></Menu.Item>
                <Menu.Item><Link to="/about">About</Link></Menu.Item>
                <Menu.Item active><Link to="/intake">New Client Intake</Link></Menu.Item>
                <Menu.Item position='right'>
                  {/*<Link to="/login"><Button inverted>Log in</Button></Link>*/}
                  {/*<Button as='a' inverted style={{ marginLeft: '0.5em' }}>Sign Up</Button>*/}
                </Menu.Item>
              </Menu>
            </Container>
          </Segment>
        </Visibility>

        <Segment style={{ padding: '4em 0em' }} vertical>
          New Client Intake
          <Grid container stackable verticalAlign='middle'>
            <Grid.Row>
              <Grid.Column width={4}>
                <Image src={this.state.image} size='medium'/>
              </Grid.Column>
              <Grid.Column floated='right' width={12}>
                <Form onSubmit={this.handleFormSubmit}>
                  <Form.Input label='Name' placeholder='First name and last initial' name='newname' value={this.state.name} onChange={this.handleInputChange} />
                  <Form.Input label='Date of Birth' placeholder='Date of Birth' name='dob' value={this.state.dob} onChange={this.handleInputChange}  />
                  <Form.Input label='Zip Code' placeholder='Zip Code' name='zipCode' value={this.state.zipCode} onChange={this.handleInputChange}  />
                  <Form.Input label='Client Avatar URL' placeholder='Avatar URL' name='image' value={this.state.image} onChange={this.handleInputChange}  />
                  <Form.Button color='teal'>Submit</Form.Button>
                </Form>
              </Grid.Column>
            </Grid.Row>
            <Divider/>
          </Grid>
        </Segment>

        <Segment inverted vertical style={{ padding: '5em 0em' }} color='teal'>
          <Container>
            <Grid divided inverted stackable>
              <Grid.Row>
                <Grid.Column width={3}>

                  <List link inverted>
                    <List.Item as='a'>Sitemap</List.Item>
                    <List.Item as='a'>Contact Us</List.Item>
                  </List>
                </Grid.Column>
                <Grid.Column width={3}>

                  <List link inverted>
                    <List.Item as='a'>Choice 1</List.Item>
                    <List.Item as='a'>Choice 2</List.Item>
                    <List.Item as='a'>Choice 3</List.Item>
                    <List.Item as='a'>Choice 4</List.Item>
                  </List>
                </Grid.Column>
                <Grid.Column width={7}>
                  Cliff Effects Tool

Made with <Icon name='heart' size='small' /> by Code for Boston

                </Grid.Column>
              </Grid.Row>
            </Grid>
          </Container>
        </Segment>

    )
  }
}

export default ClientIntakePage;<commit_msg>Removes new client intake alert. Issue #9, item 4.<commit_after>import React, { Component } from 'react';
import {
  Button,
  Container,
  Divider,
  Grid,
  Header,
  Image,
  List,
  Menu,
  Segment,
  Visibility,
  Icon,
  Table,
  Form
} from 'semantic-ui-react';
import { Link, Redirect } from 'react-router-dom';
import FixedMenu from './fixedMenu';
import logo from './logo.png';
import { clientList } from './clientList';

class ClientIntakePage extends Component {

  state = {
    redirect: false,
    name: '',
    lastVisit: '',
    clientId: '',
    image: 'http://react.semantic-ui.com/assets/images/avatar/large/jenny.jpg',
    dob: '',
    zipCode: '',
    visits: [],
  };

  hideFixedMenu = () => this.setState({ visible: false })
  showFixedMenu = () => this.setState({ visible: true })

  handleInputChange = (e, { name, value }) => this.setState({ [name]: value })

  handleFormSubmit = e => {
    // alert('Placeholder. Will save the client and take you to the client detail page')
    this.setState({redirect:true});
    // Take the current state and create a new client in the database
  }

  render() {
    const { visible } = this.state

    return (

        { visible ? <FixedMenu /> : null }
        {this.state.redirect ? (<Redirect to='/detail/54321'/>) : false}

        <Visibility
          onBottomPassed={this.showFixedMenu}
          onBottomVisible={this.hideFixedMenu}
          once={false}
        >
          <Segment
            inverted
            textAlign='center'
            style={{ padding: '1em 0em' }}
            vertical
            color='teal'
          >
            <Container>
              <Menu inverted secondary size='large'>
                <Menu.Item>
                  <Link to="/"><Image src={logo} size='tiny' /></Link>
                </Menu.Item>
                <Menu.Item><Link to="/">Home</Link></Menu.Item>
                <Menu.Item><Link to="/about">About</Link></Menu.Item>
                <Menu.Item active><Link to="/intake">New Client Intake</Link></Menu.Item>
                <Menu.Item position='right'>
                  {/*<Link to="/login"><Button inverted>Log in</Button></Link>*/}
                  {/*<Button as='a' inverted style={{ marginLeft: '0.5em' }}>Sign Up</Button>*/}
                </Menu.Item>
              </Menu>
            </Container>
          </Segment>
        </Visibility>

        <Segment style={{ padding: '4em 0em' }} vertical>
          New Client Intake
          <Grid container stackable verticalAlign='middle'>
            <Grid.Row>
              <Grid.Column width={4}>
                <Image src={this.state.image} size='medium'/>
              </Grid.Column>
              <Grid.Column floated='right' width={12}>
                <Form onSubmit={this.handleFormSubmit}>
                  <Form.Input label='Name' placeholder='First name and last initial' name='newname' value={this.state.name} onChange={this.handleInputChange} />
                  <Form.Input label='Date of Birth' placeholder='Date of Birth' name='dob' value={this.state.dob} onChange={this.handleInputChange}  />
                  <Form.Input label='Zip Code' placeholder='Zip Code' name='zipCode' value={this.state.zipCode} onChange={this.handleInputChange}  />
                  <Form.Input label='Client Avatar URL' placeholder='Avatar URL' name='image' value={this.state.image} onChange={this.handleInputChange}  />
                  <Form.Button color='teal'>Submit</Form.Button>
                </Form>
              </Grid.Column>
            </Grid.Row>
            <Divider/>
          </Grid>
        </Segment>

        <Segment inverted vertical style={{ padding: '5em 0em' }} color='teal'>
          <Container>
            <Grid divided inverted stackable>
              <Grid.Row>
                <Grid.Column width={3}>

                  <List link inverted>
                    <List.Item as='a'>Sitemap</List.Item>
                    <List.Item as='a'>Contact Us</List.Item>
                  </List>
                </Grid.Column>
                <Grid.Column width={3}>

                  <List link inverted>
                    <List.Item as='a'>Choice 1</List.Item>
                    <List.Item as='a'>Choice 2</List.Item>
                    <List.Item as='a'>Choice 3</List.Item>
                    <List.Item as='a'>Choice 4</List.Item>
                  </List>
                </Grid.Column>
                <Grid.Column width={7}>
                  Cliff Effects Tool

Made with <Icon name='heart' size='small' /> by Code for Boston

                </Grid.Column>
              </Grid.Row>
            </Grid>
          </Container>
        </Segment>

    )
  }
}

export default ClientIntakePage;<|endoftext|>