<commit_before>/**
 * dat-gui JavaScript Controller Library
 * http://code.google.com/p/dat-gui
 *
 * Copyright 2011 Data Arts Team, Google Creative Lab
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 */

import Controller from './Controller';
import dom from '../dom/dom';
import Color from '../color/Color';
import interpret from '../color/interpret';
import common from '../utils/common';

class ColorController extends Controller {
  constructor(object, property) {
    super(object, property);

    this.__color = new Color(this.getValue());
    this.__temp = new Color(0);

    const _this = this;

    this.domElement = document.createElement('div');

    dom.makeSelectable(this.domElement, false);

    this.__selector = document.createElement('div');
    this.__selector.className = 'selector';

    this.__saturation_field = document.createElement('div');
    this.__saturation_field.className = 'saturation-field';

    this.__field_knob = document.createElement('div');
    this.__field_knob.className = 'field-knob';
    this.__field_knob_border = '2px solid ';

    this.__hue_knob = document.createElement('div');
    this.__hue_knob.className = 'hue-knob';

    this.__hue_field = document.createElement('div');
    this.__hue_field.className = 'hue-field';

    this.__input = document.createElement('input');
    this.__input.type = 'text';
    this.__input_textShadow = '0 1px 1px ';

    dom.bind(this.__input, 'keydown', function(e) {
      if (e.keyCode === 13) { // on enter
        onBlur.call(this);
      }
    });

    dom.bind(this.__input, 'blur', onBlur);

    dom.bind(this.__selector, 'mousedown', function(/* e */) {
      dom
        .addClass(this, 'drag')
        .bind(window, 'mouseup', function(/* e */) {
          dom.removeClass(_this.__selector, 'drag');
        });
    });

    const valueField = document.createElement('div');

    common.extend(this.__selector.style, {
      width: '122px',
      height: '102px',
      padding: '3px',
      backgroundColor: '#222',
      boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
    });

    common.extend(this.__field_knob.style, {
      position: 'absolute',
      width: '12px',
      height: '12px',
      border: this.__field_knob_border + (this.__color.v < 0.5 ? '#fff' : '#000'),
      boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
      borderRadius: '12px',
      zIndex: 1
    });

    common.extend(this.__hue_knob.style, {
      position: 'absolute',
      width: '15px',
      height: '2px',
      borderRight: '4px solid #fff',
      zIndex: 1
    });

    common.extend(this.__saturation_field.style, {
      width: '100px',
      height: '100px',
      border: '1px solid #555',
      marginRight: '3px',
      display: 'inline-block',
      cursor: 'pointer'
    });

    common.extend(valueField.style, {
      width: '100%',
      height: '100%',
      background: 'none'
    });

    linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');

    common.extend(this.__hue_field.style, {
      width: '15px',
      height: '100px',
      border: '1px solid #555',
      cursor: 'ns-resize',
      position: 'absolute',
      top: '3px',
      right: '3px'
    });

    hueGradient(this.__hue_field);

    common.extend(this.__input.style, {
      outline: 'none',
//      width: '120px',
      textAlign: 'center',
//      padding: '4px',
//      marginBottom: '6px',
      color: '#fff',
      border: 0,
      fontWeight: 'bold',
      textShadow: this.__input_textShadow + 'rgba(0,0,0,0.7)'
    });

    dom.bind(this.__saturation_field, 'mousedown', fieldDown);
    dom.bind(this.__field_knob, 'mousedown', fieldDown);

    dom.bind(this.__hue_field, 'mousedown', function(e) {
      setH(e);
      dom.bind(window, 'mousemove', setH);
      dom.bind(window, 'mouseup', unbindH);
    });

    function fieldDown(e) {
      setSV(e);
      // document.body.style.cursor = 'none';
      dom.bind(window, 'mousemove', setSV);
      dom.bind(window, 'mouseup', unbindSV);
    }

    function unbindSV() {
      dom.unbind(window, 'mousemove', setSV);
      dom.unbind(window, 'mouseup', unbindSV);
      // document.body.style.cursor = 'default';
    }

    function onBlur() {
      const i = interpret(this.value);
      if (i !== false) {
        _this.__color.__state = i;
        _this.setValue(_this.__color.toOriginal());
      } else {
        this.value = _this.__color.toString();
      }
    }

    function unbindH() {
      dom.unbind(window, 'mousemove', setH);
      dom.unbind(window, 'mouseup', unbindH);
    }

    this.__saturation_field.appendChild(valueField);
    this.__selector.appendChild(this.__field_knob);
    this.__selector.appendChild(this.__saturation_field);
    this.__selector.appendChild(this.__hue_field);
    this.__hue_field.appendChild(this.__hue_knob);

    this.domElement.appendChild(this.__input);
    this.domElement.appendChild(this.__selector);

    this.updateDisplay();

    function setSV(e) {
      e.preventDefault();

      const w = dom.getWidth(_this.__saturation_field);
      const o = dom.getOffset(_this.__saturation_field);
      let s = (e.clientX - o.left + document.body.scrollLeft) / w;
      let v = 1 - (e.clientY - o.top + document.body.scrollTop) / w;

      if (v > 1) {
        v = 1;
      } else if (v < 0) {
        v = 0;
      }

      if (s > 1) {
        s = 1;
      } else if (s < 0) {
        s = 0;
      }

      _this.__color.v = v;
      _this.__color.s = s;

      _this.setValue(_this.__color.toOriginal());

      return false;
    }

    function setH(e) {
      e.preventDefault();

      const s = dom.getHeight(_this.__hue_field);
      const o = dom.getOffset(_this.__hue_field);
      let h = 1 - (e.clientY - o.top + document.body.scrollTop) / s;

      if (h > 1) {
        h = 1;
      } else if (h < 0) {
        h = 0;
      }

      _this.__color.h = h * 360;

      _this.setValue(_this.__color.toOriginal());

      return false;
    }
  }

  updateDisplay() {
    const i = interpret(this.getValue());

    if (i !== false) {
      let mismatch = false;

      // Check for mismatch on the interpreted value.

      common.each(Color.COMPONENTS, function(component) {
        if (!common.isUndefined(i[component]) && !common.isUndefined(this.__color.__state[component]) &&
          i[component] !== this.__color.__state[component]) {
          mismatch = true;
          return {}; // break
        }
      }, this);

      // If nothing diverges, we keep our previous values
      // for statefulness, otherwise we recalculate fresh
      if (mismatch) {
        common.extend(this.__color.__state, i);
      }
    }

    common.extend(this.__temp.__state, this.__color.__state);

    this.__temp.a = 1;

    const flip = (this.__color.v < 0.5 || this.__color.s > 0.5) ? 255 : 0;
    const _flip = 255 - flip;

    common.extend(this.__field_knob.style, {
      marginLeft: 100 * this.__color.s - 7 + 'px',
      marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
      backgroundColor: this.__temp.toString(),
      border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
    });

    this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';

    this.__temp.s = 1;
    this.__temp.v = 1;

    linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toString());

    common.extend(this.__input.style, {
      backgroundColor: this.__input.value = this.__color.toString(),
      color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
      textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
    });
  }
}

const vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];

function linearGradient(elem, x, a, b) {
  elem.style.background = '';
  common.each(vendors, function(vendor) {
    elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  });
}

function hueGradient(elem) {
  elem.style.background = '';
  elem.style.cssText += 'background: -moz-linear-gradient(top,  #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  elem.style.cssText += 'background: -webkit-linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  elem.style.cssText += 'background: -o-linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  elem.style.cssText += 'background: -ms-linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  elem.style.cssText += 'background: linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
}

export default ColorController;
<commit_msg>color controller calls onFinishChange callback<commit_after>/**
 * dat-gui JavaScript Controller Library
 * http://code.google.com/p/dat-gui
 *
 * Copyright 2011 Data Arts Team, Google Creative Lab
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 */

import Controller from './Controller';
import dom from '../dom/dom';
import Color from '../color/Color';
import interpret from '../color/interpret';
import common from '../utils/common';

