<commit_before>'use strict'

import { TextTransform } from './text.transform'
import { ImageTransform } from './image.transform'
import { HTMLTransform } from './html.transform'
/**
 * Transforms mimetypes into HTMLElements
 */
class Transformime {

  /**
   * Public constructor
   * @param  {function[]} transformers - list of transformers, in reverse priority order.
   */
  constructor (transformers) {
    // Initialize instance variables.
    this.transformers = []
    this.push(TextTransform)
    this.push(ImageTransform)
    this.push(HTMLTransform)
    if (transformers) transformers.map((transformer) => this.push(transformer))
  }
  /**
   * Transforms a mime bundle, using the richest available representation,
   * into an HTMLElement.
   * @param  {any}      bundle - {mimetype1: data1, mimetype2: data2, ...}
   * @param  {Document} document - Any of window.document, iframe.contentDocument
   * @return {Promise<{mimetype: string, el: HTMLElement}>}
   */
  transform (bundle, document) {
    if (this.transformers.length <= 0) {
      // Empty transformers
      return Promise.reject(new Error('No transformers configured'))
    }

    if (Object.keys(bundle).length <= 0) {
      return Promise.reject(new Error('MIME Bundle empty'))
    }

    let richMimetype
    let richTransformer

    // Choose the last transformer as the most rich
    for (let transformer of this.transformers) {
      if (transformer.mimetype) {
        // Make sure the transformer's mimetype is in array format.
        let transformer_mimetypes = transformer.mimetype
        if (!Array.isArray(transformer_mimetypes)) {
          transformer_mimetypes = [transformer_mimetypes]
        }

        for (let transformer_mimetype of transformer_mimetypes) {
          if (transformer_mimetype in bundle) {
            richMimetype = transformer_mimetype
            richTransformer = transformer
          }
        }
      }
    }

    if (richMimetype && richTransformer) {
      // Don't assume the transformation will return a promise.  Also
      // don't assume the transformation will succeed.
      try {
        return Promise.resolve(richTransformer.call(richTransformer,
          richMimetype, bundle[richMimetype], document)).then(el => {
            return { mimetype: richMimetype, el: el }
          })
      } catch (e) {
        return Promise.reject(e)
      }
    } else {
      return Promise.reject(new Error('Transformer(s) for ' + Object.keys(bundle).join(', ') + ' not found.'))
    }
  }

  /**
   * Deletes all transformers by mimetype.
   * @param {string|string[]} mimetype - mimetype the data type (e.g. text/plain, text/html, image/png)
   */
  del (mimetype) {
    // Convert mimetype to an array.
    let mimetypes = mimetype
    if (!Array.isArray(mimetypes)) {
      mimetypes = [mimetypes]
    }

    // Remove each mimetype.
    for (mimetype of mimetypes) {
      for (let i = 0; i < this.transformers.length; i++) {
        var transformer = this.transformers[i]

        // If the mimetype matches the one we want to remove, remove it.
        if (mimetype === transformer.mimetype) {
          this.transformers.splice(i, 1)
          i--

        // If the mimetype we want to remove is in the list of the
        // mimetypes supported by the transformer, remove it from the list.
        // If the transformer mimetype list is then empty, remove the
        // transformer.
        } else if (Array.isArray(transformer.mimetype) && mimetype in transformer.mimetype) {
          if (transformer.mimetype.length === 1) {
            this.transformers.splice(i, 1)
            i--
          } else {
            transformer.mimetype.splice(transformer.mimetype.indexOf(mimetype), 1)
          }
        }
      }
    }
  }

  /**
   * Gets a transformer matching the mimetype
   * @param {string} mimetype - the data type (e.g. text/plain, text/html, image/png)
   * @return {function} Matching transformer
   */
  get (mimetype) {
    // Loop through the transformers array in reverse.
    for (let i = this.transformers.length - 1; i >= 0; i--) {
      let transformer = this.transformers[i]

      // Get an array of the mimetypes that the transformer supports.
      let transformer_mimetypes = transformer.mimetype
      if (!Array.isArray(transformer_mimetypes)) {
        transformer_mimetypes = [transformer_mimetypes]
      }

      // Check if any of the mimetypes match the one we are looking for.
      for (let transformer_mimetype of transformer_mimetypes) {
        if (mimetype === transformer_mimetype) {
          return transformer
        }
      }
    }
  }

  /**
   * Sets a transformer matching the mimetype
   * @param {string|string[]} mimetype - the data type (e.g. text/plain, text/html, image/png)
   * @param {function} transformer
   * @return {function} inserted transformer function (may be different than arg)
   */
  set (mimetype, transformer) {
    this.del(mimetype)
    return this.push(transformer, mimetype)
  }

  /**
   * Appends a transformer to the transformer list.
   * @param  {function} transformer
   * @param  {string|string[]} mimetype
   * @return {function} inserted transformer function (may be different than arg)
   */
  push (transformer, mimetype) {
    // If the mimetype specified is different than the mimetype of the
    // transformer, make a copy of the transformer and set the new mimetype
    // on the copy.
    let transform = transformer
    if (mimetype && transformer.mimetype !== mimetype) {
      transform = this._proxy(transformer, mimetype)
    }

    // Verify a mimetype is set on the transformer.
    if (!transform.mimetype) throw Error('Could not infer transformer mimetype')

    this.transformers.push(transform)
    return transform
  }

  /**
   * Create a proxy to a transformer, using another mimetype.
   * @param  {function} transformer
   * @param  {string|string[]} mimetype
   * @return {function} transformer
   */
  _proxy (transformer, mimetype) {
    let transform = function (...args) { return transformer.call(this, ...args) }
    transform.mimetype = mimetype
    return transform
  }
}

export {
    Transformime,
    TextTransform,
    TextTransform as TextTransformer,
    ImageTransform,
    ImageTransform as ImageTransformer,
    HTMLTransform,
    HTMLTransform as HTMLTransformer
};
<commit_msg>use forEach instead of map<commit_after>'use strict'

import { TextTransform } from './text.transform'
import { ImageTransform } from './image.transform'
import { HTMLTransform } from './html.transform'
/**
 * Transforms mimetypes into HTMLElements
 */
class Transformime {

  /**
   * Public constructor
   * @param  {function[]} transformers - list of transformers, in reverse priority order.
   */
  constructor (transformers) {
    // Initialize instance variables.
    this.transformers = []
    this.push(TextTransform)
    this.push(ImageTransform)
    this.push(HTMLTransform)
    if (transformers) transformers.forEach((transformer) => { this.push(transformer) })
  }
  /**
   * Transforms a mime bundle, using the richest available representation,
   * into an HTMLElement.
   * @param  {any}      bundle - {mimetype1: data1, mimetype2: data2, ...}
   * @param  {Document} document - Any of window.document, iframe.contentDocument
   * @return {Promise<{mimetype: string, el: HTMLElement}>}
   */
  transform (bundle, document) {
    if (this.transformers.length <= 0) {
      // Empty transformers
      return Promise.reject(new Error('No transformers configured'))
    }

    if (Object.keys(bundle).length <= 0) {
      return Promise.reject(new Error('MIME Bundle empty'))
    }

    let richMimetype
    let richTransformer

    // Choose the last transformer as the most rich
    for (let transformer of this.transformers) {
      if (transformer.mimetype) {
        // Make sure the transformer's mimetype is in array format.
        let transformer_mimetypes = transformer.mimetype
        if (!Array.isArray(transformer_mimetypes)) {
          transformer_mimetypes = [transformer_mimetypes]
        }

        for (let transformer_mimetype of transformer_mimetypes) {
          if (transformer_mimetype in bundle) {
            richMimetype = transformer_mimetype
            richTransformer = transformer
          }
        }
      }
    }

    if (richMimetype && richTransformer) {
      // Don't assume the transformation will return a promise.  Also
      // don't assume the transformation will succeed.
      try {
        return Promise.resolve(richTransformer.call(richTransformer,
          richMimetype, bundle[richMimetype], document)).then(el => {
            return { mimetype: richMimetype, el: el }
          })
      } catch (e) {
        return Promise.reject(e)
      }
    } else {
      return Promise.reject(new Error('Transformer(s) for ' + Object.keys(bundle).join(', ') + ' not found.'))
    }
  }

  /**
   * Deletes all transformers by mimetype.
   * @param {string|string[]} mimetype - mimetype the data type (e.g. text/plain, text/html, image/png)
   */
  del (mimetype) {
    // Convert mimetype to an array.
    let mimetypes = mimetype
    if (!Array.isArray(mimetypes)) {
      mimetypes = [mimetypes]
    }

    // Remove each mimetype.
    for (mimetype of mimetypes) {
      for (let i = 0; i < this.transformers.length; i++) {
        var transformer = this.transformers[i]

        // If the mimetype matches the one we want to remove, remove it.
        if (mimetype === transformer.mimetype) {
          this.transformers.splice(i, 1)
          i--

        // If the mimetype we want to remove is in the list of the
        // mimetypes supported by the transformer, remove it from the list.
        // If the transformer mimetype list is then empty, remove the
        // transformer.
        } else if (Array.isArray(transformer.mimetype) && mimetype in transformer.mimetype) {
          if (transformer.mimetype.length === 1) {
            this.transformers.splice(i, 1)
            i--
          } else {
            transformer.mimetype.splice(transformer.mimetype.indexOf(mimetype), 1)
          }
        }
      }
    }
  }

  /**
   * Gets a transformer matching the mimetype
   * @param {string} mimetype - the data type (e.g. text/plain, text/html, image/png)
   * @return {function} Matching transformer
   */
  get (mimetype) {
    // Loop through the transformers array in reverse.
    for (let i = this.transformers.length - 1; i >= 0; i--) {
      let transformer = this.transformers[i]

      // Get an array of the mimetypes that the transformer supports.
      let transformer_mimetypes = transformer.mimetype
      if (!Array.isArray(transformer_mimetypes)) {
        transformer_mimetypes = [transformer_mimetypes]
      }

      // Check if any of the mimetypes match the one we are looking for.
      for (let transformer_mimetype of transformer_mimetypes) {
        if (mimetype === transformer_mimetype) {
          return transformer
        }
      }
    }
  }

  /**
   * Sets a transformer matching the mimetype
   * @param {string|string[]} mimetype - the data type (e.g. text/plain, text/html, image/png)
   * @param {function} transformer
   * @return {function} inserted transformer function (may be different than arg)
   */
  set (mimetype, transformer) {
    this.del(mimetype)
    return this.push(transformer, mimetype)
  }