class ColorController extends Controller {
  constructor(object, property) {
    super(object, property);

    this.__color = new Color(this.getValue());
    this.__temp = new Color(0);

    const _this = this;

    this.domElement = document.createElement('div');

    dom.makeSelectable(this.domElement, false);

    this.__selector = document.createElement('div');
    this.__selector.className = 'selector';

    this.__saturation_field = document.createElement('div');
    this.__saturation_field.className = 'saturation-field';

    this.__field_knob = document.createElement('div');
    this.__field_knob.className = 'field-knob';
    this.__field_knob_border = '2px solid ';

    this.__hue_knob = document.createElement('div');
    this.__hue_knob.className = 'hue-knob';

    this.__hue_field = document.createElement('div');
    this.__hue_field.className = 'hue-field';

    this.__input = document.createElement('input');
    this.__input.type = 'text';
    this.__input_textShadow = '0 1px 1px ';

    dom.bind(this.__input, 'keydown', function(e) {
      if (e.keyCode === 13) { // on enter
        onBlur.call(this);
      }
    });

    dom.bind(this.__input, 'blur', onBlur);

    dom.bind(this.__selector, 'mousedown', function(/* e */) {
      dom
        .addClass(this, 'drag')
        .bind(window, 'mouseup', function(/* e */) {
          dom.removeClass(_this.__selector, 'drag');
        });
    });

    const valueField = document.createElement('div');

    common.extend(this.__selector.style, {
      width: '122px',
      height: '102px',
      padding: '3px',
      backgroundColor: '#222',
      boxShadow: '0px 1px 3px rgba(0,0,0,0.3)'
    });

    common.extend(this.__field_knob.style, {
      position: 'absolute',
      width: '12px',
      height: '12px',
      border: this.__field_knob_border + (this.__color.v < 0.5 ? '#fff' : '#000'),
      boxShadow: '0px 1px 3px rgba(0,0,0,0.5)',
      borderRadius: '12px',
      zIndex: 1
    });

    common.extend(this.__hue_knob.style, {
      position: 'absolute',
      width: '15px',
      height: '2px',
      borderRight: '4px solid #fff',
      zIndex: 1
    });

    common.extend(this.__saturation_field.style, {
      width: '100px',
      height: '100px',
      border: '1px solid #555',
      marginRight: '3px',
      display: 'inline-block',
      cursor: 'pointer'
    });

    common.extend(valueField.style, {
      width: '100%',
      height: '100%',
      background: 'none'
    });

    linearGradient(valueField, 'top', 'rgba(0,0,0,0)', '#000');

    common.extend(this.__hue_field.style, {
      width: '15px',
      height: '100px',
      border: '1px solid #555',
      cursor: 'ns-resize',
      position: 'absolute',
      top: '3px',
      right: '3px'
    });

    hueGradient(this.__hue_field);

    common.extend(this.__input.style, {
      outline: 'none',
//      width: '120px',
      textAlign: 'center',
//      padding: '4px',
//      marginBottom: '6px',
      color: '#fff',
      border: 0,
      fontWeight: 'bold',
      textShadow: this.__input_textShadow + 'rgba(0,0,0,0.7)'
    });

    dom.bind(this.__saturation_field, 'mousedown', fieldDown);
    dom.bind(this.__field_knob, 'mousedown', fieldDown);

    dom.bind(this.__hue_field, 'mousedown', function(e) {
      setH(e);
      dom.bind(window, 'mousemove', setH);
      dom.bind(window, 'mouseup', fieldUpH);
    });

    function fieldDown(e) {
      setSV(e);
      // document.body.style.cursor = 'none';
      dom.bind(window, 'mousemove', setSV);
      dom.bind(window, 'mouseup', fieldUpSV);
    }

    function fieldUpSV() {
      dom.unbind(window, 'mousemove', setSV);
      dom.unbind(window, 'mouseup', fieldUpSV);
      // document.body.style.cursor = 'default';
      onFinish();
    }

    function onBlur() {
      const i = interpret(this.value);
      if (i !== false) {
        _this.__color.__state = i;
        _this.setValue(_this.__color.toOriginal());
      } else {
        this.value = _this.__color.toString();
      }
    }

    function fieldUpH() {
      dom.unbind(window, 'mousemove', setH);
      dom.unbind(window, 'mouseup', fieldUpH);
      onFinish();
    }

    function onFinish() {
      if (_this.__onFinishChange) {
        _this.__onFinishChange.call(_this, _this.__color.toString());
      }
    }

    this.__saturation_field.appendChild(valueField);
    this.__selector.appendChild(this.__field_knob);
    this.__selector.appendChild(this.__saturation_field);
    this.__selector.appendChild(this.__hue_field);
    this.__hue_field.appendChild(this.__hue_knob);

    this.domElement.appendChild(this.__input);
    this.domElement.appendChild(this.__selector);

    this.updateDisplay();

    function setSV(e) {
      e.preventDefault();

      const w = dom.getWidth(_this.__saturation_field);
      const o = dom.getOffset(_this.__saturation_field);
      let s = (e.clientX - o.left + document.body.scrollLeft) / w;
      let v = 1 - (e.clientY - o.top + document.body.scrollTop) / w;

      if (v > 1) {
        v = 1;
      } else if (v < 0) {
        v = 0;
      }

      if (s > 1) {
        s = 1;
      } else if (s < 0) {
        s = 0;
      }

      _this.__color.v = v;
      _this.__color.s = s;

      _this.setValue(_this.__color.toOriginal());

      return false;
    }

    function setH(e) {
      e.preventDefault();

      const s = dom.getHeight(_this.__hue_field);
      const o = dom.getOffset(_this.__hue_field);
      let h = 1 - (e.clientY - o.top + document.body.scrollTop) / s;

      if (h > 1) {
        h = 1;
      } else if (h < 0) {
        h = 0;
      }

      _this.__color.h = h * 360;

      _this.setValue(_this.__color.toOriginal());

      return false;
    }
  }

  updateDisplay() {
    const i = interpret(this.getValue());

    if (i !== false) {
      let mismatch = false;

      // Check for mismatch on the interpreted value.

      common.each(Color.COMPONENTS, function(component) {
        if (!common.isUndefined(i[component]) && !common.isUndefined(this.__color.__state[component]) &&
          i[component] !== this.__color.__state[component]) {
          mismatch = true;
          return {}; // break
        }
      }, this);

      // If nothing diverges, we keep our previous values
      // for statefulness, otherwise we recalculate fresh
      if (mismatch) {
        common.extend(this.__color.__state, i);
      }
    }

    common.extend(this.__temp.__state, this.__color.__state);

    this.__temp.a = 1;

    const flip = (this.__color.v < 0.5 || this.__color.s > 0.5) ? 255 : 0;
    const _flip = 255 - flip;

    common.extend(this.__field_knob.style, {
      marginLeft: 100 * this.__color.s - 7 + 'px',
      marginTop: 100 * (1 - this.__color.v) - 7 + 'px',
      backgroundColor: this.__temp.toString(),
      border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip + ')'
    });

    this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px';

    this.__temp.s = 1;
    this.__temp.v = 1;

    linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toString());

    common.extend(this.__input.style, {
      backgroundColor: this.__input.value = this.__color.toString(),
      color: 'rgb(' + flip + ',' + flip + ',' + flip + ')',
      textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip + ',.7)'
    });
  }
}

const vendors = ['-moz-', '-o-', '-webkit-', '-ms-', ''];

function linearGradient(elem, x, a, b) {
  elem.style.background = '';
  common.each(vendors, function(vendor) {
    elem.style.cssText += 'background: ' + vendor + 'linear-gradient(' + x + ', ' + a + ' 0%, ' + b + ' 100%); ';
  });
}

function hueGradient(elem) {
  elem.style.background = '';
  elem.style.cssText += 'background: -moz-linear-gradient(top,  #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);';
  elem.style.cssText += 'background: -webkit-linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  elem.style.cssText += 'background: -o-linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  elem.style.cssText += 'background: -ms-linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
  elem.style.cssText += 'background: linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);';
}

export default ColorController;
<|endoftext|>


<commit_before>///<reference path="Order.js"/>
//Self-Executing Anonymous Function
//Adding New Functionality to Purchasing for Edit
(function (purchasing, $, undefined) {
    "use strict";
    //Private Property
    var lineItemAndSplitSections = "#line-items-section, #order-split-section, #order-account-section";

    //Public Method
    purchasing.initEdit = function () {
        loadLineItemsAndSplits({ disableModification: true });
        attachModificationEvents();
    };

    //Public Method
    purchasing.initCopy = function () {
        loadLineItemsAndSplits({ disableModification: false });
    };

    function loadLineItemsAndSplits(options) {
        $.getJSON(purchasing._getOption("GetLineItemsAndSplitsUrl"), null, function (result) {
            //manual mapping for now.  can look into mapping plugin later
            var model = purchasing.OrderModel;
            model.items.removeAll();
            model.splitType(result.splitType);
            model.shipping(purchasing.displayAmount(result.orderDetail.Shipping));
            model.freight(purchasing.displayAmount(result.orderDetail.Freight));
            model.tax(purchasing.displayPercent(result.orderDetail.Tax));

            purchasing.OrderModel.disableSubaccountLoading = true; //Don't search subaccounts when loading existing selections
            $.each(result.lineItems, function (index, lineResult) {
                var lineItem = new purchasing.LineItem(index, model);

                lineItem.quantity(lineResult.Quantity);
                lineItem.unit(lineResult.Units);
                lineItem.desc(lineResult.Description);
                lineItem.price(lineResult.Price);
                lineItem.catalogNumber(lineResult.CatalogNumber);

                lineItem.commodity(lineResult.CommodityCode);
                lineItem.url(lineResult.Url);
                lineItem.note(lineResult.Notes);

                if (lineItem.hasDetails()) {
                    lineItem.showDetails(true);
                }

                if (model.splitType() === "Line") {
                    var lineSplitCount = model.lineSplitCount(); //keep starting split count, and increment until we push the lineItem
                    $.each(result.splits, function (i, split) {
                        if (split.LineItemId === lineResult.Id) {
                            //Add split because it's for this line
                            var newSplit = new purchasing.LineSplit(lineSplitCount++, lineItem);

                            addAccountIfNeeded(split.Account, split.AccountName);
                            addSubAccountIfNeeded(split.SubAccount, newSplit.subAccounts);

                            newSplit.amountComputed(split.Amount);
                            newSplit.account(split.Account);
                            newSplit.subAccount(split.SubAccount);
                            newSplit.project(split.Project);

                            lineItem.splits.push(newSplit);
                        }
                    });
                }

                model.items.push(lineItem);
            });

            //Lines are in, now add Order splits if needed
            if (model.splitType() === "Order") {
                $.each(result.splits, function (i, split) {
                    //Create a new split, index starting at 0, and the model is the order/$root
                    var newSplit = new purchasing.OrderSplit(i, model);

                    addAccountIfNeeded(split.Account, split.AccountName);
                    addSubAccountIfNeeded(split.SubAccount, newSplit.subAccounts);

                    newSplit.amountComputed(split.Amount);
                    newSplit.account(split.Account);
                    newSplit.subAccount(split.SubAccount);
                    newSplit.project(split.Project);

                    model.splits.push(newSplit);
                });
            }

            //Add the basic account info if there are no splits (aka just one split)
            if (model.splitType() === "None") {
                var singleSplit = result.splits[0];
                addAccountIfNeeded(singleSplit.Account, singleSplit.AccountName);
                addSubAccountIfNeeded(singleSplit.SubAccount, model.subAccounts);

                model.account(singleSplit.Account);
                model.subAccount(singleSplit.SubAccount);
                model.project(singleSplit.Project);
            }

            $(".account-number").change(); //notify that account numbers were changed to update tip UI

            purchasing.repopulateSubAccounts(model.splitType());

            if (options.disableModification) {
                disableLineItemAndSplitModification();
            }
        });
    }

    //If the account is not in list of accounts, add it
    function addAccountIfNeeded(account, accountName) {
        if (account) {
            var accountIfFound = ko.utils.arrayFirst(purchasing.OrderModel.accounts(), function (item) {
                return item.id === account;
            });

            if (accountIfFound === null) { //not found, add to list
                purchasing.OrderModel.addAccount(account, account, accountName);
            }
        }
    }

    //If the subAccount is not in the associated subAccount list, add it
    function addSubAccountIfNeeded(subAccount, subAccounts) {
        if (subAccount) {
            var subAccountIfFound = ko.utils.arrayFirst(subAccounts(), function (item) {
                return item === subAccount;
            });

            if (subAccountIfFound === null) { //not found, add to list
                subAccounts.push(subAccount);
            }
        }
    }

    function attachModificationEvents() {
        $("#item-modification-template").tmpl({}).insertBefore("#line-items-section");

        purchasing.updateNav(); //Update navigation now that we inserted a new section

        $("#item-modification-button").click(function (e, data) {
            e.preventDefault();

            var automate = data === undefined ? false : data.automate;

            if (!automate && !confirm(purchasing.getMessage("ConfirmModification"))) {
                return;
            }

            enableLineItemAndSplitModification();
        });
    }

    function disableLineItemAndSplitModification() {
        $(":input", lineItemAndSplitSections).attr("disabled", "disabled");
        $("a.button, a.biggify", lineItemAndSplitSections).hide();
        purchasing.OrderModel.adjustRouting("False");
    }

    function enableLineItemAndSplitModification() {
        $(":input", lineItemAndSplitSections).removeAttr("disabled");
        $("a.button, a.biggify", lineItemAndSplitSections).show();
        $("#item-modification-section").hide();

        //adjust the routing and for a reevaluation of the the split type so the UI updates
        purchasing.OrderModel.adjustRouting("True");
        purchasing.OrderModel.splitType.valueHasMutated();
    }

    purchasing.lowerCaseFirstLetter = function (w) {
        return w.charAt(0).toLowerCase() + w.slice(1);
    };

    purchasing.selectListContainsValue = function ($select, val) {
        var exists = false;
        $select.find("option").each(function () {
            if (this.value === val) {
                exists = true;
            }
        });

        return exists;
    };

    purchasing.repopulateSubAccounts = function (splitType) {
        $.get(purchasing._getOption("GetSubAccounts"), null, function (result) {
            $(result).each(function () { //First load all subaccounts for this order and go through each account
                var account = this.Account;
                var subAccounts = this.SubAccounts;

                //Now for each account look through accounts depending on splits and load matching subAccounts
                if (splitType === "None") { //easy, just load the subaccounts in and don't overwrite any values
                    loadSubAccountsForSplit(purchasing.OrderModel, account, subAccounts);
                }
                else if (splitType === "Order") { //go through line splits and load subaccounts when the account matches
                    $(purchasing.OrderModel.splits()).each(function () {
                        if (this.account() === account) {
                            loadSubAccountsForSplit(this, account, subAccounts);
                        }
                    });
                }
                else if (splitType === "Line") {
                    $(purchasing.OrderModel.items()).each(function () {
                        $(this.splits()).each(function () {
                            if (this.account() === account) {
                                loadSubAccountsForSplit(this, account, subAccounts);
                            }
                        });
                    });
                }
            });

            purchasing.OrderModel.disableSubaccountLoading = false; //Turn auto subaccount loading back on now that we are finished
        });
    };

    function loadSubAccountsForSplit(model, account, subAccounts) { //Add subaccounts to model.subAccounts if they don't exist
        $(subAccounts).each(function () {
            if (model.subAccounts.indexOf(this) === -1) {
                model.subAccounts.push(this);
            }
        });
    }

} (window.purchasing = window.purchasing || {}, jQuery));
<commit_msg>only bind account info if there is a split assoc with order<commit_after>///<reference path="Order.js"/>
//Self-Executing Anonymous Function
//Adding New Functionality to Purchasing for Edit
(function (purchasing, $, undefined) {
    "use strict";
    //Private Property
    var lineItemAndSplitSections = "#line-items-section, #order-split-section, #order-account-section";

    //Public Method
    purchasing.initEdit = function () {
        loadLineItemsAndSplits({ disableModification: true });
        attachModificationEvents();
    };

    //Public Method
    purchasing.initCopy = function () {
        loadLineItemsAndSplits({ disableModification: false });
    };

    function loadLineItemsAndSplits(options) {
        $.getJSON(purchasing._getOption("GetLineItemsAndSplitsUrl"), null, function (result) {
            //manual mapping for now.  can look into mapping plugin later
            var model = purchasing.OrderModel;
            model.items.removeAll();
            model.splitType(result.splitType);
            model.shipping(purchasing.displayAmount(result.orderDetail.Shipping));
            model.freight(purchasing.displayAmount(result.orderDetail.Freight));
            model.tax(purchasing.displayPercent(result.orderDetail.Tax));

            purchasing.OrderModel.disableSubaccountLoading = true; //Don't search subaccounts when loading existing selections
            $.each(result.lineItems, function (index, lineResult) {
                var lineItem = new purchasing.LineItem(index, model);

                lineItem.quantity(lineResult.Quantity);
                lineItem.unit(lineResult.Units);
                lineItem.desc(lineResult.Description);
                lineItem.price(lineResult.Price);
                lineItem.catalogNumber(lineResult.CatalogNumber);

                lineItem.commodity(lineResult.CommodityCode);
                lineItem.url(lineResult.Url);
                lineItem.note(lineResult.Notes);

                if (lineItem.hasDetails()) {
                    lineItem.showDetails(true);
                }

                if (model.splitType() === "Line") {
                    var lineSplitCount = model.lineSplitCount(); //keep starting split count, and increment until we push the lineItem
                    $.each(result.splits, function (i, split) {
                        if (split.LineItemId === lineResult.Id) {
                            //Add split because it's for this line
                            var newSplit = new purchasing.LineSplit(lineSplitCount++, lineItem);

                            addAccountIfNeeded(split.Account, split.AccountName);
                            addSubAccountIfNeeded(split.SubAccount, newSplit.subAccounts);

                            newSplit.amountComputed(split.Amount);
                            newSplit.account(split.Account);
                            newSplit.subAccount(split.SubAccount);
                            newSplit.project(split.Project);

                            lineItem.splits.push(newSplit);
                        }
                    });
                }

                model.items.push(lineItem);
            });

            //Lines are in, now add Order splits if needed
            if (model.splitType() === "Order") {
                $.each(result.splits, function (i, split) {
                    //Create a new split, index starting at 0, and the model is the order/$root
                    var newSplit = new purchasing.OrderSplit(i, model);

                    addAccountIfNeeded(split.Account, split.AccountName);
                    addSubAccountIfNeeded(split.SubAccount, newSplit.subAccounts);

                    newSplit.amountComputed(split.Amount);
                    newSplit.account(split.Account);
                    newSplit.subAccount(split.SubAccount);
                    newSplit.project(split.Project);

                    model.splits.push(newSplit);
                });
            }

            //Add the basic account info if there are no splits (aka just one split)
            if (model.splitType() === "None") {
                var singleSplit = result.splits[0];

                if (singleSplit) {
                    addAccountIfNeeded(singleSplit.Account, singleSplit.AccountName);
                    addSubAccountIfNeeded(singleSplit.SubAccount, model.subAccounts);

                    model.account(singleSplit.Account);
                    model.subAccount(singleSplit.SubAccount);
                    model.project(singleSplit.Project);
                }
            }

            $(".account-number").change(); //notify that account numbers were changed to update tip UI

            purchasing.repopulateSubAccounts(model.splitType());

            if (options.disableModification) {
                disableLineItemAndSplitModification();
            }
        });
    }

    //If the account is not in list of accounts, add it
    function addAccountIfNeeded(account, accountName) {
        if (account) {
            var accountIfFound = ko.utils.arrayFirst(purchasing.OrderModel.accounts(), function (item) {
                return item.id === account;
            });

            if (accountIfFound === null) { //not found, add to list
                purchasing.OrderModel.addAccount(account, account, accountName);
            }
        }
    }

    //If the subAccount is not in the associated subAccount list, add it
    function addSubAccountIfNeeded(subAccount, subAccounts) {
        if (subAccount) {
            var subAccountIfFound = ko.utils.arrayFirst(subAccounts(), function (item) {
                return item === subAccount;
            });

            if (subAccountIfFound === null) { //not found, add to list
                subAccounts.push(subAccount);
            }
        }
    }

    function attachModificationEvents() {
        $("#item-modification-template").tmpl({}).insertBefore("#line-items-section");

        purchasing.updateNav(); //Update navigation now that we inserted a new section

        $("#item-modification-button").click(function (e, data) {
            e.preventDefault();

            var automate = data === undefined ? false : data.automate;

            if (!automate && !confirm(purchasing.getMessage("ConfirmModification"))) {
                return;
            }

            enableLineItemAndSplitModification();
        });
    }

    function disableLineItemAndSplitModification() {
        $(":input", lineItemAndSplitSections).attr("disabled", "disabled");
        $("a.button, a.biggify", lineItemAndSplitSections).hide();
        purchasing.OrderModel.adjustRouting("False");
    }

    function enableLineItemAndSplitModification() {
        $(":input", lineItemAndSplitSections).removeAttr("disabled");
        $("a.button, a.biggify", lineItemAndSplitSections).show();
        $("#item-modification-section").hide();

        //adjust the routing and for a reevaluation of the the split type so the UI updates
        purchasing.OrderModel.adjustRouting("True");
        purchasing.OrderModel.splitType.valueHasMutated();
    }

    purchasing.lowerCaseFirstLetter = function (w) {
        return w.charAt(0).toLowerCase() + w.slice(1);
    };

    purchasing.selectListContainsValue = function ($select, val) {
        var exists = false;
        $select.find("option").each(function () {
            if (this.value === val) {
                exists = true;
            }
        });

        return exists;
    };

    purchasing.repopulateSubAccounts = function (splitType) {
        $.get(purchasing._getOption("GetSubAccounts"), null, function (result) {
            $(result).each(function () { //First load all subaccounts for this order and go through each account
                var account = this.Account;
                var subAccounts = this.SubAccounts;

                //Now for each account look through accounts depending on splits and load matching subAccounts
                if (splitType === "None") { //easy, just load the subaccounts in and don't overwrite any values
                    loadSubAccountsForSplit(purchasing.OrderModel, account, subAccounts);
                }
                else if (splitType === "Order") { //go through line splits and load subaccounts when the account matches
                    $(purchasing.OrderModel.splits()).each(function () {
                        if (this.account() === account) {
                            loadSubAccountsForSplit(this, account, subAccounts);
                        }
                    });
                }
                else if (splitType === "Line") {
                    $(purchasing.OrderModel.items()).each(function () {
                        $(this.splits()).each(function () {
                            if (this.account() === account) {
                                loadSubAccountsForSplit(this, account, subAccounts);
                            }
                        });
                    });
                }
            });

            purchasing.OrderModel.disableSubaccountLoading = false; //Turn auto subaccount loading back on now that we are finished
        });
    };

    function loadSubAccountsForSplit(model, account, subAccounts) { //Add subaccounts to model.subAccounts if they don't exist
        $(subAccounts).each(function () {
            if (model.subAccounts.indexOf(this) === -1) {
                model.subAccounts.push(this);
            }
        });
    }

} (window.purchasing = window.purchasing || {}, jQuery));
<|endoftext|>