  /**
   * Appends a transformer to the transformer list.
   * @param  {function} transformer
   * @param  {string|string[]} mimetype
   * @return {function} inserted transformer function (may be different than arg)
   */
  push (transformer, mimetype) {
    // If the mimetype specified is different than the mimetype of the
    // transformer, make a copy of the transformer and set the new mimetype
    // on the copy.
    let transform = transformer
    if (mimetype && transformer.mimetype !== mimetype) {
      transform = this._proxy(transformer, mimetype)
    }

    // Verify a mimetype is set on the transformer.
    if (!transform.mimetype) throw Error('Could not infer transformer mimetype')

    this.transformers.push(transform)
    return transform
  }

  /**
   * Create a proxy to a transformer, using another mimetype.
   * @param  {function} transformer
   * @param  {string|string[]} mimetype
   * @return {function} transformer
   */
  _proxy (transformer, mimetype) {
    let transform = function (...args) { return transformer.call(this, ...args) }
    transform.mimetype = mimetype
    return transform
  }
}

export {
    Transformime,
    TextTransform,
    TextTransform as TextTransformer,
    ImageTransform,
    ImageTransform as ImageTransformer,
    HTMLTransform,
    HTMLTransform as HTMLTransformer
};
<|endoftext|>


<commit_before>"use strict";

const moment = require("moment");
const _ = require("lodash");
const configuration = require("./config");
const Promise = require("bluebird");

module.exports = class Translation {
  constructor (options) {
    this.config = new configuration(options).getConfiguration();
    this.cache_time = null;
    this.translation = {};
    this.config._LOCALES.map((locale)=> {
      this.translation[locale] = {
        value: {},
        metadata: {
          cache_time : null
        }
      };
    });
    this.spawnTranslations();
  }

  getTranslationByKeyAndLocale (key, dependentKeys, locale, cb) {
    let self = this;
    locale = locale.toLowerCase();

    // If cache can be used, use it to serve translations;
    if (self.canUseCache(locale)) {
      return cb(null, self.fetchKeyFromJSON(key, dependentKeys, locale));
    } else {
      // if cache cannot be used , serve it from previous cache and update it in background.
      if (!_.isEmpty(self.translation[locale].value)) {
        self.downloadTranslationData(locale).then((response) => {
          self.updateCache(locale, response);
        }).catch((e) => {
          console.error(`Error while downloading translations ${locale}, ${e.stack}`);
        });

        try {
          return cb(null, self.fetchKeyFromJSON(key, dependentKeys, locale));
        } catch (e) {
          return cb(e, null);
        };
      } else {
        // If cache cannot be used and no previous cache available download , update cache and serve it.
        self.downloadTranslationData(locale).then((response) => {
          self.updateCache(locale, response);
          return cb(null, self.fetchKeyFromJSON(key, dependentKeys, locale));
        }).catch((e) => {
          console.error(`Error while downloading translations ${locale}, ${e.stack}`);
          return cb(e, null);
        });
      }
    }
  }

  canUseCache (locale) {
    return !_.isEmpty(this.translation[locale].value) &&
        this.translation[locale].metadata.cache_time.clone().add(this.config._CACHE_MINUTES, "minutes").isAfter(moment());
  }

  downloadTranslationData (locale) {
    let self = this;
    return new Promise ((resolve, reject) => {
      self.config._S3.getObject({
        Bucket: self.config._BUCKET,
        Key: `${self.config._WORKSPACE}/${locale}.json`
      }, function (err, data) {
        if (err) {
          return reject(err);
        } else {
          return resolve(JSON.parse(data.Body.toString()));
        }
      });
    });
  }

  fetchKeyFromJSON (key, dependentKeys, locale) {
    let data = {};

    dependentKeys.map((key)=> {
      data[key] = this.translation[locale].value[key];
    });

    data[key] = this.translation[locale].value[key];
    data.key = key;

    return data;
  }

  spawnTranslations () {
    let self = this;
    let alpha = moment();

    console.info(`Spawning Translations started for ${self.config._LOCALES}`);

    Promise.map(self.config._LOCALES, (translationLocale) => {
      return self.downloadTranslationData(translationLocale).then( (transations) => {
        self.updateCache(translationLocale, transations);
        console.info(`Spawning Translations finished for ${translationLocale}`);
      });
    }).then(() => {
      console.info(`Spawning Translations finished for ${self.config._LOCALES} in ${moment().diff(alpha)} ms`);
    }).catch((e) => {
      console.error(`Error while spawning translations ${e.stack}`);
      throw e.stack;
    });
  }

  updateCache(locale, translations) {
    this.translation[locale].va:qlue = translations;
    this.translation[locale].metadata.cache_time = moment();
  }
};<commit_msg>fix typo<commit_after>"use strict";

const moment = require("moment");
const _ = require("lodash");
const configuration = require("./config");
const Promise = require("bluebird");