<commit_before>var path = 'StyleManager/view/';
define([path + 'PropertyView', 'StyleManager/model/Property'],
  function(PropertyView, Property) {

    return {
      run : function(){

          describe('PropertyView', function() {

            var $fixtures;
            var $fixture;
            var model;
            var view;

            before(function () {
              $fixtures  = $("#fixtures");
              $fixture   = $('

');
            });

            beforeEach(function () {
              model = new Property();
              view = new PropertyView({
                model: model
              });
              $fixture.empty().appendTo($fixtures);
              $fixture.html(view.render().el);
            });

            afterEach(function () {
              //view.remove(); // strange errors ???
            });

            after(function () {
              $fixture.remove();
            });

            it('Rendered correctly', function() {
              var prop = view.el;
              $fixture.get(0).querySelector('.property').should.be.ok;
              prop.querySelector('.label').should.be.ok;
            });

        });
      }
    };

});<commit_msg>Add Component to StyleManager tests<commit_after>var path = 'StyleManager/view/';
define([path + 'PropertyView', 'StyleManager/model/Property', 'DomComponents/model/Component'],
  function(PropertyView, Property, Component) {

    return {
      run : function(){

          describe('PropertyView', function() {

            var $fixtures;
            var $fixture;
            var model;
            var view;

            before(function () {
              $fixtures  = $("#fixtures");
              $fixture   = $('

');
            });

            beforeEach(function () {
              component = new Component();
              model = new Property();
              view = new PropertyView({
                model: model
              });
              $fixture.empty().appendTo($fixtures);
              $fixture.html(view.render().el);
            });

            afterEach(function () {
              //view.remove(); // strange errors ???
            });

            after(function () {
              $fixture.remove();
            });

            it('Rendered correctly', function() {
              var prop = view.el;
              $fixture.get(0).querySelector('.property').should.be.ok;
              prop.querySelector('.label').should.be.ok;
            });

            it('Rendered correctly', function() {
              var prop = view.el;
              $fixture.get(0).querySelector('.property').should.be.ok;
              prop.querySelector('.label').should.be.ok;
            });

        });
      }
    };

});<|endoftext|>


<commit_before>define(function (require) {
  "use strict";

  var InstanceConstants = require('constants/InstanceConstants'),
    ProjectInstanceConstants = require('constants/ProjectInstanceConstants'),
    ProjectConstants = require('constants/ProjectConstants'),
    Instance = require('models/Instance'),
    Project = require('models/Project'),
    Router = require('Router'),
    actions = require('actions'),
    Utils = require('../Utils'),
    ProjectInstance = require('models/ProjectInstance');

  function launch(params) {
    if(!params.project) throw new Error("Missing project");
    if(!params.instanceName) throw new Error("Missing instanceName");
    if(!params.identity) throw new Error("Missing identity");
    if(!params.size) throw new Error("Missing size");
    if(params.version) {
        //Determine 'machine' from selected version and identity
        //var machines = stores.ImageVersionStore.getMachines(params.version.id),

        var machines = params.version.get('machines'),
        selected_machines = machines.filter(function(machine) {
          return machine.provider.uuid === params.identity.get('provider').uuid;
        });
        if(!selected_machines.length)
            throw new Error("Machine could not be filtered-down based on selected version & identity")
        params.machine = selected_machines[0]
    }
    if (!params.machine) throw new Error("Missing machine");

    var project = params.project,
        instanceName = params.instanceName,
        identity = params.identity,
        size = params.size,
        machine = params.machine,
        scripts = params.scripts;

    var instance = new Instance({
      name: instanceName,
      size: {
        id: size.id,
        alias: size.get('alias')
      },
      status: "build - requesting_launch",
      provider: {
        id: identity.get('provider').id,
        uuid: identity.get('provider').uuid
      },
      projects: [ project.id ],
      identity: {
        id: identity.id,
        uuid: identity.get('uuid')
      },
    }, {parse: true});

    // Add instance to InstanceStore
    Utils.dispatch(InstanceConstants.ADD_INSTANCE, {instance: instance});

    // Create ProjectInstance
    var projectInstance = new ProjectInstance({
      project: project.toJSON(),
      instance: instance.toJSON()
    });

    // Add to ProjectInstanceStore
    Utils.dispatch(ProjectInstanceConstants.ADD_PROJECT_INSTANCE, {projectInstance: projectInstance});

    instance.createOnV1Endpoint({
      name: instanceName,
      size_alias: size.get('alias'),
      machine_alias: machine.uuid,
      scripts: scripts,
    }).done(function(attrs, status, response) {
        instance.set('id', attrs.id);

        // Get the instance from the cloud, ignore our local copy
        instance.fetch().done(function() {
            // NOTE: we have to set this here, because our instance above never gets saved
            instance.set('projects', [project.id]);

            Utils.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
            Utils.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});
        });

        // Save projectInstance to db
        projectInstance.save(null, {attrs: {
            project: project.id,
            instance: instance.id
        }});

    }).fail(function (response) {
      // Remove instance from stores
      Utils.dispatch(InstanceConstants.REMOVE_INSTANCE, {instance: instance});
      Utils.dispatch(ProjectInstanceConstants.REMOVE_PROJECT_INSTANCE, {projectInstance: projectInstance});
      Utils.displayError({title: "Instance could not be launched", response: response});
    });

    // Since this is triggered from the images page, navigate off
    // that page and back to the instance list so the user can see
    // their instance being created
    Router.getInstance().transitionTo("project-resources", {projectId: project.id});
  }

  return {

    createProjectAndLaunchInstance: function (params) {
      if (!params.projectName) throw new Error("Missing projectName");

      var projectName = params.projectName,
        project = new Project({
          name: projectName,
          description: projectName,
          instances: [],
          volumes: []
        });

      Utils.dispatch(ProjectConstants.ADD_PROJECT, {project: project});

      project.save().done(function() {
        Utils.dispatch(ProjectConstants.UPDATE_PROJECT, {project: project});

        // launch the instance into the project
        params.project = project;
        delete params['projectName'];
        launch(params);

        // Since this is triggered from the images page, navigate off
        // that page and back to the instance list so the user can see
        // their instance being created
        Router.getInstance().transitionTo("project-resources", {projectId: project.id});
      }).fail(function(response) {
        Utils.dispatch(ProjectConstants.REMOVE_PROJECT, {project: project});
        Utils.displayError({title: "Project could not be created", response: response});
      });
    },

    launch: launch
  };

});
<commit_msg>dispatch InstanceHistoryStore add<commit_after>define(function (require) {
  "use strict";

  var InstanceConstants = require('constants/InstanceConstants'),
    InstanceHistoryConstants = require('constants/InstanceHistoryConstants'),
    ProjectInstanceConstants = require('constants/ProjectInstanceConstants'),
    ProjectConstants = require('constants/ProjectConstants'),
    Instance = require('models/Instance'),
    Project = require('models/Project'),
    Router = require('Router'),
    actions = require('actions'),
    Utils = require('../Utils'),
    ProjectInstance = require('models/ProjectInstance');

  function launch(params) {
    if(!params.project) throw new Error("Missing project");
    if(!params.instanceName) throw new Error("Missing instanceName");
    if(!params.identity) throw new Error("Missing identity");
    if(!params.size) throw new Error("Missing size");
    if(params.version) {
        //Determine 'machine' from selected version and identity
        //var machines = stores.ImageVersionStore.getMachines(params.version.id),

        var machines = params.version.get('machines'),
        selected_machines = machines.filter(function(machine) {
          return machine.provider.uuid === params.identity.get('provider').uuid;
        });
        if(!selected_machines.length)
            throw new Error("Machine could not be filtered-down based on selected version & identity")
        params.machine = selected_machines[0]
    }
    if (!params.machine) throw new Error("Missing machine");

    var project = params.project,
        instanceName = params.instanceName,
        identity = params.identity,
        size = params.size,
        machine = params.machine,
        scripts = params.scripts;

    var instance = new Instance({
      name: instanceName,
      size: {
        id: size.id,
        alias: size.get('alias')
      },
      status: "build - requesting_launch",
      provider: {
        id: identity.get('provider').id,
        uuid: identity.get('provider').uuid
      },
      projects: [ project.id ],
      identity: {
        id: identity.id,
        uuid: identity.get('uuid')
      },
    }, {parse: true});

    // Add instance to InstanceStore
    Utils.dispatch(InstanceConstants.ADD_INSTANCE, {instance: instance});

    // Create ProjectInstance
    var projectInstance = new ProjectInstance({
      project: project.toJSON(),
      instance: instance.toJSON()
    });

    // Add to ProjectInstanceStore
    Utils.dispatch(ProjectInstanceConstants.ADD_PROJECT_INSTANCE, {projectInstance: projectInstance});

    instance.createOnV1Endpoint({
      name: instanceName,
      size_alias: size.get('alias'),
      machine_alias: machine.uuid,
      scripts: scripts,
    }).done(function(attrs, status, response) {
        instance.set('id', attrs.id);

        // Get the instance from the cloud, ignore our local copy
        instance.fetch().done(function() {
            // NOTE: we have to set this here, because our instance above never gets saved
            instance.set('projects', [project.id]);

            Utils.dispatch(InstanceConstants.UPDATE_INSTANCE, {instance: instance});
            Utils.dispatch(InstanceConstants.POLL_INSTANCE, {instance: instance});

            // Add instance to InstanceHistoryStore
            Utils.dispatch(InstanceHistoryConstants.ADD, {instance: instance});
        });

        // Save projectInstance to db
        projectInstance.save(null, {attrs: {
            project: project.id,
            instance: instance.id
        }});

    }).fail(function (response) {
      // Remove instance from stores
      Utils.dispatch(InstanceConstants.REMOVE_INSTANCE, {instance: instance});
      Utils.dispatch(ProjectInstanceConstants.REMOVE_PROJECT_INSTANCE, {projectInstance: projectInstance});
      Utils.displayError({title: "Instance could not be launched", response: response});
    });

    // Since this is triggered from the images page, navigate off
    // that page and back to the instance list so the user can see
    // their instance being created
    Router.getInstance().transitionTo("project-resources", {projectId: project.id});
  }

  return {

    createProjectAndLaunchInstance: function (params) {
      if (!params.projectName) throw new Error("Missing projectName");

      var projectName = params.projectName,
        project = new Project({
          name: projectName,
          description: projectName,
          instances: [],
          volumes: []
        });

      Utils.dispatch(ProjectConstants.ADD_PROJECT, {project: project});

      project.save().done(function() {
        Utils.dispatch(ProjectConstants.UPDATE_PROJECT, {project: project});

        // launch the instance into the project
        params.project = project;
        delete params['projectName'];
        launch(params);

        // Since this is triggered from the images page, navigate off
        // that page and back to the instance list so the user can see
        // their instance being created
        Router.getInstance().transitionTo("project-resources", {projectId: project.id});
      }).fail(function(response) {
        Utils.dispatch(ProjectConstants.REMOVE_PROJECT, {project: project});
        Utils.displayError({title: "Project could not be created", response: response});
      });
    },

    launch: launch
  };

});
<|endoftext|>


<commit_before>var AnalysisDefinitionNodeModel = require('./analysis-definition-node-model');
var TableModel = require('./table-model');

/**
 * Special case of a node model representing a source node.
 */
module.exports = AnalysisDefinitionNodeModel.extend({

  defaults: {
    status: 'ready'
  },

  /**
   * @override AnalysisDefinitionNodeModel.prototype.initialize
   */
  initialize: function (attrs, opts) {
    AnalysisDefinitionNodeModel.prototype.initialize.apply(this, arguments);

    var query = this.get('query');
    this.querySchemaModel.set({
      query: query,
      ready: true
    }, { silent: true });

    this.queryGeometryModel.set({
      query: query,
      ready: true
    }, { silent: true });

    ;

    this.tableModel = this.getTableModel();

    this.fetchTable();
  },

  getTableModel: function () {
    var tableModel = new TableModel({
      name: this.get('table_name')
    }, {
      configModel: opts.configModel
    });

    return tableModel;
  },

  fetchTable: function () {
    if (!this.tableModel.get('id')) {
      this.tableModel.fetch();
    }
  }

});
<commit_msg>layers: sync in analysis source, changes<commit_after>var AnalysisDefinitionNodeModel = require('./analysis-definition-node-model');
var TableModel = require('./table-model');

/**
 * Special case of a node model representing a source node.
 */
module.exports = AnalysisDefinitionNodeModel.extend({

  defaults: {
    status: 'ready'
  },

  /**
   * @override AnalysisDefinitionNodeModel.prototype.initialize
   */
  initialize: function (attrs, opts) {
    AnalysisDefinitionNodeModel.prototype.initialize.apply(this, arguments);

    var query = this.get('query');
    this.querySchemaModel.set({
      query: query,
      ready: true
    }, { silent: true });

    this.queryGeometryModel.set({
      query: query,
      ready: true
    }, { silent: true });

    ;

    this.tableModel = new TableModel({
      name: this.get('table_name')
    }, {
      configModel: opts.configModel
    });

    this.fetchTable();
  },

  getTableModel: function () {
    return this.tableModel;
  },

  fetchTable: function () {
    if (!this.tableModel.get('id')) {
      this.tableModel.fetch();
    }
  }

});
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var constants = require( './constants.js' );

// FUNCTIONS //

/**
* Returns number of elements in array equal to a provided value.
*
* @private
* @param {Array} arr - input array
* @param {NonNegativeInteger} start - starting search index (inclusive)
* @param {NonNegativeInteger} end - ending search index (inclusive)
* @param {*} value - input value
* @returns {NonNegativeInteger} number of elements in array equal to a provided value
*/
function count( arr, start, end, value ) {
	var cnt;
	var i;

	if ( end >= arr.length ) {
		end = arr.length - 1;
	}
	cnt = 0;
	for ( i = start; i <= end; i++ ) {
		if ( arr[ i ] === value ) {
			cnt += 1;
		}
	}
	return cnt;
}

/**
* Returns whether every indexed array element is equal to a provided value.
*
* @private
* @param {Array} arr - input array
* @param {NonNegativeInteger} start - starting search index (inclusive)
* @param {NonNegativeInteger} end - ending search index (inclusive)
* @param {*} value - search value
* @returns {boolean} boolean indicating whether all the values in array in the given range are equal to the provided value
*/
function every( arr, start, end, value ) {
	var i;

	if ( end >= arr.length ) {
		end = arr.length - 1;
	}
	for ( i = start; i <= end; i++ ) {
		if ( arr[ i ] !== value ) {
			return false;
		}
	}
	return true;
}

/**
* Returns the index of the first occurrence of a value in a provided array.
*
* @private
* @param {Array} arr - input array
* @param {NonNegativeInteger} start - starting search index (inclusive)
* @param {NonNegativeInteger} end - ending search index (inclusive)
* @param {*} value - search value
* @returns {integer} index of the first occurrence
*/
function indexOf( arr, start, end, value ) {
	var i;

	if ( end >= arr.length ) {
		end = arr.length - 1;
	}
	for ( i = start; i <= end; i++ ) {
		if ( arr[ i ] === value ) {
			return i;
		}
	}
	return -1;
}

/**
* Returns the index of the last occurrence of a value in a provided array.
*
* @private
* @param {Array} arr - input array
* @param {NonNegativeInteger} start - starting search index at which to start searching backwards (inclusive)
* @param {NonNegativeInteger} end - ending search index (inclusive)
* @param {*} value - search value
* @returns {integer} index of the last occurrence
*/
function lastIndexOf( arr, start, end, value ) {
	var i;

	if ( start >= arr.length-1 ) {
		start = arr.length - 1;
	}
	for ( i = start; i >= end; i-- ) {
		if ( arr[ i ] === value ) {
			return i;
		}
	}
	return -1;
}

// MAIN //

/**
* Returns the break type between the two given grapheme breaking classes according to _UAX #29 3.1.1 Grapheme Cluster Boundary Rules_ on extended grapheme clusters.
*
* @private
* @param {Array} breaks - list of grapheme break properties
* @param {Array} emoji - list of emoji properties
* @returns {NonNegativeInteger} break type
*/
function breakType( breaks, emoji ) {
	var nextEmoji;
	var next;
	var prev;
	var idx;
	var N;
	var M;

	N = breaks.length;
	M = N - 1;

	prev = breaks[ M-1 ];
	next = breaks[ M ];
	nextEmoji = emoji[ M ];

	idx = lastIndexOf( breaks, M, 0, constants.RegionalIndicator );
	if (
		idx > 0 &&
		prev !== constants.Prepend &&
		prev !== constants.RegionalIndicator &&
		every( breaks, 1, idx-1, constants.RegionalIndicator )
	) {
		if ( count( breaks, 0, M, constants.RegionalIndicator ) % 2 === 1 ) {
			return constants.BreakLastRegional;
		}
		return constants.BreakPenultimateRegional;
	}
	// GB3: CR × LF
	if (
		prev === constants.CR &&
		next === constants.LF
	) {
		return constants.NotBreak;
	}
	// GB4: (Control|CR|LF) ÷
	if (
		prev === constants.Control ||
		prev === constants.CR ||
		prev === constants.LF
	) {
		return constants.BreakStart;
	}
	// GB5: ÷ (Control|CR|LF)
	if (
		next === constants.Control ||
		next === constants.CR ||
		next === constants.LF
	) {
		return constants.BreakStart;
	}
	// GB6: L × (L|V|LV|LVT)
	if (
		prev === constants.L &&
		(
			next === constants.L ||
			next === constants.V ||
			next === constants.LV ||
			next === constants.LVT
		)
	) {
		return constants.NotBreak;
	}
	// GB7: (LV|V) × (V|T)
	if (
		( prev === constants.LV || prev === constants.V ) &&
		( next === constants.V || next === constants.T )
	) {
		return constants.NotBreak;
	}
	// GB8: (LVT|T) × (T)
	if (
		( prev === constants.LVT || prev === constants.T ) &&
		next === constants.T
	) {
		return constants.NotBreak;
	}
	// GB9: × (Extend|ZWJ)
	if (
		next === constants.Extend ||
		next === constants.ZWJ
	) {
		return constants.NotBreak;
	}
	// GB9a: × SpacingMark
	if ( next === constants.SpacingMark ) {
		return constants.NotBreak;
	}
	// GB9b: Prepend ×
	if ( prev === constants.Prepend ) {
		return constants.NotBreak;
	}
	// GB11: \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic}
	idx = lastIndexOf( emoji, M-1, 0, constants.ExtendedPictographic );
	if (
		idx >= 0 &&
		prev === constants.ZWJ &&
		nextEmoji === constants.ExtendedPictographic &&
		emoji[ idx ] === constants.ExtendedPictographic &&
		every( breaks, idx+1, M-2, constants.Extend )
	) {
		return constants.NotBreak;
	}
	// GB12: ^ (RI RI)* RI × RI
	// GB13: [^RI] (RI RI)* RI × RI
	if ( indexOf( breaks, 1, M-1, constants.RegionalIndicator ) >= 0 ) {
		return constants.Break;
	}
	if (
		prev === constants.RegionalIndicator &&
		next === constants.RegionalIndicator
	) {
		return constants.NotBreak;
	}
	// GB999: Any ? Any
	return constants.BreakStart;
}

// EXPORTS //

module.exports = breakType;
<commit_msg>Update description<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

// MODULES //

var constants = require( './constants.js' );

// FUNCTIONS //

/**
* Returns number of elements in array equal to a provided value.
*
* @private
* @param {Array} arr - input array
* @param {NonNegativeInteger} start - starting search index (inclusive)
* @param {NonNegativeInteger} end - ending search index (inclusive)
* @param {*} value - input value
* @returns {NonNegativeInteger} number of elements in array equal to a provided value
*/
function count( arr, start, end, value ) {
	var cnt;
	var i;

	if ( end >= arr.length ) {
		end = arr.length - 1;
	}
	cnt = 0;
	for ( i = start; i <= end; i++ ) {
		if ( arr[ i ] === value ) {
			cnt += 1;
		}
	}
	return cnt;
}

/**
* Returns whether every indexed array element is equal to a provided value.
*
* @private
* @param {Array} arr - input array
* @param {NonNegativeInteger} start - starting search index (inclusive)
* @param {NonNegativeInteger} end - ending search index (inclusive)
* @param {*} value - search value
* @returns {boolean} boolean indicating whether all the values in array in the given range are equal to the provided value
*/
function every( arr, start, end, value ) {
	var i;

	if ( end >= arr.length ) {
		end = arr.length - 1;
	}
	for ( i = start; i <= end; i++ ) {
		if ( arr[ i ] !== value ) {
			return false;
		}
	}
	return true;
}

/**
* Returns the index of the first occurrence of a value in a provided array.
*
* @private
* @param {Array} arr - input array
* @param {NonNegativeInteger} start - starting search index (inclusive)
* @param {NonNegativeInteger} end - ending search index (inclusive)
* @param {*} value - search value
* @returns {integer} index of the first occurrence
*/
function indexOf( arr, start, end, value ) {
	var i;

	if ( end >= arr.length ) {
		end = arr.length - 1;
	}
	for ( i = start; i <= end; i++ ) {
		if ( arr[ i ] === value ) {
			return i;
		}
	}
	return -1;
}

/**
* Returns the index of the last occurrence of a value in a provided array.
*
* @private
* @param {Array} arr - input array
* @param {NonNegativeInteger} start - starting search index at which to start searching backwards (inclusive)
* @param {NonNegativeInteger} end - ending search index (inclusive)
* @param {*} value - search value
* @returns {integer} index of the last occurrence
*/
function lastIndexOf( arr, start, end, value ) {
	var i;

	if ( start >= arr.length-1 ) {
		start = arr.length - 1;
	}
	for ( i = start; i >= end; i-- ) {
		if ( arr[ i ] === value ) {
			return i;
		}
	}
	return -1;
}

// MAIN //