module.exports = class Translation {
  constructor (options) {
    this.config = new configuration(options).getConfiguration();
    this.cache_time = null;
    this.translation = {};
    this.config._LOCALES.map((locale)=> {
      this.translation[locale] = {
        value: {},
        metadata: {
          cache_time : null
        }
      };
    });
    this.spawnTranslations();
  }

  getTranslationByKeyAndLocale (key, dependentKeys, locale, cb) {
    let self = this;
    locale = locale.toLowerCase();

    // If cache can be used, use it to serve translations;
    if (self.canUseCache(locale)) {
      return cb(null, self.fetchKeyFromJSON(key, dependentKeys, locale));
    } else {
      // if cache cannot be used , serve it from previous cache and update it in background.
      if (!_.isEmpty(self.translation[locale].value)) {
        self.downloadTranslationData(locale).then((response) => {
          self.updateCache(locale, response);
        }).catch((e) => {
          console.error(`Error while downloading translations ${locale}, ${e.stack}`);
        });

        try {
          return cb(null, self.fetchKeyFromJSON(key, dependentKeys, locale));
        } catch (e) {
          return cb(e, null);
        };
      } else {
        // If cache cannot be used and no previous cache available download , update cache and serve it.
        self.downloadTranslationData(locale).then((response) => {
          self.updateCache(locale, response);
          return cb(null, self.fetchKeyFromJSON(key, dependentKeys, locale));
        }).catch((e) => {
          console.error(`Error while downloading translations ${locale}, ${e.stack}`);
          return cb(e, null);
        });
      }
    }
  }

  canUseCache (locale) {
    return !_.isEmpty(this.translation[locale].value) &&
        this.translation[locale].metadata.cache_time.clone().add(this.config._CACHE_MINUTES, "minutes").isAfter(moment());
  }

  downloadTranslationData (locale) {
    let self = this;
    return new Promise ((resolve, reject) => {
      self.config._S3.getObject({
        Bucket: self.config._BUCKET,
        Key: `${self.config._WORKSPACE}/${locale}.json`
      }, function (err, data) {
        if (err) {
          return reject(err);
        } else {
          return resolve(JSON.parse(data.Body.toString()));
        }
      });
    });
  }

  fetchKeyFromJSON (key, dependentKeys, locale) {
    let data = {};

    dependentKeys.map((key)=> {
      data[key] = this.translation[locale].value[key];
    });

    data[key] = this.translation[locale].value[key];
    data.key = key;

    return data;
  }

  spawnTranslations () {
    let self = this;
    let alpha = moment();

    console.info(`Spawning Translations started for ${self.config._LOCALES}`);

    Promise.map(self.config._LOCALES, (translationLocale) => {
      return self.downloadTranslationData(translationLocale).then( (transations) => {
        self.updateCache(translationLocale, transations);
        console.info(`Spawning Translations finished for ${translationLocale}`);
      });
    }).then(() => {
      console.info(`Spawning Translations finished for ${self.config._LOCALES} in ${moment().diff(alpha)} ms`);
    }).catch((e) => {
      console.error(`Error while spawning translations ${e.stack}`);
      throw e.stack;
    });
  }

  updateCache(locale, translations) {
    this.translation[locale].value = translations;
    this.translation[locale].metadata.cache_time = moment();
  }
};<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.menu',
  name: 'VerticalMenu',
  extends: 'foam.u2.View',

  implements: [
    'foam.mlang.Expressions'
  ],

  imports: [
    'currentMenu',
    'menuListener',
    'loginSuccess',
    'menuDAO',
    'pushMenu'
  ],

  requires: [
    'foam.nanos.menu.Menu',
    'foam.nanos.menu.VerticalMenu',
    'foam.dao.ArraySink'
  ],

  css: `
  input {
    width: 220px;
  }

  ^ .side-nav-view {
    font-size: medium!important;
    font-weight: normal;
    display: inline-block;
    position: absolute;
    height: calc(100vh - 80px);
    width: 240px;
    overflow-x: hidden;
    z-index: 100;
    font-size: 26px;
    color: /*%GREY2%*/ #9ba1a6;
    border-right: 1px solid /*%GREY4%*/ #e7eaec;
    background: /*%GREY5%*/ #f5f7fas;
  }

  .foam-u2-search-TextSearchView {
    text-align: center;
    margin: 4px 0;
  }

  ^ .foam-u2-view-TreeViewRow-label {
    font-weight: 300;
  }

  ^ .foam-u2-view-TreeViewRow {
    width: 100%;
  }
  ^ .tree-view-height-manager {
    margin-bottom: 40px;
  }
  `,

  properties: [
    {
      class: 'FObjectProperty',
      of: 'foam.u2.Element',
      name: 'subMenu',
      documentation: 'Used to store selected submenu element after window reload and scroll into parent view'
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'dao_',
      factory: function() {
        return this.menuDAO.orderBy(this.Menu.ORDER);
      }
    },
    {
      class: 'String',
      name: 'menuSearch',
      view: {
        class: 'foam.u2.TextField',
        type: 'search',
        onKey: true
      },
      value: ''
    }
  ],

  methods: [
    function initE() {
      var self = this;

      this
      .addClass(this.myClass())
      .start()
        .addClass('side-nav-view')
        .start()
          .startContext({ data: this })
          .start()
            .add(this.MENU_SEARCH)
            .addClass('foam-u2-search-TextSearchView')
          .end()
          .endContext()
          .start()
            .addClass('tree-view-height-manager')
            .tag({
              class: 'foam.u2.view.TreeView',
              data: self.dao_,
              relationship: foam.nanos.menu.MenuMenuChildrenRelationship,
              startExpanded: true,
              query: self.menuSearch$,
              onClickAddOn: function(data) { self.openMenu(data); },
              formatter: function(data) { this.add(data.label); }
            })
          .end()
        .end()
      .end();
    },

    function openMenu(menu) {
      if ( Object.keys(menu.handler.instance_).length > 0 ) {
        this.pushMenu(menu.id);
        this.menuListener(menu);
      }
    }
  ]
});
<commit_msg>Fixed the CSS label bug<commit_after>/**
 * @license
 * Copyright 2020 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

foam.CLASS({
  package: 'foam.nanos.menu',
  name: 'VerticalMenu',
  extends: 'foam.u2.View',

  implements: [
    'foam.mlang.Expressions'
  ],

  imports: [
    'currentMenu',
    'menuListener',
    'loginSuccess',
    'menuDAO',
    'pushMenu'
  ],

  requires: [
    'foam.nanos.menu.Menu',
    'foam.nanos.menu.VerticalMenu',
    'foam.dao.ArraySink'
  ],

  css: `
  ^ input {
    width: 220px;
  }

  ^ .side-nav-view {
    font-size: medium!important;
    font-weight: normal;
    display: inline-block;
    position: absolute;
    height: calc(100vh - 80px);
    width: 240px;
    overflow-x: hidden;
    z-index: 100;
    font-size: 26px;
    color: /*%GREY2%*/ #9ba1a6;
    border-right: 1px solid /*%GREY4%*/ #e7eaec;
    background: /*%GREY5%*/ #f5f7fas;
  }

  .foam-u2-search-TextSearchView {
    text-align: center;
    margin: 4px 0;
  }

  ^ .foam-u2-view-TreeViewRow-label {
    font-weight: 300;
  }

  ^ .foam-u2-view-TreeViewRow {
    width: 100%;
  }
  ^ .tree-view-height-manager {
    margin-bottom: 40px;
  }
  `,

  properties: [
    {
      class: 'FObjectProperty',
      of: 'foam.u2.Element',
      name: 'subMenu',
      documentation: 'Used to store selected submenu element after window reload and scroll into parent view'
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'dao_',
      factory: function() {
        return this.menuDAO.orderBy(this.Menu.ORDER);
      }
    },
    {
      class: 'String',
      name: 'menuSearch',
      view: {
        class: 'foam.u2.TextField',
        type: 'search',
        onKey: true
      },
      value: ''
    }
  ],

  methods: [
    function initE() {
      var self = this;

      this
      .addClass(this.myClass())
      .start()
        .addClass('side-nav-view')
        .start()
          .startContext({ data: this })
          .start()
            .add(this.MENU_SEARCH)
            .addClass('foam-u2-search-TextSearchView')
          .end()
          .endContext()
          .start()
            .addClass('tree-view-height-manager')
            .tag({
              class: 'foam.u2.view.TreeView',
              data: self.dao_,
              relationship: foam.nanos.menu.MenuMenuChildrenRelationship,
              startExpanded: true,
              query: self.menuSearch$,
              onClickAddOn: function(data) { self.openMenu(data); },
              formatter: function(data) { this.add(data.label); }
            })
          .end()
        .end()
      .end();
    },

    function openMenu(menu) {
      if ( Object.keys(menu.handler.instance_).length > 0 ) {
        this.pushMenu(menu.id);
        this.menuListener(menu);
      }
    }
  ]
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

 foam.CLASS({
  package: 'foam.u2.view',
  name: 'ScrollTableView',
  extends: 'foam.u2.Element',

  requires: [
    'foam.dao.FnSink',
    'foam.graphics.ScrollCView',
    'foam.mlang.sink.Count',
    'foam.u2.view.TableView'
  ],

  properties: [
    {
      class: 'foam.dao.DAOProperty',
      name: 'data'
    },
    {
      class: 'Int',
      name: 'limit',
      value: 18,
      // TODO make this a funciton of the height.
    },
    {
      class: 'Int',
      name: 'skip',
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'scrolledDAO',
      expression: function(data, limit, skip) {
        return data.limit(limit).skip(skip);
      },
    },
    'columns',
    {
      class: 'Int',
      name: 'daoCount'
    },
    'selection'
  ],

  methods: [
    function init() {
      this.onDetach(this.data$proxy.listen(this.FnSink.create({fn:this.onDAOUpdate})));
      this.onDAOUpdate();
    },

    function initE() {
      // TODO probably shouldn't be using a table.
      this.start('table').
        on('wheel', this.onWheel).
        start('tr').
          start('td').
            style({ 'vertical-align': 'top' }).
            start(this.TableView, {data$: this.scrolledDAO$, columns: this.columns, selection$: this.selection$}).
            end().
          end().
          start('td').style({ 'vertical-align': 'top' }).
            add(this.ScrollCView.create({
              value$: this.skip$,
              extent$: this.limit$,
              height: 40*18+41, // TODO use window height.
              width: 15,
              size$: this.daoCount$,
            })).
          end().
        end().
      end();
    }
  ],

  listeners: [
    {
      name: 'onWheel',
      code: function(e) {
        var negative = e.deltaY < 0;
        // Convert to rows, rounding up. (Therefore minumum 1.)
        var rows = Math.ceil(Math.abs(e.deltaY) / /*self.rowHeight*/ 40);
        this.skip = Math.max(0, this.skip + (negative ? -rows : rows));
        e.preventDefault();
      }
    },
    {
      // TODO: Avoid onDAOUpdate approaches.
      name: 'onDAOUpdate',
      isFramed: true,
      code: function() {
        var self = this;
        this.data$proxy.select(this.Count.create()).then(function(s) {
          self.daoCount = s.value;
        })
      },
    },
  ]
});
<commit_msg>Make ScrollTableView scrollbar wider.<commit_after>/**
 * @license
 * Copyright 2017 The FOAM Authors. All Rights Reserved.
 * http://www.apache.org/licenses/LICENSE-2.0
 */

 foam.CLASS({
  package: 'foam.u2.view',
  name: 'ScrollTableView',
  extends: 'foam.u2.Element',

  requires: [
    'foam.dao.FnSink',
    'foam.graphics.ScrollCView',
    'foam.mlang.sink.Count',
    'foam.u2.view.TableView'
  ],

  properties: [
    {
      class: 'foam.dao.DAOProperty',
      name: 'data'
    },
    {
      class: 'Int',
      name: 'limit',
      value: 18,
      // TODO make this a funciton of the height.
    },
    {
      class: 'Int',
      name: 'skip',
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'scrolledDAO',
      expression: function(data, limit, skip) {
        return data.limit(limit).skip(skip);
      },
    },
    'columns',
    {
      class: 'Int',
      name: 'daoCount'
    },
    'selection'
  ],

  methods: [
    function init() {
      this.onDetach(this.data$proxy.listen(this.FnSink.create({fn:this.onDAOUpdate})));
      this.onDAOUpdate();
    },

    function initE() {
      // TODO probably shouldn't be using a table.
      this.start('table').
        on('wheel', this.onWheel).
        start('tr').
          start('td').
            style({ 'vertical-align': 'top' }).
            start(this.TableView, {data$: this.scrolledDAO$, columns: this.columns, selection$: this.selection$}).
            end().
          end().
          start('td').style({ 'vertical-align': 'top' }).
            add(this.ScrollCView.create({
              value$: this.skip$,
              extent$: this.limit$,
              height: 40*18+41, // TODO use window height.
              width: 18,
              size$: this.daoCount$,
            })).
          end().
        end().
      end();
    }
  ],

  listeners: [
    {
      name: 'onWheel',
      code: function(e) {
        var negative = e.deltaY < 0;
        // Convert to rows, rounding up. (Therefore minumum 1.)
        var rows = Math.ceil(Math.abs(e.deltaY) / /*self.rowHeight*/ 40);
        this.skip = Math.max(0, this.skip + (negative ? -rows : rows));
        e.preventDefault();
      }
    },
    {
      // TODO: Avoid onDAOUpdate approaches.
      name: 'onDAOUpdate',
      isFramed: true,
      code: function() {
        var self = this;
        this.data$proxy.select(this.Count.create()).then(function(s) {
          self.daoCount = s.value;
        })
      },
    },
  ]
});
<|endoftext|>


<commit_before>import random from '../core/random';
import words from '../generators/words';
import utils from '../core/utils';
import optionAPI from '../api/option';

// fallback generator
const anyType = { type: ['string', 'number', 'integer', 'boolean'] };

// TODO provide types
function objectType(value, path, resolve, traverseCallback) {
  const props = {};

  const properties = value.properties || {};
  const patternProperties = value.patternProperties || {};
  const requiredProperties = typeof value.required === 'boolean' ? [] : (value.required || []).slice();
  const allowsAdditional = value.additionalProperties !== false;

  const propertyKeys = Object.keys(properties);
  const patternPropertyKeys = Object.keys(patternProperties);
  const optionalProperties = propertyKeys.concat(patternPropertyKeys).reduce((_response, _key) => {
    if (requiredProperties.indexOf(_key) === -1) _response.push(_key);
    return _response;
  }, []);
  const allProperties = requiredProperties.concat(optionalProperties);

  const additionalProperties = allowsAdditional // eslint-disable-line
    ? (value.additionalProperties === true ? anyType : value.additionalProperties)
    : value.additionalProperties;

  if (!allowsAdditional
    && propertyKeys.length === 0
    && patternPropertyKeys.length === 0
    && utils.hasProperties(value, 'minProperties', 'maxProperties', 'dependencies', 'required')
  ) {
    // just nothing
    return null;
  }

  if (optionAPI('requiredOnly') === true) {
    requiredProperties.forEach(key => {
      if (properties[key]) {
        props[key] = properties[key];
      }
    });

    return traverseCallback(props, path.concat(['properties']), resolve);
  }

  const optionalsProbability = optionAPI('alwaysFakeOptionals') === true ? 1.0 : optionAPI('optionalsProbability');
  const fixedProbabilities = optionAPI('alwaysFakeOptionals') || optionAPI('fixedProbabilities') || false;
  const ignoreProperties = optionAPI('ignoreProperties') || [];

  const min = Math.max(value.minProperties || 0, requiredProperties.length);
  const max = value.maxProperties || (allProperties.length + (allowsAdditional ? random.number(1, 5) : 0));

  let neededExtras = Math.max(0, min - requiredProperties.length);

  if (allProperties.length === 1 && !requiredProperties.length) {
    neededExtras = random.number(neededExtras, allProperties.length + (allProperties.length - min));
  }

  if (optionalsProbability !== false) {
    if (fixedProbabilities === true) {
      neededExtras = Math.round((min - requiredProperties.length) + (optionalsProbability * (allProperties.length - min)));
    } else {
      neededExtras = random.number(min - requiredProperties.length, optionalsProbability * (allProperties.length - min));
    }
  }

  const extraPropertiesRandomOrder = random.shuffle(optionalProperties).slice(0, neededExtras);
  const extraProperties = optionalProperties.filter(_item => {
    return extraPropertiesRandomOrder.indexOf(_item) !== -1;
  });

  // properties are read from right-to-left
  const _props = requiredProperties.concat(extraProperties).slice(0, max);
  const _defns = [];

  if (value.dependencies) {
    Object.keys(value.dependencies).forEach(prop => {
      const _required = value.dependencies[prop];

      if (_props.indexOf(prop) !== -1) {
        if (Array.isArray(_required)) {
          // property-dependencies
          _required.forEach(sub => {
            if (_props.indexOf(sub) === -1) {
              _props.push(sub);
            }
          });
        } else {
          _defns.push(_required);
        }
      }
    });

    // schema-dependencies
    if (_defns.length) {
      delete value.dependencies;

      return traverseCallback({
        allOf: _defns.concat(value),
      }, path.concat(['properties']), resolve);
    }
  }

  const skipped = [];
  const missing = [];

  _props.forEach(key => {
    for (let i = 0; i < ignoreProperties.length; i += 1) {
      if ((ignoreProperties[i] instanceof RegExp && ignoreProperties[i].test(key))
        || (typeof ignoreProperties[i] === 'string' && ignoreProperties[i] === key)
        || (typeof ignoreProperties[i] === 'function' && ignoreProperties[i](properties[key], key))) {
        skipped.push(key);
        return;
      }
    }

    if (additionalProperties === false) {
      if (requiredProperties.indexOf(key) !== -1) {
        props[key] = properties[key];
      }
    }

    if (properties[key]) {
      props[key] = properties[key];
    }

    let found;

    // then try patternProperties
    patternPropertyKeys.forEach(_key => {
      if (key.match(new RegExp(_key))) {
        found = true;

        if (props[key]) {
          utils.merge(props[key], patternProperties[_key]);
        } else {
          props[random.randexp(key)] = patternProperties[_key];
        }
      }
    });

    if (!found) {
      // try patternProperties again,
      const subschema = patternProperties[key] || additionalProperties;

      // FIXME: allow anyType as fallback when no subschema is given?

      if (subschema && additionalProperties !== false) {
        // otherwise we can use additionalProperties?
        props[patternProperties[key] ? random.randexp(key) : key] = properties[key] || subschema;
      } else {
        missing.push(key);
      }
    }
  });

  const fillProps = optionAPI('fillProperties');
  const reuseProps = optionAPI('reuseProperties');

  // discard already ignored props if they're not required to be filled...
  let current = Object.keys(props).length + (fillProps ? 0 : skipped.length);

  // generate dynamic suffix for additional props...
  const hash = suffix => random.randexp(`_?[_a-f\\d]{1,3}${suffix ? '\\$?' : ''}`);

  function get(from) {
    let one;

    do {
      if (!from.length) break;
      one = from.shift();
    } while (props[one]);

    return one;
  }

  while (fillProps) {
    if (!(patternPropertyKeys.length || allowsAdditional)) {
      break;
    }

    if (current >= min) {
      break;
    }

    if (allowsAdditional) {
      if (reuseProps && ((propertyKeys.length - current) > min)) {
        let count = 0;
        let key;

        do {
          count += 1;

          // skip large objects
          if (count > 1000) {
            break;
          }

          key = get(requiredProperties) || random.pick(propertyKeys);
        } while (typeof props[key] !== 'undefined');

        if (typeof props[key] === 'undefined') {
          props[key] = properties[key];
          current += 1;
        }
      } else if (patternPropertyKeys.length && !additionalProperties) {
        const prop = random.pick(patternPropertyKeys);
        const word = random.randexp(prop);

        if (!props[word]) {
          props[word] = patternProperties[prop];
          current += 1;
        }
      } else {
        const word = get(requiredProperties) || (words(1) + hash());

        if (!props[word]) {
          props[word] = additionalProperties || anyType;
          current += 1;
        }
      }
    }

    for (let i = 0; current < min && i < patternPropertyKeys.length; i += 1) {
      const _key = patternPropertyKeys[i];
      const word = random.randexp(_key);

      if (!props[word]) {
        props[word] = patternProperties[_key];
        current += 1;
      }
    }
  }

  // fill up-to this value and no more!
  if (requiredProperties.length === 0 && (!allowsAdditional || optionalsProbability === false)) {
    const maximum = random.number(min, max);

    for (; current < maximum;) {
      const word = get(propertyKeys);

      if (word) {
        props[word] = properties[word];
      }

      current += 1;
    }
  }

  return traverseCallback(props, path.concat(['properties']), resolve);
}

export default objectType;
<commit_msg>Generate enough props from min to all-props; fix<commit_after>import random from '../core/random';
import words from '../generators/words';
import utils from '../core/utils';
import optionAPI from '../api/option';

// fallback generator
const anyType = { type: ['string', 'number', 'integer', 'boolean'] };

// TODO provide types
function objectType(value, path, resolve, traverseCallback) {
  const props = {};

  const properties = value.properties || {};
  const patternProperties = value.patternProperties || {};
  const requiredProperties = typeof value.required === 'boolean' ? [] : (value.required || []).slice();
  const allowsAdditional = value.additionalProperties !== false;

  const propertyKeys = Object.keys(properties);
  const patternPropertyKeys = Object.keys(patternProperties);
  const optionalProperties = propertyKeys.concat(patternPropertyKeys).reduce((_response, _key) => {
    if (requiredProperties.indexOf(_key) === -1) _response.push(_key);
    return _response;
  }, []);
  const allProperties = requiredProperties.concat(optionalProperties);

  const additionalProperties = allowsAdditional // eslint-disable-line
    ? (value.additionalProperties === true ? anyType : value.additionalProperties)
    : value.additionalProperties;

  if (!allowsAdditional
    && propertyKeys.length === 0
    && patternPropertyKeys.length === 0
    && utils.hasProperties(value, 'minProperties', 'maxProperties', 'dependencies', 'required')
  ) {
    // just nothing
    return null;
  }

  if (optionAPI('requiredOnly') === true) {
    requiredProperties.forEach(key => {
      if (properties[key]) {
        props[key] = properties[key];
      }
    });

    return traverseCallback(props, path.concat(['properties']), resolve);
  }

  const optionalsProbability = optionAPI('alwaysFakeOptionals') === true ? 1.0 : optionAPI('optionalsProbability');
  const fixedProbabilities = optionAPI('alwaysFakeOptionals') || optionAPI('fixedProbabilities') || false;
  const ignoreProperties = optionAPI('ignoreProperties') || [];

  const min = Math.max(value.minProperties || 0, random.number(requiredProperties.length, allProperties.length));
  const max = value.maxProperties || (allProperties.length + (allowsAdditional ? random.number(1, 5) : 0));

  let neededExtras = Math.max(0, min - requiredProperties.length);

  if (allProperties.length === 1 && !requiredProperties.length) {
    neededExtras = random.number(neededExtras, allProperties.length + (allProperties.length - min));
  }

  if (optionalsProbability !== false) {
    if (fixedProbabilities === true) {
      neededExtras = Math.round((min - requiredProperties.length) + (optionalsProbability * (allProperties.length - min)));
    } else {
      neededExtras = random.number(min - requiredProperties.length, optionalsProbability * (allProperties.length - min));
    }
  }

  const extraPropertiesRandomOrder = random.shuffle(optionalProperties).slice(0, neededExtras);
  const extraProperties = optionalProperties.filter(_item => {
    return extraPropertiesRandomOrder.indexOf(_item) !== -1;
  });

  // properties are read from right-to-left
  const _props = requiredProperties.concat(extraProperties).slice(0, max);
  const _defns = [];

  if (value.dependencies) {
    Object.keys(value.dependencies).forEach(prop => {
      const _required = value.dependencies[prop];

      if (_props.indexOf(prop) !== -1) {
        if (Array.isArray(_required)) {
          // property-dependencies
          _required.forEach(sub => {
            if (_props.indexOf(sub) === -1) {
              _props.push(sub);
            }
          });
        } else {
          _defns.push(_required);
        }
      }
    });

    // schema-dependencies
    if (_defns.length) {
      delete value.dependencies;

      return traverseCallback({
        allOf: _defns.concat(value),
      }, path.concat(['properties']), resolve);
    }
  }

  const skipped = [];
  const missing = [];

  _props.forEach(key => {
    for (let i = 0; i < ignoreProperties.length; i += 1) {
      if ((ignoreProperties[i] instanceof RegExp && ignoreProperties[i].test(key))
        || (typeof ignoreProperties[i] === 'string' && ignoreProperties[i] === key)
        || (typeof ignoreProperties[i] === 'function' && ignoreProperties[i](properties[key], key))) {
        skipped.push(key);
        return;
      }
    }

    if (additionalProperties === false) {
      if (requiredProperties.indexOf(key) !== -1) {
        props[key] = properties[key];
      }
    }

    if (properties[key]) {
      props[key] = properties[key];
    }

    let found;

    // then try patternProperties
    patternPropertyKeys.forEach(_key => {
      if (key.match(new RegExp(_key))) {
        found = true;

        if (props[key]) {
          utils.merge(props[key], patternProperties[_key]);
        } else {
          props[random.randexp(key)] = patternProperties[_key];
        }
      }
    });

    if (!found) {
      // try patternProperties again,
      const subschema = patternProperties[key] || additionalProperties;

      // FIXME: allow anyType as fallback when no subschema is given?

      if (subschema && additionalProperties !== false) {
        // otherwise we can use additionalProperties?
        props[patternProperties[key] ? random.randexp(key) : key] = properties[key] || subschema;
      } else {
        missing.push(key);
      }
    }
  });

  const fillProps = optionAPI('fillProperties');
  const reuseProps = optionAPI('reuseProperties');

  // discard already ignored props if they're not required to be filled...
  let current = Object.keys(props).length + (fillProps ? 0 : skipped.length);

  // generate dynamic suffix for additional props...
  const hash = suffix => random.randexp(`_?[_a-f\\d]{1,3}${suffix ? '\\$?' : ''}`);

  function get(from) {
    let one;

    do {
      if (!from.length) break;
      one = from.shift();
    } while (props[one]);

    return one;
  }

  while (fillProps) {
    if (!(patternPropertyKeys.length || allowsAdditional)) {
      break;
    }

    if (current >= min) {
      break;
    }

    if (allowsAdditional) {
      if (reuseProps && ((propertyKeys.length - current) > min)) {
        let count = 0;
        let key;

        do {
          count += 1;

          // skip large objects
          if (count > 1000) {
            break;
          }

          key = get(requiredProperties) || random.pick(propertyKeys);
        } while (typeof props[key] !== 'undefined');

        if (typeof props[key] === 'undefined') {
          props[key] = properties[key];
          current += 1;
        }
      } else if (patternPropertyKeys.length && !additionalProperties) {
        const prop = random.pick(patternPropertyKeys);
        const word = random.randexp(prop);

        if (!props[word]) {
          props[word] = patternProperties[prop];
          current += 1;
        }
      } else {
        const word = get(requiredProperties) || (words(1) + hash());

        if (!props[word]) {
          props[word] = additionalProperties || anyType;
          current += 1;
        }
      }
    }

    for (let i = 0; current < min && i < patternPropertyKeys.length; i += 1) {
      const _key = patternPropertyKeys[i];
      const word = random.randexp(_key);

      if (!props[word]) {
        props[word] = patternProperties[_key];
        current += 1;
      }
    }
  }

  // fill up-to this value and no more!
  if (requiredProperties.length === 0 && (!allowsAdditional || optionalsProbability === false)) {
    const maximum = random.number(min, max);

    for (; current < maximum;) {
      const word = get(propertyKeys);

      if (word) {
        props[word] = properties[word];
      }

      current += 1;
    }
  }

  return traverseCallback(props, path.concat(['properties']), resolve);
}

export default objectType;
<|endoftext|>


<commit_before>/* @flow */

'use strict';

const BaseType = require('./base');

class StringType extends BaseType {

    apply (val: string): any {
        this.set(val);
    }

    set (val: ?string): Object {
        super.set((val) ? String(val) : null);

        return this;
    }

}

module.exports = StringType;
<commit_msg>returning this on string apply<commit_after>/* @flow */

'use strict';

const BaseType = require('./base');

class StringType extends BaseType {

    apply (val: string): any {
        return this.set(val);
    }

    set (val: ?string): Object {
        super.set((val) ? String(val) : null);

        return this;
    }

}

module.exports = StringType;
<|endoftext|>


<commit_before>import { Geometry } from 'three/core/Geometry';
import { LineBasicMaterial } from 'three/materials/LineBasicMaterial';
import { Vector3 } from 'three/math/Vector3';
import { LineSegments } from 'three/objects/LineSegments';

export default class Crosshair extends LineSegments {
  constructor() {
    const geometry = createGeometry(0.05);
    const material = createMaterial();
    super(geometry, material);

    this.size = 0.05;
    this.selected = false;
    this.timer = 0;
    this.timeLimit = 30;
  }

  update(selector) {
    // TODO: Rewrite this animation using tweens.

    if (!this.selected && selector.isSelectPressed && selector.selected) {
      this.selected = true;
    }
    else if (this.selected && this.timer < this.timeLimit) {
      this.timer += 3;
      this.size += 0.002;
      this.updateGeometry(this.size);
    }
    else if (this.selected) {
      this.size = 0.05;
      this.updateGeometry(this.size);
      this.selected = false;
      this.timer = 0;
    }
  }

  updateGeometry(size) {
    const halfSize = size / 2;
    this.geometry.dynamic = true;
    this.geometry.vertices[0] = new Vector3(0, halfSize, 0);
    this.geometry.vertices[1] = new Vector3(0, -halfSize, 0);
    this.geometry.vertices[2] = new Vector3(-halfSize, 0, 0);
    this.geometry.vertices[3] = new Vector3(halfSize, 0, 0);
    this.geometry.verticesNeedUpdate = true;
  }

}

function createMaterial() {
  return new LineBasicMaterial({
    color: '#fff',
    linewidth: 2,
    linecap: 'round',
    linejoin: 'round',
    opacity: 0.25,
    transparent: true,
  });
}

function createGeometry(size) {
  const geometry = new Geometry();
  const halfSize = size / 2;
  geometry.vertices.push(new Vector3(0, halfSize, 0));
  geometry.vertices.push(new Vector3(0, -halfSize, 0));
  geometry.vertices.push(new Vector3(-halfSize, 0, 0));
  geometry.vertices.push(new Vector3(halfSize, 0, 0));
  return geometry;
}

<commit_msg>Updated crosshair to use scaling instead of dynamic geometry<commit_after>import { Geometry } from 'three/core/Geometry';
import { LineBasicMaterial } from 'three/materials/LineBasicMaterial';
import { Vector3 } from 'three/math/Vector3';
import { LineSegments } from 'three/objects/LineSegments';

export default class Crosshair extends LineSegments {
  constructor() {
    const geometry = createGeometry(0.05);
    const material = createMaterial();
    super(geometry, material);

    this.scaleStep = 0.05;
    this.selected = false;
    this.timer = 0;
    this.timeLimit = 30;
  }

  update(selector) {
    // TODO: Rewrite this animation using tweens.

    if (!this.selected && selector.isSelectPressed && selector.selected) {
      this.selected = true;
    }
    else if (this.selected && this.timer < this.timeLimit) {
      this.timer += 3;
      this.scale.addScalar(this.scaleStep);
    }
    else if (this.selected) {
      this.scale.set(1, 1, 1);
      this.selected = false;
      this.timer = 0;
    }
  }
}

function createMaterial() {
  return new LineBasicMaterial({
    color: '#fff',
    linewidth: 2,
    linecap: 'round',
    linejoin: 'round',
    opacity: 0.25,
    transparent: true,
  });
}

function createGeometry(size) {
  const geometry = new Geometry();
  const halfSize = size / 2;
  geometry.vertices.push(new Vector3(0, halfSize, 0));
  geometry.vertices.push(new Vector3(0, -halfSize, 0));
  geometry.vertices.push(new Vector3(-halfSize, 0, 0));
  geometry.vertices.push(new Vector3(halfSize, 0, 0));
  return geometry;
}

<|endoftext|>


<commit_before>'use strict';

var memoize = require('./memoize');
var is = require('../is');

module.exports = {

  camel2dash: memoize( function( str ){
    var ret = [];

    for( var i = 0; i < str.length; i++ ){
      var ch = str[i];
      var chLowerCase = ch.toLowerCase();
      var isUpperCase = ch !== chLowerCase;

      if( isUpperCase ){
        ret.push( '-' );
        ret.push( chLowerCase );
      } else {
        ret.push( ch );
      }
    }

    var noUpperCases = ret.length === str.length;
    if( noUpperCases ){ return str; } // cheaper than .join()

    return ret.join('');
  } ),

  dash2camel: memoize( function( str ){
    var ret = [];
    var nextIsUpper = false;

    for( var i = 0; i < str.length; i++ ){
      var ch = str[i];
      var isDash = ch === '-';

      if( isDash ){
        nextIsUpper = true;
      } else {
        if( nextIsUpper ){
          ret.push( ch.toUpperCase() );
        } else {
          ret.push( ch );
        }

        nextIsUpper = false;
      }
    }

    return ret.join('');
  } ),

  capitalize: function(str){
    if( is.emptyString(str) ){
      return str;
    }

    return str.charAt(0).toUpperCase() + str.substring(1);
  }

}
<commit_msg>refactor<commit_after>'use strict';

var memoize = require('./memoize');
var is = require('../is');

module.exports = {

  camel2dash: memoize( function( str ){
    return str.replace(/([A-Z])/g, function( v ){
      return '-' + v.toLowerCase();
    });
  } ),

  dash2camel: memoize( function( str ){
    return str.replace(/(-\w)/g, function( v ){
      return v[1].toUpperCase();
    });
  } ),

  capitalize: function(str){
    if( is.emptyString(str) ){
      return str;
    }

    return str.charAt(0).toUpperCase() + str.substring(1);
  }

}
<|endoftext|>


<commit_before>/* eslint
  global-require: 0,
  import/no-mutable-exports: 0,
  import/no-unresolved: 0,
  react/no-deprecated: 0,
  react/no-render-return-value: 0,
*/

import objectAssign from 'object.assign';
import { REACT013, REACT155 } from './version';

let TestUtils;
let createShallowRenderer;
let renderToStaticMarkup;
let renderIntoDocument;
let findDOMNode;
let childrenToArray;
let renderWithOptions;
let unmountComponentAtNode;
let batchedUpdates;
let shallowRendererFactory;

const React = require('react');

if (REACT013) {
  renderToStaticMarkup = React.renderToStaticMarkup;
  /* eslint-disable react/no-deprecated */
  findDOMNode = React.findDOMNode;
  unmountComponentAtNode = React.unmountComponentAtNode;
  /* eslint-enable react/no-deprecated */
  TestUtils = require('react/addons').addons.TestUtils;
  batchedUpdates = require('react/addons').addons.batchedUpdates;
  const ReactContext = require('react/lib/ReactContext');

  // Shallow rendering in 0.13 did not properly support context. This function provides a shim
  // around `TestUtils.createRenderer` that instead returns a ShallowRenderer that actually
  // works with context. See https://github.com/facebook/react/issues/3721 for more details.
  createShallowRenderer = function createRendererCompatible() {
    const renderer = TestUtils.createRenderer();
    renderer.render = (originalRender => function contextCompatibleRender(node, context = {}) {
      ReactContext.current = context;
      originalRender.call(this, React.createElement(node.type, node.props), context);
      ReactContext.current = {};
      return renderer.getRenderOutput();
    })(renderer.render);
    return renderer;
  };
  renderIntoDocument = TestUtils.renderIntoDocument;
  // this fixes some issues in React 0.13 with setState and jsdom...
  // see issue: https://github.com/airbnb/enzyme/issues/27
  require('react/lib/ExecutionEnvironment').canUseDOM = true;

  // in 0.13, a Children.toArray function was not exported. Make our own instead.
  childrenToArray = (children) => {
    const results = [];
    if (children !== undefined && children !== null && children !== false) {
      React.Children.forEach(children, (el) => {
        if (el !== undefined && el !== null && el !== false) {
          results.push(el);
        }
      });
    }
    return results;
  };

  renderWithOptions = (node, options) => {
    if (options.attachTo) {
      return React.render(node, options.attachTo);
    }
    return TestUtils.renderIntoDocument(node);
  };
} else {
  let ReactDOM;

  try {
    // eslint-disable-next-line import/no-extraneous-dependencies
    ReactDOM = require('react-dom');
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(
      'react-dom is an implicit dependency in order to support react@0.13-14. ' +
      'Please add the appropriate version to your devDependencies. ' +
      'See https://github.com/airbnb/enzyme#installation',
    );
    throw e;
  }

  // eslint-disable-next-line import/no-extraneous-dependencies
  renderToStaticMarkup = require('react-dom/server').renderToStaticMarkup;

  findDOMNode = ReactDOM.findDOMNode;
  unmountComponentAtNode = ReactDOM.unmountComponentAtNode;
  batchedUpdates = ReactDOM.unstable_batchedUpdates;
  // We require the testutils, but they don't come with 0.14 out of the box, so we
  // require them here through this node module. The bummer is that we are not able
  // to list this as a dependency in package.json and have 0.13 work properly.
  // As a result, right now this is basically an implicit dependency.
  try {
    try {
      // This is for react v15.5 and up...

      // eslint-disable-next-line import/no-extraneous-dependencies
      TestUtils = require('react-dom/test-utils');
      // eslint-disable-next-line import/no-extraneous-dependencies
      shallowRendererFactory = require('react-test-renderer/shallow').createRenderer;
    } catch (e) {
      // This is for react < v15.5.  Note that users who have `react^15.4.x` in their package.json
      // will arrive here, too.  They need to upgrade.  React will print a nice warning letting
      // them know they need to upgrade, though, so we're good.  Also note we explicitly do not
      // use TestUtils from react-dom/test-utils here, mainly so the user still gets a warning for
      // requiring 'react-addons-test-utils', which lets them know there's action required.

      // eslint-disable-next-line import/no-extraneous-dependencies
      TestUtils = require('react-addons-test-utils');
      shallowRendererFactory = TestUtils.createRenderer;
    }
  } catch (e) {
    if (REACT155) {
      console.error( // eslint-disable-line no-console
        'react-dom@15.5+ and react-test-renderer are implicit dependencies when using' +
        'react@15.5+ with enzyme. Please add the appropriate version to your' +
        'devDependencies. See https://github.com/airbnb/enzyme#installation',
      );
    } else {
      console.error( // eslint-disable-line no-console
        'react-addons-test-utils is an implicit dependency in order to support react@0.13-14. ' +
        'Please add the appropriate version to your devDependencies. ' +
        'See https://github.com/airbnb/enzyme#installation',
      );
    }
    throw e;
  }

  // Shallow rendering changed from 0.13 => 0.14 in such a way that
  // 0.14 now does not allow shallow rendering of native DOM elements.
  // This is mainly because the result of such a call should not realistically
  // be any different than the JSX you passed in (result of `React.createElement`.
  // In order to maintain the same behavior across versions, this function
  // is essentially a replacement for `TestUtils.createRenderer` that doesn't use
  // shallow rendering when it's just a DOM element.
  createShallowRenderer = function createRendererCompatible() {
    const renderer = shallowRendererFactory();
    const originalRender = renderer.render;
    const originalRenderOutput = renderer.getRenderOutput;
    let isDOM = false;
    let cachedNode;
    return objectAssign(renderer, {
      render(node, context) {
        /* eslint consistent-return: 0 */
        if (typeof node.type === 'string') {
          isDOM = true;
          cachedNode = node;
        } else {
          isDOM = false;
          return originalRender.call(this, node, context);
        }
      },
      getRenderOutput() {
        if (isDOM) {
          return cachedNode;
        }
        return originalRenderOutput.call(this);
      },
    });
  };
  renderIntoDocument = TestUtils.renderIntoDocument;
  childrenToArray = React.Children.toArray;

  renderWithOptions = (node, options) => {
    if (options.attachTo) {
      return ReactDOM.render(node, options.attachTo);
    }
    return TestUtils.renderIntoDocument(node);
  };
}

function isDOMComponentElement(inst) {
  return React.isValidElement(inst) && typeof inst.type === 'string';
}

const {
  mockComponent,
  isElement,
  isElementOfType,
  isDOMComponent,
  isCompositeComponent,
  isCompositeComponentWithType,
  isCompositeComponentElement,
  Simulate,
  findAllInRenderedTree,
} = TestUtils;

export {
  createShallowRenderer,
  renderToStaticMarkup,
  renderIntoDocument,
  mockComponent,
  isElement,
  isElementOfType,
  isDOMComponent,
  isDOMComponentElement,
  isCompositeComponent,
  isCompositeComponentWithType,
  isCompositeComponentElement,
  Simulate,
  findDOMNode,
  findAllInRenderedTree,
  childrenToArray,
  renderWithOptions,
  unmountComponentAtNode,
  batchedUpdates,
};
<commit_msg>Added missing space after a "your" in react-compat<commit_after>/* eslint
  global-require: 0,
  import/no-mutable-exports: 0,
  import/no-unresolved: 0,
  react/no-deprecated: 0,
  react/no-render-return-value: 0,
*/

import objectAssign from 'object.assign';
import { REACT013, REACT155 } from './version';

let TestUtils;
let createShallowRenderer;
let renderToStaticMarkup;
let renderIntoDocument;
let findDOMNode;
let childrenToArray;
let renderWithOptions;
let unmountComponentAtNode;
let batchedUpdates;
let shallowRendererFactory;

const React = require('react');

if (REACT013) {
  renderToStaticMarkup = React.renderToStaticMarkup;
  /* eslint-disable react/no-deprecated */
  findDOMNode = React.findDOMNode;
  unmountComponentAtNode = React.unmountComponentAtNode;
  /* eslint-enable react/no-deprecated */
  TestUtils = require('react/addons').addons.TestUtils;
  batchedUpdates = require('react/addons').addons.batchedUpdates;
  const ReactContext = require('react/lib/ReactContext');

  // Shallow rendering in 0.13 did not properly support context. This function provides a shim
  // around `TestUtils.createRenderer` that instead returns a ShallowRenderer that actually
  // works with context. See https://github.com/facebook/react/issues/3721 for more details.
  createShallowRenderer = function createRendererCompatible() {
    const renderer = TestUtils.createRenderer();
    renderer.render = (originalRender => function contextCompatibleRender(node, context = {}) {
      ReactContext.current = context;
      originalRender.call(this, React.createElement(node.type, node.props), context);
      ReactContext.current = {};
      return renderer.getRenderOutput();
    })(renderer.render);
    return renderer;
  };
  renderIntoDocument = TestUtils.renderIntoDocument;
  // this fixes some issues in React 0.13 with setState and jsdom...
  // see issue: https://github.com/airbnb/enzyme/issues/27
  require('react/lib/ExecutionEnvironment').canUseDOM = true;

  // in 0.13, a Children.toArray function was not exported. Make our own instead.
  childrenToArray = (children) => {
    const results = [];
    if (children !== undefined && children !== null && children !== false) {
      React.Children.forEach(children, (el) => {
        if (el !== undefined && el !== null && el !== false) {
          results.push(el);
        }
      });
    }
    return results;
  };

  renderWithOptions = (node, options) => {
    if (options.attachTo) {
      return React.render(node, options.attachTo);
    }
    return TestUtils.renderIntoDocument(node);
  };
} else {
  let ReactDOM;

  try {
    // eslint-disable-next-line import/no-extraneous-dependencies
    ReactDOM = require('react-dom');
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(
      'react-dom is an implicit dependency in order to support react@0.13-14. ' +
      'Please add the appropriate version to your devDependencies. ' +
      'See https://github.com/airbnb/enzyme#installation',
    );
    throw e;
  }

  // eslint-disable-next-line import/no-extraneous-dependencies
  renderToStaticMarkup = require('react-dom/server').renderToStaticMarkup;

  findDOMNode = ReactDOM.findDOMNode;
  unmountComponentAtNode = ReactDOM.unmountComponentAtNode;
  batchedUpdates = ReactDOM.unstable_batchedUpdates;
  // We require the testutils, but they don't come with 0.14 out of the box, so we
  // require them here through this node module. The bummer is that we are not able
  // to list this as a dependency in package.json and have 0.13 work properly.
  // As a result, right now this is basically an implicit dependency.
  try {
    try {
      // This is for react v15.5 and up...

      // eslint-disable-next-line import/no-extraneous-dependencies
      TestUtils = require('react-dom/test-utils');
      // eslint-disable-next-line import/no-extraneous-dependencies
      shallowRendererFactory = require('react-test-renderer/shallow').createRenderer;
    } catch (e) {
      // This is for react < v15.5.  Note that users who have `react^15.4.x` in their package.json
      // will arrive here, too.  They need to upgrade.  React will print a nice warning letting
      // them know they need to upgrade, though, so we're good.  Also note we explicitly do not
      // use TestUtils from react-dom/test-utils here, mainly so the user still gets a warning for
      // requiring 'react-addons-test-utils', which lets them know there's action required.

      // eslint-disable-next-line import/no-extraneous-dependencies
      TestUtils = require('react-addons-test-utils');
      shallowRendererFactory = TestUtils.createRenderer;
    }
  } catch (e) {
    if (REACT155) {
      console.error( // eslint-disable-line no-console
        'react-dom@15.5+ and react-test-renderer are implicit dependencies when using' +
        'react@15.5+ with enzyme. Please add the appropriate version to your ' +
        'devDependencies. See https://github.com/airbnb/enzyme#installation',
      );
    } else {
      console.error( // eslint-disable-line no-console
        'react-addons-test-utils is an implicit dependency in order to support react@0.13-14. ' +
        'Please add the appropriate version to your devDependencies. ' +
        'See https://github.com/airbnb/enzyme#installation',
      );
    }
    throw e;
  }

  // Shallow rendering changed from 0.13 => 0.14 in such a way that
  // 0.14 now does not allow shallow rendering of native DOM elements.
  // This is mainly because the result of such a call should not realistically
  // be any different than the JSX you passed in (result of `React.createElement`.
  // In order to maintain the same behavior across versions, this function
  // is essentially a replacement for `TestUtils.createRenderer` that doesn't use
  // shallow rendering when it's just a DOM element.
  createShallowRenderer = function createRendererCompatible() {
    const renderer = shallowRendererFactory();
    const originalRender = renderer.render;
    const originalRenderOutput = renderer.getRenderOutput;
    let isDOM = false;
    let cachedNode;
    return objectAssign(renderer, {
      render(node, context) {
        /* eslint consistent-return: 0 */
        if (typeof node.type === 'string') {
          isDOM = true;
          cachedNode = node;
        } else {
          isDOM = false;
          return originalRender.call(this, node, context);
        }
      },
      getRenderOutput() {
        if (isDOM) {
          return cachedNode;
        }
        return originalRenderOutput.call(this);
      },
    });
  };
  renderIntoDocument = TestUtils.renderIntoDocument;
  childrenToArray = React.Children.toArray;

  renderWithOptions = (node, options) => {
    if (options.attachTo) {
      return ReactDOM.render(node, options.attachTo);
    }
    return TestUtils.renderIntoDocument(node);
  };
}

function isDOMComponentElement(inst) {
  return React.isValidElement(inst) && typeof inst.type === 'string';
}

const {
  mockComponent,
  isElement,
  isElementOfType,
  isDOMComponent,
  isCompositeComponent,
  isCompositeComponentWithType,
  isCompositeComponentElement,
  Simulate,
  findAllInRenderedTree,
} = TestUtils;

export {
  createShallowRenderer,
  renderToStaticMarkup,
  renderIntoDocument,
  mockComponent,
  isElement,
  isElementOfType,
  isDOMComponent,
  isDOMComponentElement,
  isCompositeComponent,
  isCompositeComponentWithType,
  isCompositeComponentElement,
  Simulate,
  findDOMNode,
  findAllInRenderedTree,
  childrenToArray,
  renderWithOptions,
  unmountComponentAtNode,
  batchedUpdates,
};
<|endoftext|>


<commit_before>// Copyright 2015 Volker Sorge
//
// 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.

/**
 * @fileoverview Class highlighting HTML-CSS elements.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */

goog.provide('sre.HtmlHighlighter');

goog.require('sre.CssHighlighter');

/**
 * @constructor
 * @extends {sre.CssHighlighter}
 */
sre.HtmlHighlighter = function() {
  goog.base(this);

  this.mactionName = 'maction';

};
goog.inherits(sre.HtmlHighlighter, sre.CssHighlighter);

/**
 * Set the mode of the highlighter.
 * @param {!string} mode The mode indicator.
 */
sre.HtmlHighlighter.prototype.setMode = function(mode) {
  this.mode = mode;
};

/**
 * @override
 */
sre.HtmlHighlighter.prototype.highlightNode = function(node) {
  if (!node.classList.contains(this.mactionName)) {
    return goog.base(this, 'highlightNode', node);
  }
  var box = node.firstElementChild;
  sre.HtmlHighlighter.relativePosition_(box.nextSibling);
  var info = {node: node,
    opacity: box.style.opacity,
    background: box.style.backgroundColor,
    foreground: node.style.color};
  var color = this.color.rgb();
  box.style.backgroundColor = color.background;
  box.style.opacity = color.alphaback;
  node.style.color = color.foreground;
  return info;
};

/**
 * Sets a node position to relative.
 * @param {Node} node The node to set the position on.
 * @private
 */
sre.HtmlHighlighter.relativePosition_ = function(node) {
  if (node) node.style.position = "relative";
};

/**
 * @override
 */
sre.HtmlHighlighter.prototype.unhighlightNode = function(info) {
  if (!info.node.classList.contains(this.mactionName)) {
    goog.base(this, 'unhighlightNode', info);
    return;
  }
  var box = info.node.firstElementChild;
  box.style.backgroundColor = info.background;
  box.style.opacity = info.opacity;
  info.node.style.color = info.foreground;
};
<commit_msg>Removes use of classList. Important for IE9.<commit_after>// Copyright 2015 Volker Sorge
//
// 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.

/**
 * @fileoverview Class highlighting HTML-CSS elements.
 *
 * @author volker.sorge@gmail.com (Volker Sorge)
 */

goog.provide('sre.HtmlHighlighter');

goog.require('sre.CssHighlighter');

/**
 * @constructor
 * @extends {sre.CssHighlighter}
 */
sre.HtmlHighlighter = function() {
  goog.base(this);

  this.mactionName = 'maction';

};
goog.inherits(sre.HtmlHighlighter, sre.CssHighlighter);

/**
 * Set the mode of the highlighter.
 * @param {!string} mode The mode indicator.
 */
sre.HtmlHighlighter.prototype.setMode = function(mode) {
  this.mode = mode;
};

/**
 * @override
 */
sre.HtmlHighlighter.prototype.highlightNode = function(node) {
  if (node.className.search(this.mactionName) === -1) {
    return goog.base(this, 'highlightNode', node);
  }
  var box = node.firstElementChild;
  sre.HtmlHighlighter.relativePosition_(box.nextSibling);
  var info = {node: node,
    opacity: box.style.opacity,
    background: box.style.backgroundColor,
    foreground: node.style.color};
  var color = this.color.rgb();
  box.style.backgroundColor = color.background;
  box.style.opacity = color.alphaback;
  node.style.color = color.foreground;
  return info;
};

/**
 * Sets a node position to relative.
 * @param {Node} node The node to set the position on.
 * @private
 */
sre.HtmlHighlighter.relativePosition_ = function(node) {
  if (node) node.style.position = "relative";
};

/**
 * @override
 */
sre.HtmlHighlighter.prototype.unhighlightNode = function(info) {
  if (node.className.search(this.mactionName) === -1) {
    goog.base(this, 'unhighlightNode', info);
    return;
  }
  var box = info.node.firstElementChild;
  box.style.backgroundColor = info.background;
  box.style.opacity = info.opacity;
  info.node.style.color = info.foreground;
};
<|endoftext|>


<commit_before>const { isPretty } = require("./source");
const { isOriginalId } = require("../utils/source-map");

function shouldShowPrettyPrint(selectedSource) {
  const _isPretty = isPretty(selectedSource);
  const isOriginal = isOriginalId(selectedSource.id);
  const hasSourceMap = selectedSource.sourceMapURL;

  if (_isPretty || isOriginal || hasSourceMap) {
    return false;
  }

  return true;
}

function shouldShowFooter(selectedSource) {
  return shouldShowPrettyPrint(selectedSource);
}

module.exports = {
  shouldShowPrettyPrint,
  shouldShowFooter
};
<commit_msg>checking if source is javascript for pretty print (#1271)<commit_after>const { isPretty, isJavaScript } = require("./source");
const { isOriginalId } = require("../utils/source-map");

function shouldShowPrettyPrint(selectedSource) {
  const _isPretty = isPretty(selectedSource);
  const _isJavaScript = isJavaScript(selectedSource.url);
  const isOriginal = isOriginalId(selectedSource.id);
  const hasSourceMap = selectedSource.sourceMapURL;

  if (_isPretty || isOriginal || hasSourceMap || !_isJavaScript) {
    return false;
  }

  return true;
}

function shouldShowFooter(selectedSource) {
  return shouldShowPrettyPrint(selectedSource);
}

module.exports = {
  shouldShowPrettyPrint,
  shouldShowFooter
};
<|endoftext|>


<commit_before>function isObject(obj) {
  return typeof(obj) === 'object' && obj !== null;
}

/**
*  A recursive merge between two objects.
*
*  @param base     - the object whose properties are to be overwritten. It
*                    should be either the root level or some nested level.
*  @param override - an object containing properties to be overwritten. It
*                    should have the same structure as the object object.
*/
let extend = (base, override) => {

  let mergedObject = {};

  //Loop through each key in the base object
  Object.keys(base).forEach((key) => {

    let baseProp = base[key];
    let overrideProp;

    if (isObject(override)) overrideProp = override[key];

    //Recursive call extend if the prop is another object, else just copy it over
    mergedObject[key] = isObject(baseProp) && !Array.isArray(baseProp) ?
      extend(baseProp, overrideProp) : baseProp;

  });

  //Loop through each override key and override the props in the
  //base object
  if (isObject(override)) {

    Object.keys(override).forEach((overrideKey) => {

      let overrideProp = override[overrideKey];

      //Only copy over props that are not objects
      if (!isObject(overrideProp) || Array.isArray(overrideProp)) {
        mergedObject[overrideKey] = overrideProp;
      }

    });
  }

  return mergedObject;
};

module.exports = extend;
<commit_msg>Update extend.js -- Revert #9b82b5624c59948e6c9648d4253f15051e751fc<commit_after>// http://stackoverflow.com/questions/1187518/javascript-array-difference
Array.prototype.diff = function(a) {
    return this.filter(function(i) {return a.indexOf(i) < 0;});
};

/**
*  A recursive merge between two objects.
*
*  @param object     - the object whose properties are to be overwritten. It
*                     should be either the root level or some nested level.
*  @param overrides - an object containing properties to be overwritten. It
*                     should have the same structure as the object object.
*/
var extend = function(object, overrides) {
  var mergeObject = {};

  function isValidOverride(value) { return value || value === '' || value === null || value === 0; }

  Object.keys(object).forEach(function(currentKey) {

    // Arrays and null are also objects,
    var overridesIsValidObject = object[currentKey] && !Array.isArray(object[currentKey]);

    // Recursive call to next level
    if (typeof(object[currentKey]) === 'object' && overridesIsValidObject) {
      mergeObject[currentKey] = extend(object[currentKey], overrides[currentKey]);
    } else {
      if (overrides && isValidOverride(overrides[currentKey])) {
        mergeObject[currentKey] = overrides[currentKey];
      } else {
        mergeObject[currentKey] = object[currentKey];
      }
    }

  });

  // Overrides not defined in object are immediately added.
  if (overrides && typeof(overrides) === 'object' && !Array.isArray(overrides)) {
    Object.keys(overrides).diff(Object.keys(object)).forEach(function(currentDiff) {
      mergeObject[currentDiff] = overrides[currentDiff];
    });
  }

  return mergeObject;
};

module.exports = extend;
<|endoftext|>


<commit_before>'use strict';

var isWindow = require('./isWindow');

if (typeof window === 'undefined') {
    module.exports.window     = undefined;
    module.exports.realWindow = undefined;
}
else {
    // get wrapped window if using Shadow DOM polyfill

    module.exports.realWindow = window;

    // create a TextNode
    var el = window.document.createTextNode('');

    // check if it's wrapped by a polyfill
    if (el.ownerDocument !== window.document
        && typeof window.wrap === 'function'
        && window.wrap(el) === el) {
        // return wrapped window
        module.exports.window = window.wrap(window);
    }

    // no Shadow DOM polyfil or native implementation
    module.exports.window = window;
}

module.exports.getWindow = function getWindow (node) {
    if (isWindow(node)) {
        return node;
    }

    var rootNode = (node.ownerDocument || node);

    return rootNode.defaultView || rootNode.parentWindow || module.exports.window;
};
<commit_msg>utils/window: allow window to be updated later<commit_after>'use strict';

var win = module.exports,
    isWindow = require('./isWindow');

function init (window) {
    // get wrapped window if using Shadow DOM polyfill

    win.realWindow = window;

    // create a TextNode
    var el = window.document.createTextNode('');

    // check if it's wrapped by a polyfill
    if (el.ownerDocument !== window.document
        && typeof window.wrap === 'function'
        && window.wrap(el) === el) {
        // return wrapped window
        win.window = window.wrap(window);
    }

    // no Shadow DOM polyfil or native implementation
    win.window = window;
}

if (typeof window === 'undefined') {
    win.window     = undefined;
    win.realWindow = undefined;
}
else {
    init(window);
}

win.getWindow = function getWindow (node) {
    if (isWindow(node)) {
        return node;
    }

    var rootNode = (node.ownerDocument || node);

    return rootNode.defaultView || rootNode.parentWindow || win.window;
};

win.init = init;
<|endoftext|>


<commit_before>import { evaluation } from './';
import {
  or,
  and,
  not,
  mod,
  modR,
  error,
  isBool,
  isOneOf,
  isArray,
  isString,
  isNumber,
  includes,
  isUndefined,
  isDictionary,
  isNotUndefined,
  isArrayOfLength,
  objectIncludesString
} from './helpers';

const predicates = {};
const validators = {};
const isMissing = (k, v, c) => k !== 'exists' && (isUndefined(c) || isUndefined(v));

export const listPredicates = () => Object.keys(predicates);
export const hasPredicate = key => predicates.hasOwnProperty(key);
export const removePredicate = key => {
  delete predicates[key];
  delete validators[key];
}

export const registerPredicate = (key, predicator, validator) => {
  if (hasPredicate(key)) {
    error(`Predicate "${key}" is already registered`);
  } else {
    validators[key] = validator
    predicates[key] = (config, value, getThis, getThat) => {
      const v = getThis(value);
      const c = getThat ? getThat(value) : config;

      if (isMissing(key, v, c) || (validator && !validator(c))) return undefined;
      return predicator(v, c);
    }
  }
}

export const getPredicate = (key, config, thisValue) => {
  if (!hasPredicate(key)) {
    error(key ? `Unregisterd predicate: "${key}"` : 'Empty predicate');
  } else {
    const isComplexConfig = isDictionary(config) && config.that

    if (!isComplexConfig && validators[key] && !validators[key](config)) {
      error(`invalid config for "${key}": ${config}`)
    }

    const getThis = evaluation(thisValue);
    const getThat = isComplexConfig && evaluation(config.that);
    return v => predicates[key](config, v, getThis, getThat);
  }
}

registerPredicate('not', not);
registerPredicate('and', and);
registerPredicate('or', or);

// add intersect
// predication({ x: [3, 4, 5] })([1, 2, 3]) // true
// predication({ x: [4, 5, 6] })([1, 2, 3]) // false

registerPredicate('exists', (v, c) => c === !isUndefined(v),              isBool)
registerPredicate('mod', (v, c) => (isArray(c) ? modR(v, c) : mod(v, c)), isOneOf(isNumber, isArrayOfLength(2)));
registerPredicate('in',  (v, c) => includes(v, c),                        isNotUndefined);
registerPredicate('nin', (v, c) => !includes(v, c),                       isNotUndefined);
registerPredicate('eq',  (v, c) => v === c,                               isNotUndefined);
registerPredicate('ne',  (v, c) => v !== c,                               isNotUndefined);
registerPredicate('lt',  (v, c) => v < c,                                 isNumber);
registerPredicate('gt',  (v, c) => v > c,                                 isNumber);
registerPredicate('lte', (v, c) => v <= c,                                isNumber);
registerPredicate('gte', (v, c) => v >= c,                                isNumber);
registerPredicate('rng', (v, c) => (v >= c[0] && v <= c[1]),              isArrayOfLength(2, isNumber));
registerPredicate('oi',  (v, c) => objectIncludesString(v, c),            isString);
registerPredicate('noi', (v, c) => !objectIncludesString(v, c),           isString);
<commit_msg>only revalidating if that is dynamic<commit_after>import { evaluation } from './';
import {
  or,
  and,
  not,
  mod,
  modR,
  error,
  isBool,
  isOneOf,
  isArray,
  isString,
  isNumber,
  includes,
  isUndefined,
  isDictionary,
  isNotUndefined,
  isArrayOfLength,
  objectIncludesString
} from './helpers';

const predicates = {};
const validators = {};
const isMissing = (k, v, c) => k !== 'exists' && (isUndefined(c) || isUndefined(v));

export const listPredicates = () => Object.keys(predicates);
export const hasPredicate = key => predicates.hasOwnProperty(key);
export const removePredicate = key => {
  delete predicates[key];
  delete validators[key];
}

export const registerPredicate = (key, predicator, validator) => {
  if (hasPredicate(key)) {
    error(`Predicate "${key}" is already registered`);
  } else {
    validators[key] = validator
    predicates[key] = (config, value, getThis, getThat) => {
      const v = getThis(value);
      const c = getThat ? getThat(value) : config;

      if (isMissing(key, v, c) || (getThat && validator && !validator(c))) return undefined;
      return predicator(v, c);
    }
  }
}

export const getPredicate = (key, config, thisValue) => {
  if (!hasPredicate(key)) {
    error(key ? `Unregisterd predicate: "${key}"` : 'Empty predicate');
  } else {
    const isComplexConfig = isDictionary(config) && config.that

    if (!isComplexConfig && validators[key] && !validators[key](config)) {
      error(`invalid config for "${key}": ${config}`)
    }

    const getThis = evaluation(thisValue);
    const getThat = isComplexConfig && evaluation(config.that);
    return v => predicates[key](config, v, getThis, getThat);
  }
}

registerPredicate('not', not);
registerPredicate('and', and);
registerPredicate('or', or);

// add intersect
// predication({ x: [3, 4, 5] })([1, 2, 3]) // true
// predication({ x: [4, 5, 6] })([1, 2, 3]) // false

registerPredicate('exists', (v, c) => c === !isUndefined(v),              isBool)
registerPredicate('mod', (v, c) => (isArray(c) ? modR(v, c) : mod(v, c)), isOneOf(isNumber, isArrayOfLength(2)));
registerPredicate('in',  (v, c) => includes(v, c),                        isNotUndefined);
registerPredicate('nin', (v, c) => !includes(v, c),                       isNotUndefined);
registerPredicate('eq',  (v, c) => v === c,                               isNotUndefined);
registerPredicate('ne',  (v, c) => v !== c,                               isNotUndefined);
registerPredicate('lt',  (v, c) => v < c,                                 isNumber);
registerPredicate('gt',  (v, c) => v > c,                                 isNumber);
registerPredicate('lte', (v, c) => v <= c,                                isNumber);
registerPredicate('gte', (v, c) => v >= c,                                isNumber);
registerPredicate('rng', (v, c) => (v >= c[0] && v <= c[1]),              isArrayOfLength(2, isNumber));
registerPredicate('oi',  (v, c) => objectIncludesString(v, c),            isString);
registerPredicate('noi', (v, c) => !objectIncludesString(v, c),           isString);
<|endoftext|>


<commit_before>let React = require("react")
let Colr = require('colr')
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, input} = React.DOM
let cx = require("classnames")

let colorMap = React.createFactory(require("./color/map"))
let hue_slider =  React.createFactory(require("./color/hue_slider"))

export default class extends React.Component {

  static displayName = "Frig.friggingBootstrap.Color"

  static defaultProps = Object.assign(require("../default_props.js"))

  state = { showPopup: false }

  _onInputClick() {
    this.setState({
      showPopup: !this.state.showPopup,
    })
  }

  _setHex(hex) {
    hex = hex.replace(/[^\w\s]/gi, '')
    if(hex.length !== 3 && hex.length !== 6) return false

    let color = Colr.fromHex(hex)
    this.setState({
      color: color,
      hsv: color.toRawHsvObject(),
    })
  }

  _displayColor(){
    if (this.state.showPopup === false) return false
    return div({className: "controls colorpicker"},
      div({ className: "hue-slider" },
        hue_slider({
          max: 360,
          valueLink: this.props.valueLink,
        })
      ),
      colorMap({
        max: 100,
        valueLink: this.props.valueLink,
      })
    )
  }

  _getContrastYIQ(hexColor){
    hexColor = hexColor || "000000"
    hexColor = hexColor.replace(/[^\w\s]/gi, '')
    if (hexColor.length === 3) hexColor = hexColor.concat(hexColor)

    let r = parseInt(hexColor.substr(0,2),16)
    let g = parseInt(hexColor.substr(2,2),16)
    let b = parseInt(hexColor.substr(4,2),16)
    let yiq = ((r*299)+(g*587)+(b*114))/1000

    return (yiq >= 128) ? 'black' : 'white'
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: formGroupCx(this.props)},
        label(this.props),
        input(Object.assign({}, this.props.inputHtml, {
            valueLink: this.props.valueLink,
            className: cx(this.props.inputHtml.className, "form-control"),
            onClick: this._onInputClick.bind(this),
            style: {
               backgroundColor: this.props.valueLink.value,
               color: this._getContrastYIQ(this.props.valueLink.value),
            },
          }),
        ),
        this._displayColor(),
        errorList(this.props.errors),
      )
    )
  }

}
<commit_msg>Setting Color BG input via _changeBackgroundColor<commit_after>let React = require("react")
let Colr = require('colr')
let {errorList, sizeClassNames, formGroupCx, label} = require("../util.js")
let {div, input} = React.DOM
let cx = require("classnames")

let colorMap = React.createFactory(require("./color/map"))
let hue_slider =  React.createFactory(require("./color/hue_slider"))

export default class extends React.Component {

  static displayName = "Frig.friggingBootstrap.Color"

  static defaultProps = Object.assign(require("../default_props.js"))

  state = { showPopup: false }

  _onInputClick() {
    this.setState({
      showPopup: !this.state.showPopup,
    })
  }

  _setHex(hex) {
    hex = hex.replace(/[^\w\s]/gi, '')
    if(hex.length !== 3 && hex.length !== 6) return false

    let color = Colr.fromHex(hex)
    this.setState({
      color: color,
      hsv: color.toRawHsvObject(),
    })
  }

  _displayColor(){
    if (this.state.showPopup === false) return false
    return div({className: "controls colorpicker"},
      div({ className: "hue-slider" },
        hue_slider({
          max: 360,
          valueLink: this.props.valueLink,
        })
      ),
      colorMap({
        max: 100,
        valueLink: this.props.valueLink,
      })
    )
  }

  _getContrastYIQ(hexColor){
    hexColor = hexColor || "000000"
    hexColor = hexColor.replace(/[^\w\s]/gi, '')
    if (hexColor.length === 3) hexColor = hexColor.concat(hexColor)

    let r = parseInt(hexColor.substr(0,2),16)
    let g = parseInt(hexColor.substr(2,2),16)
    let b = parseInt(hexColor.substr(4,2),16)
    let yiq = ((r*299)+(g*587)+(b*114))/1000

    return (yiq >= 128) ? 'black' : 'white'
  }

  _changeBackgroundColor(){
    let newBGColor = this.props.valueLink.value || "FFF"
    if (this.refs.colorText === undefined) return newBGColor

    let currentBG = this.refs.colorText.props.style.backgroundColor
    newBGColor = newBGColor.replace(/[^\w\s]/gi, '')
    let bgColorLen = newBGColor.length

    return bgColorLen === 3 || bgColorLen === 6 ? `#${newBGColor}` : currentBG
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: formGroupCx(this.props)},
        label(this.props),
        input(Object.assign({}, this.props.inputHtml, {
            valueLink: this.props.valueLink,
            ref: "colorText",
            className: cx(this.props.inputHtml.className, "form-control"),
            onClick: this._onInputClick.bind(this),
            style: {
               backgroundColor: this._changeBackgroundColor(),
               color: this._getContrastYIQ(this.props.valueLink.value),
            },
          }),
        ),
        this._displayColor(),
        errorList(this.props.errors),
      )
    )
  }

}
<|endoftext|>