/**
* Returns the break type between grapheme breaking classes according to _UAX #29 3.1.1 Grapheme Cluster Boundary Rules_ on extended grapheme clusters.
*
* @private
* @param {Array} breaks - list of grapheme break properties
* @param {Array} emoji - list of emoji properties
* @returns {NonNegativeInteger} break type
*/
function breakType( breaks, emoji ) {
	var nextEmoji;
	var next;
	var prev;
	var idx;
	var N;
	var M;

	N = breaks.length;
	M = N - 1;

	prev = breaks[ M-1 ];
	next = breaks[ M ];
	nextEmoji = emoji[ M ];

	idx = lastIndexOf( breaks, M, 0, constants.RegionalIndicator );
	if (
		idx > 0 &&
		prev !== constants.Prepend &&
		prev !== constants.RegionalIndicator &&
		every( breaks, 1, idx-1, constants.RegionalIndicator )
	) {
		if ( count( breaks, 0, M, constants.RegionalIndicator ) % 2 === 1 ) {
			return constants.BreakLastRegional;
		}
		return constants.BreakPenultimateRegional;
	}
	// GB3: CR × LF
	if (
		prev === constants.CR &&
		next === constants.LF
	) {
		return constants.NotBreak;
	}
	// GB4: (Control|CR|LF) ÷
	if (
		prev === constants.Control ||
		prev === constants.CR ||
		prev === constants.LF
	) {
		return constants.BreakStart;
	}
	// GB5: ÷ (Control|CR|LF)
	if (
		next === constants.Control ||
		next === constants.CR ||
		next === constants.LF
	) {
		return constants.BreakStart;
	}
	// GB6: L × (L|V|LV|LVT)
	if (
		prev === constants.L &&
		(
			next === constants.L ||
			next === constants.V ||
			next === constants.LV ||
			next === constants.LVT
		)
	) {
		return constants.NotBreak;
	}
	// GB7: (LV|V) × (V|T)
	if (
		( prev === constants.LV || prev === constants.V ) &&
		( next === constants.V || next === constants.T )
	) {
		return constants.NotBreak;
	}
	// GB8: (LVT|T) × (T)
	if (
		( prev === constants.LVT || prev === constants.T ) &&
		next === constants.T
	) {
		return constants.NotBreak;
	}
	// GB9: × (Extend|ZWJ)
	if (
		next === constants.Extend ||
		next === constants.ZWJ
	) {
		return constants.NotBreak;
	}
	// GB9a: × SpacingMark
	if ( next === constants.SpacingMark ) {
		return constants.NotBreak;
	}
	// GB9b: Prepend ×
	if ( prev === constants.Prepend ) {
		return constants.NotBreak;
	}
	// GB11: \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic}
	idx = lastIndexOf( emoji, M-1, 0, constants.ExtendedPictographic );
	if (
		idx >= 0 &&
		prev === constants.ZWJ &&
		nextEmoji === constants.ExtendedPictographic &&
		emoji[ idx ] === constants.ExtendedPictographic &&
		every( breaks, idx+1, M-2, constants.Extend )
	) {
		return constants.NotBreak;
	}
	// GB12: ^ (RI RI)* RI × RI
	// GB13: [^RI] (RI RI)* RI × RI
	if ( indexOf( breaks, 1, M-1, constants.RegionalIndicator ) >= 0 ) {
		return constants.Break;
	}
	if (
		prev === constants.RegionalIndicator &&
		next === constants.RegionalIndicator
	) {
		return constants.NotBreak;
	}
	// GB999: Any ? Any
	return constants.BreakStart;
}

// EXPORTS //

module.exports = breakType;
<|endoftext|>


<commit_before>import React, {PropTypes} from 'react'
import buildInfluxQLQuery from 'utils/influxql'
import classNames from 'classnames'
import AutoRefresh from 'shared/components/AutoRefresh'
import LineGraph from 'shared/components/LineGraph'
import SingleStat from 'shared/components/SingleStat'
import Table from './Table'
import VisHeader from 'src/data_explorer/components/VisHeader'

const RefreshingLineGraph = AutoRefresh(LineGraph)
const RefreshingSingleStat = AutoRefresh(SingleStat)

const GRAPH = 'graph'
const TABLE = 'table'
const VIEWS = [GRAPH, TABLE]

const {
  func,
  arrayOf,
  number,
  shape,
  string,
} = PropTypes

const Visualization = React.createClass({
  propTypes: {
    cellName: string,
    cellType: string,
    autoRefresh: number.isRequired,
    timeRange: shape({
      upper: string,
      lower: string,
    }).isRequired,
    queryConfigs: arrayOf(shape({})).isRequired,
    activeQueryIndex: number,
    height: string,
    heightPixels: number,
    onEditRawStatus: func.isRequired,
  },

  contextTypes: {
    source: PropTypes.shape({
      links: PropTypes.shape({
        proxy: PropTypes.string.isRequired,
      }).isRequired,
    }).isRequired,
  },

  getInitialState() {
    const {queryConfigs, activeQueryIndex} = this.props
    if (!queryConfigs.length || activeQueryIndex === null) {
      return {
        view: GRAPH,
      }
    }

    return {
      view: typeof queryConfigs[activeQueryIndex].rawText === 'string' ? TABLE : GRAPH,
    }
  },

  componentWillReceiveProps(nextProps) {
    const {queryConfigs, activeQueryIndex} = nextProps
    if (!queryConfigs.length || activeQueryIndex === null || activeQueryIndex === this.props.activeQueryIndex) {
      return
    }

    const activeQuery = queryConfigs[activeQueryIndex]
    if (activeQuery && typeof activeQuery.rawText === 'string') {
      return this.setState({view: TABLE})
    }
  },

  handleToggleView(view) {
    this.setState({view})
  },

  render() {
    const {queryConfigs, timeRange, height, heightPixels, onEditRawStatus, activeQueryIndex} = this.props
    const {source} = this.context
    const proxyLink = source.links.proxy
    const {view} = this.state

    const statements = queryConfigs.map((query) => {
      const text = query.rawText || buildInfluxQLQuery(timeRange, query)
      return {text, id: query.id}
    })
    const queries = statements.filter((s) => s.text !== null).map((s) => {
      return {host: [proxyLink], text: s.text, id: s.id}
    })

    return (

        <VisHeader views={VIEWS} view={view} onToggleView={this.handleToggleView} name={name || 'Graph'}/>

          {this.renderVisualization(view, queries, heightPixels, onEditRawStatus, activeQueryIndex)}

    )
  },

  renderVisualization(view, queries, heightPixels, onEditRawStatus, activeQueryIndex) {
    const activeQuery = queries[activeQueryIndex]
    const defaultQuery = queries[0]

    switch (view) {
      case TABLE:
        return this.renderTable(activeQuery || defaultQuery, heightPixels, onEditRawStatus)
      case GRAPH:
      default:
        this.renderGraph(queries)
    }
  },

  renderTable(query, heightPixels, onEditRawStatus) {
    if (!query) {
      return
Enter your query below

    }

    return

  },

  renderGraph(queries) {
    const {cellType, autoRefresh, activeQueryIndex} = this.props
    const isInDataExplorer = true

    if (cellType === 'single-stat') {
      return <RefreshingSingleStat queries={[queries[0]]} autoRefresh={autoRefresh} />
    }

    const displayOptions = {
      stepPlot: cellType === 'line-stepplot',
      stackedGraph: cellType === 'line-stacked',
    }
    return (
      <RefreshingLineGraph
        queries={queries}
        autoRefresh={autoRefresh}
        activeQueryIndex={activeQueryIndex}
        isInDataExplorer={isInDataExplorer}
        showSingleStat={cellType === "line-plus-single-stat"}
        displayOptions={displayOptions}
      />
    )
  },
})

export default Visualization
<commit_msg>Remove switch statement<commit_after>import React, {PropTypes} from 'react'
import buildInfluxQLQuery from 'utils/influxql'
import classNames from 'classnames'
import AutoRefresh from 'shared/components/AutoRefresh'
import LineGraph from 'shared/components/LineGraph'
import SingleStat from 'shared/components/SingleStat'
import Table from './Table'
import VisHeader from 'src/data_explorer/components/VisHeader'

const RefreshingLineGraph = AutoRefresh(LineGraph)
const RefreshingSingleStat = AutoRefresh(SingleStat)

const GRAPH = 'graph'
const TABLE = 'table'
const VIEWS = [GRAPH, TABLE]

const {
  func,
  arrayOf,
  number,
  shape,
  string,
} = PropTypes

const Visualization = React.createClass({
  propTypes: {
    cellName: string,
    cellType: string,
    autoRefresh: number.isRequired,
    timeRange: shape({
      upper: string,
      lower: string,
    }).isRequired,
    queryConfigs: arrayOf(shape({})).isRequired,
    activeQueryIndex: number,
    height: string,
    heightPixels: number,
    onEditRawStatus: func.isRequired,
  },

  contextTypes: {
    source: PropTypes.shape({
      links: PropTypes.shape({
        proxy: PropTypes.string.isRequired,
      }).isRequired,
    }).isRequired,
  },

  getInitialState() {
    const {queryConfigs, activeQueryIndex} = this.props
    if (!queryConfigs.length || activeQueryIndex === null) {
      return {
        view: GRAPH,
      }
    }

    return {
      view: typeof queryConfigs[activeQueryIndex].rawText === 'string' ? TABLE : GRAPH,
    }
  },

  componentWillReceiveProps(nextProps) {
    const {queryConfigs, activeQueryIndex} = nextProps
    if (!queryConfigs.length || activeQueryIndex === null || activeQueryIndex === this.props.activeQueryIndex) {
      return
    }

    const activeQuery = queryConfigs[activeQueryIndex]
    if (activeQuery && typeof activeQuery.rawText === 'string') {
      return this.setState({view: TABLE})
    }
  },

  handleToggleView(view) {
    this.setState({view})
  },

  render() {
    const {queryConfigs, timeRange, height, heightPixels, onEditRawStatus, activeQueryIndex} = this.props
    const {source} = this.context
    const proxyLink = source.links.proxy
    const {view} = this.state

    const statements = queryConfigs.map((query) => {
      const text = query.rawText || buildInfluxQLQuery(timeRange, query)
      return {text, id: query.id}
    })
    const queries = statements.filter((s) => s.text !== null).map((s) => {
      return {host: [proxyLink], text: s.text, id: s.id}
    })

    return (

        <VisHeader views={VIEWS} view={view} onToggleView={this.handleToggleView} name={name || 'Graph'}/>

          {this.renderVisualization(view, queries, heightPixels, onEditRawStatus, activeQueryIndex)}

    )
  },

  renderVisualization(view, queries, heightPixels, onEditRawStatus, activeQueryIndex) {
    const activeQuery = queries[activeQueryIndex]
    const defaultQuery = queries[0]

    if (view === TABLE) {
      return this.renderTable(activeQuery || defaultQuery, heightPixels, onEditRawStatus)
    }

    return this.renderGraph(queries)
  },

  renderTable(query, heightPixels, onEditRawStatus) {
    if (!query) {
      return
Enter your query below

    }

    return

  },

  renderGraph(queries) {
    const {cellType, autoRefresh, activeQueryIndex} = this.props
    const isInDataExplorer = true

    if (cellType === 'single-stat') {
      return <RefreshingSingleStat queries={[queries[0]]} autoRefresh={autoRefresh} />
    }

    const displayOptions = {
      stepPlot: cellType === 'line-stepplot',
      stackedGraph: cellType === 'line-stacked',
    }
    return (
      <RefreshingLineGraph
        queries={queries}
        autoRefresh={autoRefresh}
        activeQueryIndex={activeQueryIndex}
        isInDataExplorer={isInDataExplorer}
        showSingleStat={cellType === "line-plus-single-stat"}
        displayOptions={displayOptions}
      />
    )
  },
})

export default Visualization
<|endoftext|>


<commit_before>"use strict";

const path = require("path");
const tempy = require("tempy");
const Package = require("@lerna/package");
const listable = require("..");

// remove quotes around top-level strings
expect.addSnapshotSerializer({
  test(val) {
    return typeof val === "string";
  },
  serialize(val, config, indentation, depth) {
    // top-level strings don't need quotes, but nested ones do (object properties, etc)
    return depth ? `"${val}"` : val;
  },
});

// normalize temp directory paths in snapshots
expect.addSnapshotSerializer(require("@lerna-test/serialize-tempdir"));
expect.addSnapshotSerializer(require("@lerna-test/serialize-windows-paths"));

describe("listable.format()", () => {
  let packages;

  const formatWithOptions = opts => listable.format(packages, Object.assign({ _: ["ls"] }, opts));

  beforeAll(() => {
    const cwd = tempy.directory();
    process.chdir(cwd);

    packages = [
      new Package({ name: "pkg-1", version: "1.0.0" }, path.join(cwd, "/pkgs/pkg-1")),
      new Package({ name: "pkg-2" }, path.join(cwd, "/pkgs/pkg-2")),
      new Package({ name: "pkg-3", version: "3.0.0", private: true }, path.join(cwd, "/pkgs/pkg-3")),
    ];
  });

  describe("renders", () => {
    test("all output", () => {
      const { count, text } = formatWithOptions({ all: true });

      expect(count).toBe(3);
      expect(text).toMatchInlineSnapshot(`
pkg-1
pkg-2
pkg-3 (PRIVATE)
`);
    });

    test("long output", () => {
      const { count, text } = formatWithOptions({ long: true });

      expect(count).toBe(2);
      expect(text).toMatchInlineSnapshot(`
pkg-1  v1.0.0 pkgs/pkg-1
pkg-2 MISSING pkgs/pkg-2
`);
    });

    test("all long output", () => {
      const { text } = formatWithOptions({ long: true, all: true });

      expect(text).toMatchInlineSnapshot(`
pkg-1  v1.0.0 pkgs/pkg-1
pkg-2 MISSING pkgs/pkg-2
pkg-3  v3.0.0 pkgs/pkg-3 (PRIVATE)
`);
    });

    test("JSON output", () => {
      const { text } = formatWithOptions({ json: true });

      expect(text).toMatchInlineSnapshot(`
[
  {
    "name": "pkg-1",
    "version": "1.0.0",
    "private": false,
    "location": "<PROJECT_ROOT>/pkgs/pkg-1"
  },
  {
    "name": "pkg-2",
    "private": false,
    "location": "<PROJECT_ROOT>/pkgs/pkg-2"
  }
]
`);
    });

    test("all JSON output", () => {
      const { text } = formatWithOptions({ json: true, all: true });

      expect(text).toMatchInlineSnapshot(`
[
  {
    "name": "pkg-1",
    "version": "1.0.0",
    "private": false,
    "location": "<PROJECT_ROOT>/pkgs/pkg-1"
  },
  {
    "name": "pkg-2",
    "private": false,
    "location": "<PROJECT_ROOT>/pkgs/pkg-2"
  },
  {
    "name": "pkg-3",
    "version": "3.0.0",
    "private": true,
    "location": "<PROJECT_ROOT>/pkgs/pkg-3"
  }
]
`);
    });

    test("parseable output", () => {
      const { text } = formatWithOptions({ parseable: true });

      expect(text).toMatchInlineSnapshot(`
<PROJECT_ROOT>/pkgs/pkg-1
<PROJECT_ROOT>/pkgs/pkg-2
`);
    });

    test("all parseable output", () => {
      const { text } = formatWithOptions({ parseable: true, all: true });

      expect(text).toMatchInlineSnapshot(`
<PROJECT_ROOT>/pkgs/pkg-1
<PROJECT_ROOT>/pkgs/pkg-2
<PROJECT_ROOT>/pkgs/pkg-3
`);
    });

    test("long parseable output", () => {
      const { text } = formatWithOptions({ parseable: true, long: true });

      expect(text).toMatchInlineSnapshot(`
<PROJECT_ROOT>/pkgs/pkg-1:pkg-1:1.0.0
<PROJECT_ROOT>/pkgs/pkg-2:pkg-2:MISSING
`);
    });

    test("all long parseable output", () => {
      const { text } = formatWithOptions({ parseable: true, all: true, long: true });

      expect(text).toMatchInlineSnapshot(`
<PROJECT_ROOT>/pkgs/pkg-1:pkg-1:1.0.0
<PROJECT_ROOT>/pkgs/pkg-2:pkg-2:MISSING
<PROJECT_ROOT>/pkgs/pkg-3:pkg-3:3.0.0:PRIVATE
`);
    });
  });

  describe("aliases", () => {
    test("la => ls -la", () => {
      const { text } = formatWithOptions({ _: ["la"] });

      expect(text).toMatchInlineSnapshot(`
pkg-1  v1.0.0 pkgs/pkg-1
pkg-2 MISSING pkgs/pkg-2
pkg-3  v3.0.0 pkgs/pkg-3 (PRIVATE)
`);
    });

    test("ll => ls -l", () => {
      const { text } = formatWithOptions({ _: ["ll"] });

      expect(text).toMatchInlineSnapshot(`
pkg-1  v1.0.0 pkgs/pkg-1
pkg-2 MISSING pkgs/pkg-2
`);
    });
  });
});
<commit_msg>test(listable): Turn off chalk so stuff doesn't fail in CI<commit_after>"use strict";

const chalk = require("chalk");
const path = require("path");
const tempy = require("tempy");
const Package = require("@lerna/package");
const listable = require("..");

// keep snapshots stable cross-platform
chalk.enabled = false;

// remove quotes around top-level strings
expect.addSnapshotSerializer({
  test(val) {
    return typeof val === "string";
  },
  serialize(val, config, indentation, depth) {
    // top-level strings don't need quotes, but nested ones do (object properties, etc)
    return depth ? `"${val}"` : val;
  },
});

// normalize temp directory paths in snapshots
expect.addSnapshotSerializer(require("@lerna-test/serialize-tempdir"));
expect.addSnapshotSerializer(require("@lerna-test/serialize-windows-paths"));

describe("listable.format()", () => {
  let packages;

  const formatWithOptions = opts => listable.format(packages, Object.assign({ _: ["ls"] }, opts));

  beforeAll(() => {
    const cwd = tempy.directory();
    process.chdir(cwd);

    packages = [
      new Package({ name: "pkg-1", version: "1.0.0" }, path.join(cwd, "/pkgs/pkg-1")),
      new Package({ name: "pkg-2" }, path.join(cwd, "/pkgs/pkg-2")),
      new Package({ name: "pkg-3", version: "3.0.0", private: true }, path.join(cwd, "/pkgs/pkg-3")),
    ];
  });

  describe("renders", () => {
    test("all output", () => {
      const { count, text } = formatWithOptions({ all: true });

      expect(count).toBe(3);
      expect(text).toMatchInlineSnapshot(`
pkg-1
pkg-2
pkg-3 (PRIVATE)
`);
    });

    test("long output", () => {
      const { count, text } = formatWithOptions({ long: true });

      expect(count).toBe(2);
      expect(text).toMatchInlineSnapshot(`
pkg-1  v1.0.0 pkgs/pkg-1
pkg-2 MISSING pkgs/pkg-2
`);
    });

    test("all long output", () => {
      const { text } = formatWithOptions({ long: true, all: true });

      expect(text).toMatchInlineSnapshot(`
pkg-1  v1.0.0 pkgs/pkg-1
pkg-2 MISSING pkgs/pkg-2
pkg-3  v3.0.0 pkgs/pkg-3 (PRIVATE)
`);
    });

    test("JSON output", () => {
      const { text } = formatWithOptions({ json: true });

      expect(text).toMatchInlineSnapshot(`
[
  {
    "name": "pkg-1",
    "version": "1.0.0",
    "private": false,
    "location": "<PROJECT_ROOT>/pkgs/pkg-1"
  },
  {
    "name": "pkg-2",
    "private": false,
    "location": "<PROJECT_ROOT>/pkgs/pkg-2"
  }
]
`);
    });

    test("all JSON output", () => {
      const { text } = formatWithOptions({ json: true, all: true });

      expect(text).toMatchInlineSnapshot(`
[
  {
    "name": "pkg-1",
    "version": "1.0.0",
    "private": false,
    "location": "<PROJECT_ROOT>/pkgs/pkg-1"
  },
  {
    "name": "pkg-2",
    "private": false,
    "location": "<PROJECT_ROOT>/pkgs/pkg-2"
  },
  {
    "name": "pkg-3",
    "version": "3.0.0",
    "private": true,
    "location": "<PROJECT_ROOT>/pkgs/pkg-3"
  }
]
`);
    });

    test("parseable output", () => {
      const { text } = formatWithOptions({ parseable: true });

      expect(text).toMatchInlineSnapshot(`
<PROJECT_ROOT>/pkgs/pkg-1
<PROJECT_ROOT>/pkgs/pkg-2
`);
    });

    test("all parseable output", () => {
      const { text } = formatWithOptions({ parseable: true, all: true });

      expect(text).toMatchInlineSnapshot(`
<PROJECT_ROOT>/pkgs/pkg-1
<PROJECT_ROOT>/pkgs/pkg-2
<PROJECT_ROOT>/pkgs/pkg-3
`);
    });

    test("long parseable output", () => {
      const { text } = formatWithOptions({ parseable: true, long: true });

      expect(text).toMatchInlineSnapshot(`
<PROJECT_ROOT>/pkgs/pkg-1:pkg-1:1.0.0
<PROJECT_ROOT>/pkgs/pkg-2:pkg-2:MISSING
`);
    });

    test("all long parseable output", () => {
      const { text } = formatWithOptions({ parseable: true, all: true, long: true });

      expect(text).toMatchInlineSnapshot(`
<PROJECT_ROOT>/pkgs/pkg-1:pkg-1:1.0.0
<PROJECT_ROOT>/pkgs/pkg-2:pkg-2:MISSING
<PROJECT_ROOT>/pkgs/pkg-3:pkg-3:3.0.0:PRIVATE
`);
    });
  });

  describe("aliases", () => {
    test("la => ls -la", () => {
      const { text } = formatWithOptions({ _: ["la"] });

      expect(text).toMatchInlineSnapshot(`
pkg-1  v1.0.0 pkgs/pkg-1
pkg-2 MISSING pkgs/pkg-2
pkg-3  v3.0.0 pkgs/pkg-3 (PRIVATE)
`);
    });

    test("ll => ls -l", () => {
      const { text } = formatWithOptions({ _: ["ll"] });

      expect(text).toMatchInlineSnapshot(`
pkg-1  v1.0.0 pkgs/pkg-1
pkg-2 MISSING pkgs/pkg-2
`);
    });
  });
});
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('mdi-icon', 'Integration | Component | mdi icon', {
  integration: true
});

test('it renders', function(assert) {
  // Set any properties with this.set('myProperty', 'value');
  // Handle any actions with this.on('myAction', function(val) { ... });

  this.render(hbs`{{mdi-icon}}`);

  assert.equal(this.$().text().trim(), '');

  // Template block usage:
  this.render(hbs`
    {{#mdi-icon}}
      template block text
    {{/mdi-icon}}
  `);

  assert.equal(this.$().text().trim(), 'template block text');
});
<commit_msg>Added tests<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('mdi-icon', 'Integration | Component | mdi icon', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs`{{mdi-icon "face"}}`);
  assert.equal(this.$('svg').html().trim(), '<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/icons.svg#face"></use>', 'Icon face is correct');

  this.render(hbs`{{mdi-icon icon="bug"}}`);
  assert.equal(this.$('svg').html().trim(), '<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/icons.svg#bug"></use>', 'Icon bug is correct');

  this.render(hbs`{{mdi-icon "bug" size=42}}`);
  assert.equal(this.$('svg').attr('viewBox'), '0 0 42 42', 'viewBox is correct');
  assert.equal(this.$('svg').attr('height'), '42', 'height is correct');
  assert.equal(this.$('svg').attr('width'), '42', 'width is correct');

  this.render(hbs`{{mdi-icon "bug" spin=true}}`);
  assert.ok(this.$('svg').hasClass('mdi-icon-spin'), 'Spin class');

  const rotate = 90;
  this.render(hbs`{{mdi-icon "bug" rotate=90}}`);
  assert.ok(this.$('svg').hasClass(`mdi-icon-rotate-${rotate}`), 'Rotate class');

  this.render(hbs`{{mdi-icon "bug" flipH=true}}`);
  assert.ok(this.$('svg').hasClass('mdi-icon-flip-h'), 'Horizontal flip class');

  this.render(hbs`{{mdi-icon "bug" flipV=true}}`);
  assert.ok(this.$('svg').hasClass('mdi-icon-flip-v'), 'Vertical flip class');

  this.render(hbs`{{mdi-icon "bug" role="icon"}}`);
  assert.equal(this.$('svg').attr('role'), 'icon', 'Role is correct');
});
<|endoftext|>


<commit_before>/*
 * L.Transition fallback implementation that powers Leaflet animation
 * in browsers that don't support CSS3 Transitions
 */

L.Transition = L.Transition.NATIVE ? L.Transition : L.Transition.extend({
	//TODO timer-based Transition

	statics: {
		getTime: Date.now || function() { return +new Date(); },

		TIMER: true,

		EASINGS: {
			'ease': [0.25, 0.1, 0.25, 1.0],
			'linear': [0.0, 0.0, 1.0, 1.0],
			'ease-in': [0.42, 0, 1.0, 1.0],
			'ease-out': [0, 0, 0.58, 1.0],
			'ease-in-out': [0.42, 0, 0.58, 1.0]
		},

		CUSTOM_PROPS_GETTERS: {
			position: L.DomUtil.getPosition
		},

		//used to get units from strings like "10.5px" (->px)
		UNIT_RE: /^[\d\.]+(\D*)$/
	},

	options: {
		fps: 50
	},

	initialize: function(el, options) {
		this._el = el;
		L.Util.extend(this.options, options);

		var easings = L.Transition.EASINGS[this.options.easing];
		this._p1 = new L.Point(0, 0);
		this._p2 = new L.Point(easings[0], easings[1]);
		this._p3 = new L.Point(easings[2], easings[3]);
		this._p4 = new L.Point(1, 1);

		this._step = L.Util.bind(this._step, this);
		this._interval = Math.round(1000 / this.options.fps);
	},

	run: function(props) {
		this._props = {};

		var getters = L.Transition.CUSTOM_PROPS_GETTERS,
			re = L.Transition.UNIT_RE;

		this.fire('start');

		for (var prop in props) {
			if (props.hasOwnProperty(prop)) {
				var p = {};
				if (prop in getters) {
					p.from = getters[prop](this._el);
				} else {
					var matches = this._el.style[prop].match(re);
					p.from = parseFloat(matches[0]);
					p.unit = matches[1];
				}
				p.to = props[prop];
				this._props[prop] = p;
			}
		}

		clearInterval(this._timer);
		this._timer = setInterval(this._step, this._interval);
		this._startTime = L.Transition.getTime();
	},

	_step: function() {
		var time = L.Transition.getTime(),
			elapsed = time - this._startTime,
			duration = this.options.duration * 1000;
		if (elapsed < duration) {
			var percentComplete = this._cubicBezier(elapsed / duration);
			this._runFrame(percentComplete);
		} else {
			this._runFrame(1);
			this._complete();
		}
	},

	_runFrame: function(percentComplete) {
		var setters = L.Transition.CUSTOM_PROPS_SETTERS,
			prop, p, value;

		for (prop in this._props) {
			if (this._props.hasOwnProperty(prop)) {
				p = this._props[prop];
				if (prop in setters) {
					value = p.to.subtract(p.from).multiplyBy(percentComplete).add(p.from);
					setters[prop](this._el, value);
				} else {
					this._el.style[prop] =
							((p.to - p.from) * percentComplete + p.from) + p.unit;
				}
			}
		}
		this.fire('step');
	},

	_complete: function() {
		clearInterval(this._timer);
		this.fire('end');
	},

	_cubicBezier: function(t) {
		var a = Math.pow(1 - t, 3),
			b = 3 * Math.pow(1 - t, 2) * t,
			c = 3 * (1 - t) * Math.pow(t, 2),
			d = Math.pow(t, 3),
			p1 = this._p1.multiplyBy(a),
			p2 = this._p2.multiplyBy(b),
			p3 = this._p3.multiplyBy(c),
			p4 = this._p4.multiplyBy(d);

		return p1.add(p2).add(p3).add(p4).y;
	}
});<commit_msg>remove unnecessary comment<commit_after>/*
 * L.Transition fallback implementation that powers Leaflet animation
 * in browsers that don't support CSS3 Transitions
 */

L.Transition = L.Transition.NATIVE ? L.Transition : L.Transition.extend({
	statics: {
		getTime: Date.now || function() { return +new Date(); },

		TIMER: true,

		EASINGS: {
			'ease': [0.25, 0.1, 0.25, 1.0],
			'linear': [0.0, 0.0, 1.0, 1.0],
			'ease-in': [0.42, 0, 1.0, 1.0],
			'ease-out': [0, 0, 0.58, 1.0],
			'ease-in-out': [0.42, 0, 0.58, 1.0]
		},

		CUSTOM_PROPS_GETTERS: {
			position: L.DomUtil.getPosition
		},

		//used to get units from strings like "10.5px" (->px)
		UNIT_RE: /^[\d\.]+(\D*)$/
	},

	options: {
		fps: 50
	},

	initialize: function(el, options) {
		this._el = el;
		L.Util.extend(this.options, options);

		var easings = L.Transition.EASINGS[this.options.easing];
		this._p1 = new L.Point(0, 0);
		this._p2 = new L.Point(easings[0], easings[1]);
		this._p3 = new L.Point(easings[2], easings[3]);
		this._p4 = new L.Point(1, 1);

		this._step = L.Util.bind(this._step, this);
		this._interval = Math.round(1000 / this.options.fps);
	},

	run: function(props) {
		this._props = {};

		var getters = L.Transition.CUSTOM_PROPS_GETTERS,
			re = L.Transition.UNIT_RE;

		this.fire('start');

		for (var prop in props) {
			if (props.hasOwnProperty(prop)) {
				var p = {};
				if (prop in getters) {
					p.from = getters[prop](this._el);
				} else {
					var matches = this._el.style[prop].match(re);
					p.from = parseFloat(matches[0]);
					p.unit = matches[1];
				}
				p.to = props[prop];
				this._props[prop] = p;
			}
		}

		clearInterval(this._timer);
		this._timer = setInterval(this._step, this._interval);
		this._startTime = L.Transition.getTime();
	},

	_step: function() {
		var time = L.Transition.getTime(),
			elapsed = time - this._startTime,
			duration = this.options.duration * 1000;
		if (elapsed < duration) {
			var percentComplete = this._cubicBezier(elapsed / duration);
			this._runFrame(percentComplete);
		} else {
			this._runFrame(1);
			this._complete();
		}
	},

	_runFrame: function(percentComplete) {
		var setters = L.Transition.CUSTOM_PROPS_SETTERS,
			prop, p, value;

		for (prop in this._props) {
			if (this._props.hasOwnProperty(prop)) {
				p = this._props[prop];
				if (prop in setters) {
					value = p.to.subtract(p.from).multiplyBy(percentComplete).add(p.from);
					setters[prop](this._el, value);
				} else {
					this._el.style[prop] =
							((p.to - p.from) * percentComplete + p.from) + p.unit;
				}
			}
		}
		this.fire('step');
	},

	_complete: function() {
		clearInterval(this._timer);
		this.fire('end');
	},

	_cubicBezier: function(t) {
		var a = Math.pow(1 - t, 3),
			b = 3 * Math.pow(1 - t, 2) * t,
			c = 3 * (1 - t) * Math.pow(t, 2),
			d = Math.pow(t, 3),
			p1 = this._p1.multiplyBy(a),
			p2 = this._p2.multiplyBy(b),
			p3 = this._p3.multiplyBy(c),
			p4 = this._p4.multiplyBy(d);

		return p1.add(p2).add(p3).add(p4).y;
	}
});<|endoftext|>