<commit_before>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'TableCellPropertyRefinement',
  refines: 'foam.core.Property',
  properties: [
    {
      name: 'columnLabel',
      factory: function() {
        return this.label;
      }
    },
    {
      name: 'tableCellView',
      value: function(obj) {
        return obj[this.name];
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.u2',
  name: 'TableCellActionRefinement',
  refines: 'foam.core.Action',
  properties: [
    {
      class: 'String',
      name: 'columnLabel'
    },
    {
      name: 'tableCellView',
      value: function(obj, e) {
        //       return foam.u2.ActionView.create({action: this, data: obj});

        return this.toE(null, e.__subContext__.createSubContext({data: obj}));
      }
    }
  ]
});

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

  requires: [
    // TODO(braden): This should implement Expressions instead.
    'foam.mlang.predicate.And',
    'foam.mlang.predicate.Eq',
    'foam.mlang.predicate.Not',
    'foam.mlang.predicate.Or',
    'foam.u2.CheckBox',
    'foam.u2.TableCellRefinement'
  ],

  imports: [
    'selectionQuery', // Optional. Installed by the TableSelection decorator.
    'tableView'
  ],

  properties: [
    [ 'nodeName', 'tbody' ],
    [ 'columns_' ],
    'selectionFeedback_',
    {
      name: 'rows_',
      factory: function() { return {}; }
    }
  ],

  methods: [
    function initE() {
      var self = this;
      this.on('click', function(event) {
        var me = self.el();
        var e = event.target;
        while ( e.nodeName !== 'TR' && e !== me ) {
          e = e.parentNode;
        }

        // If we managed to click between rows, do nothing.
        if ( e === me ) return;
        // Otherwise, we found the tr.
        var obj = self.rows_[e.id];
        if ( obj ) self.tableView.selection = obj;
      });
    },

    function addObj(obj) {
      var e = this.start('tr')
          .enableClass(this.tableView.myClass('selected'),
              this.tableView.selection$.map(function(sel) {
                return sel === obj;
              }));

      if ( this.selectionQuery$ ) {
        var cb;
        e.start('td')
            .start(this.CheckBox).call(function() { cb = this; }).end()
        .end();

        this.selectionQuery$.sub(foam.Function.bind(this.selectionUpdate, this,
            cb, obj));
        this.selectionUpdate(cb, obj);
        cb.data$.sub(foam.Function.bind(this.selectionClick, this, obj));
      }

      for ( var j = 0 ; j < this.columns_.length ; j++ ) {
        var prop = this.columns_[j];
        e = e.start('td').add(prop.tableCellView(obj, e)).end();
      }
      e.end();
      this.rows_[e.id] = obj;
    }
  ],

  listeners: [
    {
      name: 'selectionUpdate',
      code: function(checkbox, obj) {
        var selected = this.selectionQuery.f(obj);
        if ( selected !== checkbox.data ) {
          // Need to prevent feedback between these two listeners.
          this.selectionFeedback_ = true;
          checkbox.data = selected;
          this.selectionFeedback_ = false;
        }
      }
    },
    {
      name: 'selectionClick',
      code: function(obj, _, __, ___, slot) {
        if ( this.selectionFeedback_ ) return;

        var q = this.Eq.create({ arg1: obj.ID, arg2: obj.id });
        if ( slot.get() ) {
          this.selectionQuery = this.Or.create({
            args: [ q, this.selectionQuery ]
          }).partialEval();
        } else {
          this.selectionQuery = this.And.create({
            args: [ this.Not.create({ arg1: q }), this.selectionQuery ]
          }).partialEval();
        }
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.u2',
  name: 'TableBodySink',
  extends: 'foam.dao.AbstractSink',

  requires: [
    'foam.u2.TableBody'
  ],

  properties: [
    'columns_',
    {
      name: 'body',
      factory: function() { return this.TableBody.create({ columns_: this.columns_ }); }
    }
  ],
  methods: [
    function put(_, obj) {
      this.body.addObj(obj);
    }
  ]
});

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

  requires: [
    'foam.mlang.order.Desc',
    'foam.u2.Entity'
  ],

  imports: [
    'selectionQuery', // Optional. Exported by TableSelection.
    'tableView'
  ],

  properties: [
    {
      name: 'columns_',
      required: true
    },
    'sortOrder'
  ],

  methods: [
    function initE() {
      var self = this;
      this.nodeName = 'thead';

      var e = this.start('tr');
      if ( this.selectionQuery$ ) {
        e.start('td').end();
      }

      for ( var i = 0 ; i < this.columns_.length ; i++ ) {
        var sorting$ = this.sortOrder$.map(function(prop, order) {
          if ( ! order ) return '';
          var desc = this.Desc.isInstance(order);
          var baseOrder = desc ? order.arg1 : order;
          return prop.name === baseOrder.name ?
              this.Entity.create({ name: desc ? 'darr' : 'uarr' }) : '';
        }.bind(this, this.columns_[i]));

        e.start('td')
            .enableClass(this.myClass('sorting'), sorting$)
            .start('span')
                .addClass(this.myClass('sort-direction'))
                .add(sorting$)
            .end()
            .add(this.columns_[i].columnLabel)
            .on('click', this.tableView.sortBy.bind(this.tableView,
                  this.columns_[i]))
            .end();
      }
      e.end();
    }
  ]
});

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

  requires: [
    'foam.mlang.order.Desc',
    'foam.u2.TableBodySink',
    'foam.u2.TableHeader'
  ],

  exports: [
    'as tableView'
  ],

  axioms: [
    foam.u2.CSS.create({
      code: function CSS() {/*
        ^sorting {
          font-weight: bold;
        }

        ^sort-direction {
          display: none;
          margin-right: 8px;
        }
        ^sorting ^sort-direction {
          display: initial;
        }
      */}
    })
  ],

  properties: [
    {
      class: 'Class',
      name: 'of',
      factory: function() { return this.data.of; }
    },
    [ 'nodeName', 'table' ],
    {
      name: 'columns_',
      expression: function(columns, of) {
        var cls = this.of;
        return columns.map(function(p) {
          // Lookup String values as Axiom names, otherwise,
          // treat the object as the column object itself.
          return typeof p === 'string' ?
              cls.getAxiomByName(p) :
              p ;
        });
      }
    },
    {
      // TODO: remove when all code ported
      name: 'properties',
      setter: function(_, ps) {
        console.warn("Deprecated use of TableView.properties. Use 'columns' instead.");
        this.columns = ps;
      }
    },
    {
      name: 'columns',
      expression: function(of) {
        if ( ! this.of ) return [];

        var tableColumns = this.of.getAxiomByName('tableColumns');

        if ( tableColumns ) return tableColumns.columns;

        return this.of.getAxiomsByClass(foam.core.Property)
            .filter(function(p) { return ! p.hidden; })
            .map(foam.core.Property.NAME.f);
      }
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'data'
    },
    {
      name: 'header',
      expression: function(columns_) {
        return this.TableHeader.create({
          columns_: columns_,
          sortOrder$: this.sortOrder$
        });
      }
    },
    {
      name: 'body',
      factory: function() { return this.E('tbody'); }
    },
    {
      name: 'sortOrder'
    },
    {
      name: 'selection'
    }
  ],

  methods: [
    function initE() {
      this.onDAOUpdate();
      this.data$proxy.sub('on', this.onDAOUpdate);

      return this.
          addClass(this.myClass()).
          add(this.header$, this.body$);
    },

    function sortBy(prop) {
      // Two cases: same as the current prop, or different.
      var sortName = this.sortOrder ?
          (this.Desc.isInstance(this.sortOrder) ? this.sortOrder.arg1.name :
              this.sortOrder.name) :
          '';
      if ( sortName === prop.name ) {
        // Invert the previous order.
        this.sortOrder = this.Desc.isInstance(this.sortOrder) ?
            prop : this.Desc.create({ arg1: prop });
      } else {
        // Set it to the new column.
        this.sortOrder = prop;
      }
      this.onDAOUpdate();
    }
  ],

  listeners: [
    {
      name: 'onDAOUpdate',
      isFramed: true,
      code: function() {
        var dao = this.data;
        if ( this.sortOrder ) {
          dao = dao.orderBy(this.sortOrder);
        }
        dao.select(this.TableBodySink.create({
          columns_: this.columns_
        })).then(function(a) {
          this.body = a.body;
        }.bind(this));
      }
    }
  ]
});
<commit_msg>Minor code cleanup.<commit_after>/**
 * @license
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * 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.
 */

foam.CLASS({
  package: 'foam.u2',
  name: 'TableCellPropertyRefinement',
  refines: 'foam.core.Property',
  properties: [
    {
      name: 'columnLabel',
      factory: function() {
        return this.label;
      }
    },
    {
      name: 'tableCellView',
      value: function(obj) {
        return obj[this.name];
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.u2',
  name: 'TableCellActionRefinement',
  refines: 'foam.core.Action',
  properties: [
    {
      class: 'String',
      name: 'columnLabel'
    },
    {
      name: 'tableCellView',
      value: function(obj, e) {
        //       return foam.u2.ActionView.create({action: this, data: obj});

        return this.toE(null, e.__subContext__.createSubContext({data: obj}));
      }
    }
  ]
});

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

  requires: [
    // TODO(braden): This should implement Expressions instead.
    'foam.mlang.predicate.And',
    'foam.mlang.predicate.Eq',
    'foam.mlang.predicate.Not',
    'foam.mlang.predicate.Or',
    'foam.u2.CheckBox',
    'foam.u2.TableCellRefinement'
  ],

  imports: [
    'selectionQuery', // Optional. Installed by the TableSelection decorator.
    'tableView'
  ],

  properties: [
    [ 'nodeName', 'tbody' ],
    [ 'columns_' ],
    'selectionFeedback_',
    {
      name: 'rows_',
      factory: function() { return {}; }
    }
  ],

  methods: [
    function initE() {
      var self = this;
      this.on('click', function(event) {
        var me = self.el();
        var e = event.target;
        while ( e.nodeName !== 'TR' && e !== me ) {
          e = e.parentNode;
        }

        // If we managed to click between rows, do nothing.
        if ( e === me ) return;
        // Otherwise, we found the tr.
        var obj = self.rows_[e.id];
        if ( obj ) self.tableView.selection = obj;
      });
    },

    function addObj(obj) {
      var e = this.start('tr')
          .enableClass(this.tableView.myClass('selected'),
              this.tableView.selection$.map(function(sel) {
                return sel === obj;
              }));

      if ( this.selectionQuery$ ) {
        var cb;
        e.start('td')
            .start(this.CheckBox).call(function() { cb = this; }).end()
        .end();

        this.selectionQuery$.sub(foam.Function.bind(this.selectionUpdate, this,
            cb, obj));
        this.selectionUpdate(cb, obj);
        cb.data$.sub(foam.Function.bind(this.selectionClick, this, obj));
      }

      for ( var j = 0 ; j < this.columns_.length ; j++ ) {
        var prop = this.columns_[j];
        e = e.start('td').add(prop.tableCellView(obj, e)).end();
      }
      e.end();
      this.rows_[e.id] = obj;
    }
  ],

  listeners: [
    {
      name: 'selectionUpdate',
      code: function(checkbox, obj) {
        var selected = this.selectionQuery.f(obj);
        if ( selected !== checkbox.data ) {
          // Need to prevent feedback between these two listeners.
          this.selectionFeedback_ = true;
          checkbox.data = selected;
          this.selectionFeedback_ = false;
        }
      }
    },
    {
      name: 'selectionClick',
      code: function(obj, _, __, ___, slot) {
        if ( this.selectionFeedback_ ) return;

        var q = this.Eq.create({ arg1: obj.ID, arg2: obj.id });
        if ( slot.get() ) {
          this.selectionQuery = this.Or.create({
            args: [ q, this.selectionQuery ]
          }).partialEval();
        } else {
          this.selectionQuery = this.And.create({
            args: [ this.Not.create({ arg1: q }), this.selectionQuery ]
          }).partialEval();
        }
      }
    }
  ]
});

foam.CLASS({
  package: 'foam.u2',
  name: 'TableBodySink',
  extends: 'foam.dao.AbstractSink',

  requires: [
    'foam.u2.TableBody'
  ],

  properties: [
    'columns_',
    {
      name: 'body',
      factory: function() { return this.TableBody.create({ columns_: this.columns_ }); }
    }
  ],
  methods: [
    function put(_, obj) {
      this.body.addObj(obj);
    }
  ]
});

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

  requires: [
    'foam.mlang.order.Desc',
    'foam.u2.Entity'
  ],

  imports: [
    'selectionQuery', // Optional. Exported by TableSelection.
    'tableView'
  ],

  properties: [
    {
      name: 'columns_',
      required: true
    },
    'sortOrder'
  ],

  methods: [
    function initE() {
      var self = this;
      this.nodeName = 'thead';

      var e = this.start('tr');
      if ( this.selectionQuery$ ) {
        e.tag('td');
      }

      for ( var i = 0 ; i < this.columns_.length ; i++ ) {
        var sorting$ = this.sortOrder$.map(function(prop, order) {
          if ( ! order ) return '';
          var desc = this.Desc.isInstance(order);
          var baseOrder = desc ? order.arg1 : order;
          return prop.name === baseOrder.name ?
              this.Entity.create({ name: desc ? 'darr' : 'uarr' }) : '';
        }.bind(this, this.columns_[i]));

        e.start('td')
            .enableClass(this.myClass('sorting'), sorting$)
            .start('span')
                .addClass(this.myClass('sort-direction'))
                .add(sorting$)
            .end()
            .add(this.columns_[i].columnLabel)
            .on('click', this.tableView.sortBy.bind(this.tableView,
                  this.columns_[i]))
            .end();
      }
      e.end();
    }
  ]
});

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

  requires: [
    'foam.mlang.order.Desc',
    'foam.u2.TableBodySink',
    'foam.u2.TableHeader'
  ],

  exports: [
    'as tableView'
  ],

  axioms: [
    foam.u2.CSS.create({
      code: function CSS() {/*
        ^sorting {
          font-weight: bold;
        }

        ^sort-direction {
          display: none;
          margin-right: 8px;
        }
        ^sorting ^sort-direction {
          display: initial;
        }
      */}
    })
  ],

  properties: [
    {
      class: 'Class',
      name: 'of',
      factory: function() { return this.data.of; }
    },
    [ 'nodeName', 'table' ],
    {
      name: 'columns_',
      expression: function(columns, of) {
        var cls = this.of;
        return columns.map(function(p) {
          // Lookup String values as Axiom names, otherwise,
          // treat the object as the column object itself.
          return typeof p === 'string' ?
              cls.getAxiomByName(p) :
              p ;
        });
      }
    },
    {
      // TODO: remove when all code ported
      name: 'properties',
      setter: function(_, ps) {
        console.warn("Deprecated use of TableView.properties. Use 'columns' instead.");
        this.columns = ps;
      }
    },
    {
      name: 'columns',
      expression: function(of) {
        if ( ! this.of ) return [];

        var tableColumns = this.of.getAxiomByName('tableColumns');

        if ( tableColumns ) return tableColumns.columns;

        return this.of.getAxiomsByClass(foam.core.Property)
            .filter(function(p) { return ! p.hidden; })
            .map(foam.core.Property.NAME.f);
      }
    },
    {
      class: 'foam.dao.DAOProperty',
      name: 'data'
    },
    {
      name: 'header',
      expression: function(columns_) {
        return this.TableHeader.create({
          columns_: columns_,
          sortOrder$: this.sortOrder$
        });
      }
    },
    {
      name: 'body',
      factory: function() { return this.E('tbody'); }
    },
    {
      name: 'sortOrder'
    },
    {
      name: 'selection'
    }
  ],

  methods: [
    function initE() {
      this.onDAOUpdate();
      this.data$proxy.sub('on', this.onDAOUpdate);

      return this.
          addClass(this.myClass()).
          add(this.header$, this.body$);
    },

    function sortBy(prop) {
      // Two cases: same as the current prop, or different.
      var sortName = this.sortOrder ?
          (this.Desc.isInstance(this.sortOrder) ? this.sortOrder.arg1.name :
              this.sortOrder.name) :
          '';
      if ( sortName === prop.name ) {
        // Invert the previous order.
        this.sortOrder = this.Desc.isInstance(this.sortOrder) ?
            prop : this.Desc.create({ arg1: prop });
      } else {
        // Set it to the new column.
        this.sortOrder = prop;
      }
      this.onDAOUpdate();
    }
  ],

  listeners: [
    {
      name: 'onDAOUpdate',
      isFramed: true,
      code: function() {
        var dao = this.data;
        if ( this.sortOrder ) {
          dao = dao.orderBy(this.sortOrder);
        }
        dao.select(this.TableBodySink.create({
          columns_: this.columns_
        })).then(function(a) {
          this.body = a.body;
        }.bind(this));
      }
    }
  ]
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';
import fs from 'fs';
import { version } from './package.json';
import snfe from './index';

let input = process.argv[2];

if (process.argv.indexOf(`-h`) !== -1 ||
    process.argv.indexOf(`--help`) !== -1) {
    console.log(`snfe <input file> > <output file>`);
    process.exit(0);
} else if (process.argv.indexOf(`-v`) !== -1 ||
    process.argv.indexOf(`--version`) !== -1) {
    console.log(version);
    process.exit(0);
}

if (input) {
    process.stdout.write(strip(fs.readFileSync(input, `utf8`)).toString());
    process.exit(0);
}<commit_msg>Import `name` attribute from package.json<commit_after>#!/usr/bin/env node
'use strict';
import fs from 'fs';
import snfe from './index';
import { name, version } from './package.json';

let input = process.argv[2];

if (process.argv.indexOf(`-h`) !== -1 ||
    process.argv.indexOf(`--help`) !== -1) {
    console.log(`snfe <input file> > <output file>`);
    process.exit(0);
} else if (process.argv.indexOf(`-v`) !== -1 ||
    process.argv.indexOf(`--version`) !== -1) {
    console.log(version);
    process.exit(0);
}

if (input) {
    process.stdout.write(strip(fs.readFileSync(input, `utf8`)).toString());
    process.exit(0);
}<|endoftext|>


<commit_before>'use strict';

var Promise = require('../ext/promise');
var path    = require('path');
var findup  = Promise.denodeify(require('findup'));
var resolve = Promise.denodeify(require('resolve'));
var fs      = require('fs');
var assign  = require('lodash-node/modern/objects/assign');
var DAG     = require('../utilities/DAG');
var Command = require('../models/command');
var Addon   = require('../models/addon');
var merge   = require('lodash-node/modern/objects/merge');

var emberCLIVersion = require('../utilities/ember-cli-version');

function Project(root, pkg) {
  this.root          = root;
  this.pkg           = pkg;
  this.addonPackages = {};
  this.liveReloadFilterPatterns = [];
}

var NULL_PROJECT = new Project(process.cwd(), {});

NULL_PROJECT.isEmberCLIProject = function() {
  return false;
};

NULL_PROJECT.isEmberCLIAddon = function() {
  return false;
};

NULL_PROJECT.name = function() {
  return path.basename(process.cwd());
};

Project.NULL_PROJECT = NULL_PROJECT;

Project.prototype.name = function() {
  return this.pkg.name;
};

Project.prototype.isEmberCLIProject = function() {
  return this.pkg.devDependencies && 'ember-cli' in this.pkg.devDependencies;
};

Project.prototype.isEmberCLIAddon = function() {
  return this.pkg.keywords && this.pkg.keywords.indexOf('ember-addon') > -1;
};

Project.prototype.configPath = function() {
  var configPath = 'config';

  if (this.pkg['ember-addon'] && this.pkg['ember-addon']['configPath']) {
    configPath = this.pkg['ember-addon']['configPath'];
  }

  return path.join(configPath, 'environment');
};

Project.prototype.config = function(env) {
  var configPath = this.configPath();

  if (fs.existsSync(path.join(this.root, configPath + '.js'))) {
    var appConfig = this.require('./' + configPath)(env);
    var addonsConfig = this.getAddonsConfig(env, appConfig);

    return merge(addonsConfig, appConfig);
  } else {
    return this.getAddonsConfig(env, {});
  }
};

Project.prototype.getAddonsConfig = function(env, appConfig) {
  this.initializeAddons();

  return this.addons.reduce(function(config, addon) {
    if (addon.config) {
      merge(config, addon.config(env, config));
    }

    return config;
  }, appConfig);
};

Project.prototype.has = function(file) {
  return fs.existsSync(path.join(this.root, file)) || fs.existsSync(path.join(this.root, file + '.js'));
};

Project.prototype.resolve = function(file) {
  return resolve(file, {
    basedir: this.root
  });
};

Project.prototype.require = function(file) {
  if (/^\.\//.test(file)) { // Starts with ./
    return require(path.join(this.root, file));
  } else {
    return require(path.join(this.root, 'node_modules', file));
  }
};

Project.prototype.emberCLIVersion = emberCLIVersion;

Project.prototype.dependencies = function(pkg) {
  pkg = pkg || this.pkg || {};
  return assign({}, pkg['devDependencies'], pkg['dependencies']);
};

Project.prototype.buildAddonPackages = function() {
  if (!this.root) { return; }

  var internalMiddlewarePath = path.join(this.root, path.relative(this.root, path.join(__dirname, '../tasks/server/middleware')));

  this.addIfAddon(path.join(internalMiddlewarePath, 'history-support'));
  this.addIfAddon(path.join(internalMiddlewarePath, 'serve-files'));
  this.addIfAddon(path.join(internalMiddlewarePath, 'proxy-server'));

  this.discoverAddons(this.root, this.pkg);
};

Project.prototype.discoverAddons = function(root, pkg) {
  Object.keys(this.dependencies(pkg)).forEach(function(name) {
    if (name !== 'ember-cli') {
      var addonPath = path.join(root, 'node_modules', name);
      this.addIfAddon(addonPath);
    }
  }, this);

  if (pkg['ember-addon'] && pkg['ember-addon'].paths) {
    pkg['ember-addon'].paths.forEach(function(addonPath) {
      addonPath = path.join(root, addonPath);
      this.addIfAddon(addonPath);
    }, this);
  }
};

Project.prototype.addIfAddon = function(addonPath) {
  var pkgPath = path.join(addonPath, 'package.json');

  if(fs.existsSync(pkgPath)) {
    var addonPkg = require(pkgPath);
    var keywords = addonPkg.keywords || [];

    addonPkg['ember-addon'] = addonPkg['ember-addon'] || {};

    if (keywords.indexOf('ember-addon') > -1) {
      this.discoverAddons(addonPath, addonPkg);
      this.addonPackages[addonPkg.name] = {
        path: addonPath,
        pkg: addonPkg
      };
    }
  }
};

Project.prototype.initializeAddons = function() {
  if (this._addonsInitialized) {
    return;
  }

  var project         = this;
  var graph           = new DAG();
  var addon, emberAddonConfig;

  this.buildAddonPackages();

  for (var name in this.addonPackages) {
    addon            = this.addonPackages[name];
    emberAddonConfig = addon.pkg['ember-addon'];

    graph.addEdges(name, addon, emberAddonConfig.before, emberAddonConfig.after);
  }

  this.addons = [];
  graph.topsort(function (vertex) {
    var addon           = vertex.value;
    var AddonConstructor = Addon.lookup(addon);

    project.addons.push(new AddonConstructor(project));
  });

  this._addonsInitialized = true;
};

Project.prototype.addonCommands = function() {
  var commands = {};
  this.addons.forEach(function(addon){
    var includedCommands = (addon.includedCommands && addon.includedCommands()) || {};
    var addonCommands = {};
    for (var key in includedCommands) {
      addonCommands[key] = Command.extend(includedCommands[key]);
    }
    if(Object.keys(addonCommands).length) {
      commands[addon.name] = addonCommands;
    }
  });
  return commands;
};

Project.prototype.eachAddonCommand = function(callback) {
  if(this.initializeAddons && this.addonCommands) {
    this.initializeAddons();
    var addonCommands = this.addonCommands();

    Object.keys(addonCommands).forEach(function(addonName){
      callback(addonName, addonCommands[addonName]);
    }.bind(this));
  }
};

Project.prototype.localBlueprintLookupPath = function() {
  return path.join(this.root, 'blueprints');
};

Project.prototype.blueprintLookupPaths = function() {
  if (this.isEmberCLIProject()) {
    var lookupPaths = [this.localBlueprintLookupPath()];
    var addonLookupPaths = this.addonBlueprintLookupPaths();

    return lookupPaths.concat(addonLookupPaths);
  } else {
    return [];
  }
};

Project.prototype.addonBlueprintLookupPaths = function() {
  var addonPaths = this.addons.map(function(addon) {
    if (addon.blueprintsPath) {
      return addon.blueprintsPath();
    }
  }, this);

  return addonPaths.filter(Boolean);
};

Project.closest = function(pathName) {
  return closestPackageJSON(pathName)
    .then(function(result) {

      if (result.pkg && result.pkg.name === 'ember-cli') {
        return NULL_PROJECT;
      }

      return new Project(result.directory, result.pkg);
    })
    .catch(function(reason) {
      handleFindupError(pathName, reason);
    });
};

Project.closestSync = function(pathName) {
  try {
    var directory = findup.sync(pathName, 'package.json');
    var pkg = require(path.join(directory, 'package.json'));

    if (pkg && pkg.name === 'ember-cli') {
      return NULL_PROJECT;
    }

    return new Project(directory, pkg);
  } catch(reason) {
    handleFindupError(pathName, reason);
  }
};

function NotFoundError(message) {
  this.name = 'NotFoundError';
  this.message = message;
  this.stack = (new Error()).stack;
}

NotFoundError.constructor = NotFoundError;
NotFoundError.prototype = Object.create(Error.prototype);

Project.NotFoundError = NotFoundError;

function closestPackageJSON(pathName) {
  return findup(pathName, 'package.json')
    .then(function(directory) {
      return Promise.hash({
        directory: directory,
        pkg: require(path.join(directory, 'package.json'))
      });
    });
}

function handleFindupError(pathName, reason) {
  // Would be nice if findup threw error subclasses
  if (reason && /not found/i.test(reason.message)) {
    throw new NotFoundError('No project found at or up from: `' + pathName + '`');
  } else {
    throw reason;
  }
}

// Export
module.exports = Project;

<commit_msg>Fix NotFoundError's constructor property.<commit_after>'use strict';

var Promise = require('../ext/promise');
var path    = require('path');
var findup  = Promise.denodeify(require('findup'));
var resolve = Promise.denodeify(require('resolve'));
var fs      = require('fs');
var assign  = require('lodash-node/modern/objects/assign');
var DAG     = require('../utilities/DAG');
var Command = require('../models/command');
var Addon   = require('../models/addon');
var merge   = require('lodash-node/modern/objects/merge');

var emberCLIVersion = require('../utilities/ember-cli-version');

function Project(root, pkg) {
  this.root          = root;
  this.pkg           = pkg;
  this.addonPackages = {};
  this.liveReloadFilterPatterns = [];
}

var NULL_PROJECT = new Project(process.cwd(), {});

NULL_PROJECT.isEmberCLIProject = function() {
  return false;
};

NULL_PROJECT.isEmberCLIAddon = function() {
  return false;
};

NULL_PROJECT.name = function() {
  return path.basename(process.cwd());
};

Project.NULL_PROJECT = NULL_PROJECT;

Project.prototype.name = function() {
  return this.pkg.name;
};

Project.prototype.isEmberCLIProject = function() {
  return this.pkg.devDependencies && 'ember-cli' in this.pkg.devDependencies;
};

Project.prototype.isEmberCLIAddon = function() {
  return this.pkg.keywords && this.pkg.keywords.indexOf('ember-addon') > -1;
};

Project.prototype.configPath = function() {
  var configPath = 'config';

  if (this.pkg['ember-addon'] && this.pkg['ember-addon']['configPath']) {
    configPath = this.pkg['ember-addon']['configPath'];
  }

  return path.join(configPath, 'environment');
};

Project.prototype.config = function(env) {
  var configPath = this.configPath();

  if (fs.existsSync(path.join(this.root, configPath + '.js'))) {
    var appConfig = this.require('./' + configPath)(env);
    var addonsConfig = this.getAddonsConfig(env, appConfig);

    return merge(addonsConfig, appConfig);
  } else {
    return this.getAddonsConfig(env, {});
  }
};

Project.prototype.getAddonsConfig = function(env, appConfig) {
  this.initializeAddons();

  return this.addons.reduce(function(config, addon) {
    if (addon.config) {
      merge(config, addon.config(env, config));
    }

    return config;
  }, appConfig);
};

Project.prototype.has = function(file) {
  return fs.existsSync(path.join(this.root, file)) || fs.existsSync(path.join(this.root, file + '.js'));
};

Project.prototype.resolve = function(file) {
  return resolve(file, {
    basedir: this.root
  });
};

Project.prototype.require = function(file) {
  if (/^\.\//.test(file)) { // Starts with ./
    return require(path.join(this.root, file));
  } else {
    return require(path.join(this.root, 'node_modules', file));
  }
};

Project.prototype.emberCLIVersion = emberCLIVersion;

Project.prototype.dependencies = function(pkg) {
  pkg = pkg || this.pkg || {};
  return assign({}, pkg['devDependencies'], pkg['dependencies']);
};

Project.prototype.buildAddonPackages = function() {
  if (!this.root) { return; }

  var internalMiddlewarePath = path.join(this.root, path.relative(this.root, path.join(__dirname, '../tasks/server/middleware')));

  this.addIfAddon(path.join(internalMiddlewarePath, 'history-support'));
  this.addIfAddon(path.join(internalMiddlewarePath, 'serve-files'));
  this.addIfAddon(path.join(internalMiddlewarePath, 'proxy-server'));

  this.discoverAddons(this.root, this.pkg);
};

Project.prototype.discoverAddons = function(root, pkg) {
  Object.keys(this.dependencies(pkg)).forEach(function(name) {
    if (name !== 'ember-cli') {
      var addonPath = path.join(root, 'node_modules', name);
      this.addIfAddon(addonPath);
    }
  }, this);

  if (pkg['ember-addon'] && pkg['ember-addon'].paths) {
    pkg['ember-addon'].paths.forEach(function(addonPath) {
      addonPath = path.join(root, addonPath);
      this.addIfAddon(addonPath);
    }, this);
  }
};

Project.prototype.addIfAddon = function(addonPath) {
  var pkgPath = path.join(addonPath, 'package.json');

  if(fs.existsSync(pkgPath)) {
    var addonPkg = require(pkgPath);
    var keywords = addonPkg.keywords || [];

    addonPkg['ember-addon'] = addonPkg['ember-addon'] || {};

    if (keywords.indexOf('ember-addon') > -1) {
      this.discoverAddons(addonPath, addonPkg);
      this.addonPackages[addonPkg.name] = {
        path: addonPath,
        pkg: addonPkg
      };
    }
  }
};

Project.prototype.initializeAddons = function() {
  if (this._addonsInitialized) {
    return;
  }

  var project         = this;
  var graph           = new DAG();
  var addon, emberAddonConfig;

  this.buildAddonPackages();

  for (var name in this.addonPackages) {
    addon            = this.addonPackages[name];
    emberAddonConfig = addon.pkg['ember-addon'];

    graph.addEdges(name, addon, emberAddonConfig.before, emberAddonConfig.after);
  }

  this.addons = [];
  graph.topsort(function (vertex) {
    var addon           = vertex.value;
    var AddonConstructor = Addon.lookup(addon);

    project.addons.push(new AddonConstructor(project));
  });

  this._addonsInitialized = true;
};

Project.prototype.addonCommands = function() {
  var commands = {};
  this.addons.forEach(function(addon){
    var includedCommands = (addon.includedCommands && addon.includedCommands()) || {};
    var addonCommands = {};
    for (var key in includedCommands) {
      addonCommands[key] = Command.extend(includedCommands[key]);
    }
    if(Object.keys(addonCommands).length) {
      commands[addon.name] = addonCommands;
    }
  });
  return commands;
};

Project.prototype.eachAddonCommand = function(callback) {
  if(this.initializeAddons && this.addonCommands) {
    this.initializeAddons();
    var addonCommands = this.addonCommands();

    Object.keys(addonCommands).forEach(function(addonName){
      callback(addonName, addonCommands[addonName]);
    }.bind(this));
  }
};

Project.prototype.localBlueprintLookupPath = function() {
  return path.join(this.root, 'blueprints');
};

Project.prototype.blueprintLookupPaths = function() {
  if (this.isEmberCLIProject()) {
    var lookupPaths = [this.localBlueprintLookupPath()];
    var addonLookupPaths = this.addonBlueprintLookupPaths();

    return lookupPaths.concat(addonLookupPaths);
  } else {
    return [];
  }
};

Project.prototype.addonBlueprintLookupPaths = function() {
  var addonPaths = this.addons.map(function(addon) {
    if (addon.blueprintsPath) {
      return addon.blueprintsPath();
    }
  }, this);

  return addonPaths.filter(Boolean);
};

Project.closest = function(pathName) {
  return closestPackageJSON(pathName)
    .then(function(result) {

      if (result.pkg && result.pkg.name === 'ember-cli') {
        return NULL_PROJECT;
      }

      return new Project(result.directory, result.pkg);
    })
    .catch(function(reason) {
      handleFindupError(pathName, reason);
    });
};

Project.closestSync = function(pathName) {
  try {
    var directory = findup.sync(pathName, 'package.json');
    var pkg = require(path.join(directory, 'package.json'));

    if (pkg && pkg.name === 'ember-cli') {
      return NULL_PROJECT;
    }

    return new Project(directory, pkg);
  } catch(reason) {
    handleFindupError(pathName, reason);
  }
};

function NotFoundError(message) {
  this.name = 'NotFoundError';
  this.message = message;
  this.stack = (new Error()).stack;
}

NotFoundError.prototype = Object.create(Error.prototype);
NotFoundError.prototype.constructor = NotFoundError;

Project.NotFoundError = NotFoundError;

function closestPackageJSON(pathName) {
  return findup(pathName, 'package.json')
    .then(function(directory) {
      return Promise.hash({
        directory: directory,
        pkg: require(path.join(directory, 'package.json'))
      });
    });
}

function handleFindupError(pathName, reason) {
  // Would be nice if findup threw error subclasses
  if (reason && /not found/i.test(reason.message)) {
    throw new NotFoundError('No project found at or up from: `' + pathName + '`');
  } else {
    throw reason;
  }
}

// Export
module.exports = Project;

<|endoftext|>


<commit_before>/**
 * Setup grunt config for global tool
 */
(function() {
    exports.config = config = (function() {
        function config(grunt, config) {
            /**
             * @param name string Module name
             */
            config.initModule = function (name, done) {
                // initialize module development environment
                process.chdir(config.workspace.modules + '/' + name);
                var initProcess = require('child_process').exec('webino init', function() {
                    done && done();
                });
                grunt.log.writeln();
                initProcess.stdout.pipe(process.stdout);
                initProcess.stderr.pipe(process.stderr);
            };

            /**
             * Setup mkdir tasks
             */
            config.mkdir.workspace = {
                options: {create: ['<%= workspace.root %>', '<%= workspace.modules %>', '<%= workspace.sites %>']}
            };

            config.mkdir.utils = {
                options: {create: ['<%= utils.root %>']}
            };

            /**
             * Waiting for utils initialization
             */
            config.wait_async.utils = {
                options: {
                    wait: function (done) {
                        var func = function () {
                            if (grunt.file.isDir(config.utils.root)) {
                                grunt.task.run(['copy:utils']);
                                done();
                            } else {
                                setTimeout(func, 250);
                            }
                        };
                        func();
                    }
                }
            };

            /**
             * Waiting for utils copying
             */
            config.wait_async.setup = {
                options: {
                    wait: function (done) {
                        var func = function () {
                            if (grunt.file.isDir(config.utils.php)) {
                                var root = config.utils.php;
                                process.chdir(root);

                                if (config.utils.isInit()) {
                                    grunt.task.run('exec:get_composer');
                                    grunt.task.run('exec:get_selenium');
                                } else {
                                    grunt.log.ok('Updating ...');
                                    grunt.task.run('exec:composer_self_update');
                                }

                                grunt.task.run('exec:composer_update');
                                done();
                            } else {
                                func();
                            }
                        };
                        func();
                    }
                }
            };

            /**
             * Searching module repository
             */
            config.wait_async.mod = {
                options: {
                    timeout: 240 * 10000,
                    wait: function (done) {
                        if (!config.repositories.size()) {
                            grunt.fail.warn('\n\nExpected any repository \n\n');
                        }
                        var func = function (error) {
                            if (!config.repositories.size()) {
                                if (error) {
                                    grunt.log.debug(error);
                                    grunt.fail.warn('\n\nCan\'t clone repository \n\n');
                                }
                                done();
                            }

                            var repo = config.repositories.deq();
                            var name = grunt.task.current.args[0];

                            repo.ssh || grunt.fail.warn('\n\nExpected repository ssh option');
                            name || grunt.fail.warn('\n\nExpected module option, e.g.: \n\ -name WebinoExample \n\n');

                            var uri = repo.ssh + '/' + name;
                            var target = config.workspace.modules + '/' + name;

                            grunt.log.debug(target);
                            if (grunt.file.exists(target + '/.git')) {
                                grunt.log.write('\nTarget already exists, initializing ...');
                                config.initModule(name, done);
                                return;
                            }

                            grunt.log.write('Cloning ' + repo.name + ':' + repo.vendor + '/' + name + ' ...');
                            config.loading();

                            grunt.log.debug(uri);
                            grunt.log.debug(repo);

                            var cp = require('child_process');
                            var cloneProcess = cp.exec('git clone ' + uri + ' ' + target, function (error) {
                                clearTimeout(config.loading.timeout);
                                if (error) {
                                    func(error);
                                    return;
                                }

                                grunt.log.writeln('OK');
                                grunt.log.ok('\nInitializing ' + target + ' ...');
                                config.initModule(name, done);
                            });

                            cloneProcess.stderr.on('data', function (data) {
                                grunt.log.debug(data);
                                if (-1 !== data.indexOf('not exist')
                                    || -1 !== data.indexOf('not found')
                                ) {
                                    grunt.log.writeln('nope');
                                }
                            });

                            cloneProcess.stdout.on('data', function (data) {
                                grunt.log.debug(data);
                            });

                            if (config.verbose) {
                                cloneProcess.stdout.pipe(process.stdout);
                                cloneProcess.stderr.pipe(process.stderr);
                            }
                        };
                        func();
                    }
                }
            };

            /**
             * Setup copy tasks
             */
            config.copy.utils = {
                files: [{
                    expand: true,
                    cwd: '<%= data.root %>',
                    src: ['utils/**'],
                    dest: '<%= utils.root %>',
                    mode: 644
                }]
            };

            /**
             * Register grunt tasks
             */
            config.tasks.default = {
                isSystem: true,
                description: 'Webino Development Kit help',
                function: function () {
                    config.showTasksHelp();
                }
            };

            config.tasks.workspace = {
                description: 'Initialize your Webino workspace',
                /**
                 * Required to run as user
                 */
                function: function () {
                    grunt.log.ok('Initializing workspace ...');
                    if (!process.getuid()) {
                        grunt.fail.warn('Are you a root?');
                        return;
                    }

                    // crete user config
                    if (!grunt.file.exists(this.user_cfg)) {
                        /**
                         * Required to run as user
                         */
                        grunt.log.ok('Installing Webino user config ...');
                        grunt.util.spawn({cmd: 'cp', args: [__dirname + '/../dist/webino.json', this.user_cfg]}, function () {});
                    }

                    // TODO create workspace directories
                    //grunt.task.run('mkdir:workspace');
                }
            };

            config.tasks.mod = {
                description: 'Develop existing Webino module',
                examples: ['webino mod:WebinoExample'],
                examples: ['webino mod -name WebinoExample'],
                function: function (name) {
                    // Resolve module by name
                    name || grunt.fail.warn('\n\nExpected module option, e.g.: \n\ -name WebinoExample \n\n');
                    grunt.log.writeln('Preparing module \'' + name + '\' for development ...');
                    grunt.task.run('wait_async:mod:' + name);
                }
            };

            config.tasks.setup = {
                isSystem: true,
                description: 'Initializes Webino Development Kit',
                /**
                 * Required to run as root
                 */
                function: function () {
                    if (config.utils.isInit()) {
                        grunt.log.ok('Initializing ...');
                        grunt.task.run(['mkdir:utils', 'wait_async:utils']);
                    }

                    grunt.task.run('wait_async:setup');
                }
            };
        };
        return config;
    })();
}).call(this);
<commit_msg>Updated global.js, fixed copy.utils<commit_after>/**
 * Setup grunt config for global tool
 */
(function() {
    exports.config = config = (function() {
        function config(grunt, config) {
            /**
             * @param name string Module name
             */
            config.initModule = function (name, done) {
                // initialize module development environment
                process.chdir(config.workspace.modules + '/' + name);
                var initProcess = require('child_process').exec('webino init', function() {
                    done && done();
                });
                grunt.log.writeln();
                initProcess.stdout.pipe(process.stdout);
                initProcess.stderr.pipe(process.stderr);
            };

            /**
             * Setup mkdir tasks
             */
            config.mkdir.workspace = {
                options: {create: ['<%= workspace.root %>', '<%= workspace.modules %>', '<%= workspace.sites %>']}
            };

            config.mkdir.utils = {
                options: {create: ['<%= utils.root %>']}
            };

            /**
             * Waiting for utils initialization
             */
            config.wait_async.utils = {
                options: {
                    wait: function (done) {
                        var func = function () {
                            if (grunt.file.isDir(config.utils.root)) {
                                grunt.task.run(['copy:utils']);
                                done();
                            } else {
                                setTimeout(func, 250);
                            }
                        };
                        func();
                    }
                }
            };

            /**
             * Waiting for utils copying
             */
            config.wait_async.setup = {
                options: {
                    wait: function (done) {
                        var func = function () {
                            if (grunt.file.isDir(config.utils.php)) {
                                var root = config.utils.php;
                                process.chdir(root);

                                if (config.utils.isInit()) {
                                    grunt.task.run('exec:get_composer');
                                    grunt.task.run('exec:get_selenium');
                                } else {
                                    grunt.log.ok('Updating ...');
                                    grunt.task.run('exec:composer_self_update');
                                }

                                grunt.task.run('exec:composer_update');
                                done();
                            } else {
                                func();
                            }
                        };
                        func();
                    }
                }
            };

            /**
             * Searching module repository
             */
            config.wait_async.mod = {
                options: {
                    timeout: 240 * 10000,
                    wait: function (done) {
                        if (!config.repositories.size()) {
                            grunt.fail.warn('\n\nExpected any repository \n\n');
                        }
                        var func = function (error) {
                            if (!config.repositories.size()) {
                                if (error) {
                                    grunt.log.debug(error);
                                    grunt.fail.warn('\n\nCan\'t clone repository \n\n');
                                }
                                done();
                            }

                            var repo = config.repositories.deq();
                            var name = grunt.task.current.args[0];

                            repo.ssh || grunt.fail.warn('\n\nExpected repository ssh option');
                            name || grunt.fail.warn('\n\nExpected module option, e.g.: \n\ -name WebinoExample \n\n');

                            var uri = repo.ssh + '/' + name;
                            var target = config.workspace.modules + '/' + name;

                            grunt.log.debug(target);
                            if (grunt.file.exists(target + '/.git')) {
                                grunt.log.write('\nTarget already exists, initializing ...');
                                config.initModule(name, done);
                                return;
                            }

                            grunt.log.write('Cloning ' + repo.name + ':' + repo.vendor + '/' + name + ' ...');
                            config.loading();

                            grunt.log.debug(uri);
                            grunt.log.debug(repo);

                            var cp = require('child_process');
                            var cloneProcess = cp.exec('git clone ' + uri + ' ' + target, function (error) {
                                clearTimeout(config.loading.timeout);
                                if (error) {
                                    func(error);
                                    return;
                                }

                                grunt.log.writeln('OK');
                                grunt.log.ok('\nInitializing ' + target + ' ...');
                                config.initModule(name, done);
                            });

                            cloneProcess.stderr.on('data', function (data) {
                                grunt.log.debug(data);
                                if (-1 !== data.indexOf('not exist')
                                    || -1 !== data.indexOf('not found')
                                ) {
                                    grunt.log.writeln('nope');
                                }
                            });

                            cloneProcess.stdout.on('data', function (data) {
                                grunt.log.debug(data);
                            });

                            if (config.verbose) {
                                cloneProcess.stdout.pipe(process.stdout);
                                cloneProcess.stderr.pipe(process.stderr);
                            }
                        };
                        func();
                    }
                }
            };

            /**
             * Setup copy tasks
             */
            config.copy.utils = {
                files: [{
                    expand: true,
                    cwd: '<%= data.utils %>',
                    src: ['**'],
                    dest: '<%= utils.root %>',
                    mode: 644
                }]
            };

            /**
             * Register grunt tasks
             */
            config.tasks.default = {
                isSystem: true,
                description: 'Webino Development Kit help',
                function: function () {
                    config.showTasksHelp();
                }
            };

            config.tasks.workspace = {
                description: 'Initialize your Webino workspace',
                /**
                 * Required to run as user
                 */
                function: function () {
                    grunt.log.ok('Initializing workspace ...');
                    if (!process.getuid()) {
                        grunt.fail.warn('Are you a root?');
                        return;
                    }

                    // crete user config
                    if (!grunt.file.exists(this.user_cfg)) {
                        /**
                         * Required to run as user
                         */
                        grunt.log.ok('Installing Webino user config ...');
                        grunt.util.spawn({cmd: 'cp', args: [__dirname + '/../dist/webino.json', this.user_cfg]}, function () {});
                    }

                    // TODO create workspace directories
                    //grunt.task.run('mkdir:workspace');
                }
            };

            config.tasks.mod = {
                description: 'Develop existing Webino module',
                examples: ['webino mod:WebinoExample'],
                examples: ['webino mod -name WebinoExample'],
                function: function (name) {
                    // Resolve module by name
                    name || grunt.fail.warn('\n\nExpected module option, e.g.: \n\ -name WebinoExample \n\n');
                    grunt.log.writeln('Preparing module \'' + name + '\' for development ...');
                    grunt.task.run('wait_async:mod:' + name);
                }
            };

            config.tasks.setup = {
                isSystem: true,
                description: 'Initializes Webino Development Kit',
                /**
                 * Required to run as root
                 */
                function: function () {
                    if (config.utils.isInit()) {
                        grunt.log.ok('Initializing ...');
                        grunt.task.run(['mkdir:utils', 'wait_async:utils']);
                    }

                    grunt.task.run('wait_async:setup');
                }
            };
        };
        return config;
    })();
}).call(this);
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2008-2012 The Open Source Geospatial Foundation
 *
 * Published under the BSD license.
 * See http://svn.geoext.org/core/trunk/geoext/license.txt for the full text
 * of the license.
 */

/**
 * @include GeoExt/data/WMSCapabilitiesReader.js
 */

/** api: (define)
 *  module = GeoExt.data
 *  class = WMSCapabilitiesStore
 *  base_link = `Ext.data.Store <http://dev.sencha.com/deploy/dev/docs/?class=Ext.data.Store>`_
 */
Ext.namespace("GeoExt.data");

/** api: constructor
 *  .. class:: WMSCapabilitiesStore
 *
 *      Small helper class to make creating stores for remote WMS layer data
 *      easier.  The store is pre-configured with a built-in
 *      ``Ext.data.HttpProxy`` and :class:`GeoExt.data.WMSCapabilitiesReader`.
 *      The proxy is configured to allow caching and issues requests via GET.
 *      If you require some other proxy/reader combination then you'll have to
 *      configure this with your own proxy or create a basic
 *      :class:`GeoExt.data.LayerStore` and configure as needed.
 */

/** api: config[format]
 *  ``OpenLayers.Format``
 *  A parser for transforming the XHR response into an array of objects
 *  representing attributes.  Defaults to an ``OpenLayers.Format.WMSCapabilities``
 *  parser.
 */

/** api: config[fields]
 *  ``Array | Function``
 *  Either an Array of field definition objects as passed to
 *  ``Ext.data.Record.create``, or a record constructor created using
 *  ``Ext.data.Record.create``.  Defaults to ``["name", "type"]``.
 */

GeoExt.data.WMSCapabilitiesStore = function(c) {
    c = c || {};
    GeoExt.data.WMSCapabilitiesStore.superclass.constructor.call(
        this,
        Ext.apply(c, {
            proxy: c.proxy || (!c.data ?
                new Ext.data.HttpProxy({url: c.url, disableCaching: false, method: "GET"}) :
                undefined
            ),
            reader: new GeoExt.data.WMSCapabilitiesReader(
                c, c.fields
            )
        })
    );
};
Ext.extend(GeoExt.data.WMSCapabilitiesStore, Ext.data.Store);
<commit_msg>remove old file<commit_after><|endoftext|>


<commit_before>/* eslint-disable */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { uniqueID } from 'shared/utils/helpers'
import { bindActionCreators } from 'redux'
import { Form, Control } from 'react-redux-form'
import Textfield from 'shared/form/Textfield'
import formProps from 'shared/form/formPropsSelector'
import { required, validDate, validPriceRange, validMonth } from 'shared/validators'
import Datefield from 'shared/form/Datefield'
import RadioList from 'shared/form/RadioList'
import SubmitForm from 'shared/form/SubmitForm'
import styles from './EditPriceForm.scss'
import StatefulError from 'shared/form/StatefulError'
import ErrorBox from 'shared/form/ErrorBox'
import isBefore from 'date-fns/is_before'

class EditPriceForm extends Component {
  render() {
    const {
      submitClicked,
      priceData,
      serviceToEdit,
      model,
      action,
      form,
      editPriceForm,
      handlePriceSubmit,
      buttonClick,
      supplierCode
    } = this.props
    const date = editPriceForm.date
    const currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000)
    const tomorrowDay = currentDate.getDate()
    const tomorrowMonth = currentDate.getMonth() + 1
    const tomorrowYear = currentDate.getFullYear()
    const tomorrowDate = tomorrowYear + '-' + tomorrowMonth + '-' + tomorrowDay
    let hasFocused = false
    const setFocus = e => {
      if (!hasFocused) {
        hasFocused = true
        e.focus()
      }
    }
    const onSubmitFailed = () => {
      window.scrollTo(0, 0)
    }

    return (

            Pricing for {serviceToEdit.serviceName}
            {serviceToEdit.subCategoryName ? ' ' + '(' + serviceToEdit.subCategoryName + ')' : ''}

Step 3 of 4

              this.props.loadPrices(
                supplierCode,
                serviceToEdit.serviceTypeId,
                serviceToEdit.categoryId,
                serviceToEdit.serviceName,
                serviceToEdit.subCategoryName ? serviceToEdit.subCategoryName : ''
              )}
          >
            Back to pricing information

                Region: {priceData.region.state + ' ' + priceData.region.name}

              Pricing must be a fixed fee and all inclusive of GST, travel, assessment and report. The negotiated cap
              for each region is specified inline, you are not able to exceed.

          <ErrorBox model={model} setFocus={setFocus} submitClicked={submitClicked} />
          <Form
            model={model}
            action={action}
            id="BusinessDetails__create"
            validateOn="submit"
            onSubmit={data => handlePriceSubmit(data, priceData.capPrice)}
            validators={{
              '': {
                // Form-level validator
                validSequenceOfDates: vals => isBefore(vals.start_date, vals.end_date)
              }
            }}
            onSubmitFailed={onSubmitFailed}
          >
            <Textfield
              model={`${model}.price`}
              name="price"
              id="price"
              htmlFor="price"
              label="Enter a new price including GST"
              description={'The new price must not exceed $' + priceData.capPrice}
              validators={{ validPriceRange: validPriceRange(priceData.capPrice) }}
              messages={{
                validPriceRange: 'Price must be valid and less than $' + priceData.capPrice
              }}
            />

              <RadioList
                model={`${model}.date`}
                name="date"
                id="date"
                label="How long is this price valid for?"
                options={[
                  {
                    value: `${tomorrowDate}`,
                    label: 'From tomorrow onwards'
                  },
                  {
                    value: 'custom',
                    label: 'Select a date range'
                  }
                ]}
                validators={{
                  required
                }}
                messages={{
                  required: 'You must select how long is the price valid for.'
                }}
              />

            {date &&
              date === 'custom' &&

                <StatefulError
                  model={`${model}.start_date`}
                  id="start_date_error"
                  messages={{
                    validDate: 'Start date is required and must be in the future.',
                    validMonth: 'Month can only be from 1 to 12.'
                  }}
                />
                <StatefulError
                    model={`${model}`}
                    id="validSequenceOfDates"
                    messages={{
                        validSequenceOfDates: 'The start date must be prior to the end date.'
                    }}
                />
                <Control
                  model={`${model}.start_date`}
                  component={Datefield}
                  name="start_date"
                  id="start_date"
                  label="Start date"
                  controlProps={{
                    id: 'start_date',
                    model: `${model}.start_date`,
                    htmlFor: 'start_date',
                    label: 'Start date'
                  }}
                  validators={{
                    validDate,
                    validMonth
                  }}
                />

                <StatefulError
                  model={`${model}.end_date`}
                  id="end_date_error"
                  messages={{
                    validDate: 'End date is required and must be in the future.',
                    validMonth: 'Month can only be from 1 to 12.'
                  }}
                />
                <Control
                  model={`${model}.end_date`}
                  component={Datefield}
                  name="end_date"
                  id="end_date"
                  label="End date"
                  controlProps={{
                    id: 'end_date',
                    model: `${model}.end_date`,
                    htmlFor: 'end_date',
                    label: 'End date'
                  }}
                  validators={{
                    validDate
                  }}
                />

}

                <button
                  type="submit"
                  onClick={() => {
                    buttonClick('saveAnother')
                  }}
                  className="uikit-btn right-button-margin"
                >
                  Save and edit another
                </button>
                <button type="submit" onClick={() => buttonClick('continueToFinalStep')} className="uikit-btn">
                  Continue to contract variation
                </button>

          </Form>

    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    ...formProps(state, 'editPriceForm')
  }
}

const mapDispatchToProps = dispatch => {
  return {}
}

export { mapStateToProps, EditPriceForm as Form }

export default connect(mapStateToProps, mapDispatchToProps)(EditPriceForm)
<commit_msg>Final prior date validation logic<commit_after>/* eslint-disable */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { uniqueID } from 'shared/utils/helpers'
import { bindActionCreators } from 'redux'
import { Form, Control } from 'react-redux-form'
import Textfield from 'shared/form/Textfield'
import formProps from 'shared/form/formPropsSelector'
import { required, validDate, validPriceRange, validMonth } from 'shared/validators'
import Datefield from 'shared/form/Datefield'
import RadioList from 'shared/form/RadioList'
import SubmitForm from 'shared/form/SubmitForm'
import styles from './EditPriceForm.scss'
import StatefulError from 'shared/form/StatefulError'
import ErrorBox from 'shared/form/ErrorBox'
import isBefore from 'date-fns/is_before'

class EditPriceForm extends Component {
  render() {
    const {
      submitClicked,
      priceData,
      serviceToEdit,
      model,
      action,
      form,
      editPriceForm,
      handlePriceSubmit,
      buttonClick,
      supplierCode
    } = this.props
    const date = editPriceForm.date
    const currentDate = new Date(new Date().getTime() + 24 * 60 * 60 * 1000)
    const tomorrowDay = currentDate.getDate()
    const tomorrowMonth = currentDate.getMonth() + 1
    const tomorrowYear = currentDate.getFullYear()
    const tomorrowDate = tomorrowYear + '-' + tomorrowMonth + '-' + tomorrowDay
    let hasFocused = false
    const setFocus = e => {
      if (!hasFocused) {
        hasFocused = true
        e.focus()
      }
    }
    const onSubmitFailed = () => {
      window.scrollTo(0, 0)
    }

    return (

            Pricing for {serviceToEdit.serviceName}
            {serviceToEdit.subCategoryName ? ' ' + '(' + serviceToEdit.subCategoryName + ')' : ''}

Step 3 of 4

              this.props.loadPrices(
                supplierCode,
                serviceToEdit.serviceTypeId,
                serviceToEdit.categoryId,
                serviceToEdit.serviceName,
                serviceToEdit.subCategoryName ? serviceToEdit.subCategoryName : ''
              )}
          >
            Back to pricing information

                Region: {priceData.region.state + ' ' + priceData.region.name}

              Pricing must be a fixed fee and all inclusive of GST, travel, assessment and report. The negotiated cap
              for each region is specified inline, you are not able to exceed.

          <ErrorBox model={model} setFocus={setFocus} submitClicked={submitClicked} />
          <Form
            model={model}
            action={action}
            id="BusinessDetails__create"
            validateOn="submit"
            onSubmit={data => handlePriceSubmit(data, priceData.capPrice)}
            validators={{
              '': {
                // Form-level validator
                validSequenceOfDates: vals => vals.date === 'custom' ? isBefore(vals.start_date, vals.end_date) : true
              }
            }}
            onSubmitFailed={onSubmitFailed}
          >
            <Textfield
              model={`${model}.price`}
              name="price"
              id="price"
              htmlFor="price"
              label="Enter a new price including GST"
              description={'The new price must not exceed $' + priceData.capPrice}
              validators={{ validPriceRange: validPriceRange(priceData.capPrice) }}
              messages={{
                validPriceRange: 'Price must be valid and less than $' + priceData.capPrice
              }}
            />

              <RadioList
                model={`${model}.date`}
                name="date"
                id="date"
                label="How long is this price valid for?"
                options={[
                  {
                    value: `${tomorrowDate}`,
                    label: 'From tomorrow onwards'
                  },
                  {
                    value: 'custom',
                    label: 'Select a date range'
                  }
                ]}
                validators={{
                  required
                }}
                messages={{
                  required: 'You must select how long is the price valid for.'
                }}
              />

            {date &&
              date === 'custom' &&

                <StatefulError
                  model={`${model}.start_date`}
                  id="start_date_error"
                  messages={{
                    validDate: 'Start date is required and must be in the future.',
                    validMonth: 'Month can only be from 1 to 12.'
                  }}
                />
                <StatefulError
                    model={`${model}`}
                    id="validSequenceOfDates"
                    messages={{
                        validSequenceOfDates: 'The start date must be prior to the end date.'
                    }}
                />
                <Control
                  model={`${model}.start_date`}
                  component={Datefield}
                  name="start_date"
                  id="start_date"
                  label="Start date"
                  controlProps={{
                    id: 'start_date',
                    model: `${model}.start_date`,
                    htmlFor: 'start_date',
                    label: 'Start date'
                  }}
                  validators={{
                    validDate,
                    validMonth
                  }}
                />

                <StatefulError
                  model={`${model}.end_date`}
                  id="end_date_error"
                  messages={{
                    validDate: 'End date is required and must be in the future.',
                    validMonth: 'Month can only be from 1 to 12.'
                  }}
                />
                <Control
                  model={`${model}.end_date`}
                  component={Datefield}
                  name="end_date"
                  id="end_date"
                  label="End date"
                  controlProps={{
                    id: 'end_date',
                    model: `${model}.end_date`,
                    htmlFor: 'end_date',
                    label: 'End date'
                  }}
                  validators={{
                    validDate
                  }}
                />

}

                <button
                  type="submit"
                  onClick={() => {
                    buttonClick('saveAnother')
                  }}
                  className="uikit-btn right-button-margin"
                >
                  Save and edit another
                </button>
                <button type="submit" onClick={() => buttonClick('continueToFinalStep')} className="uikit-btn">
                  Continue to contract variation
                </button>

          </Form>

    )
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    ...formProps(state, 'editPriceForm')
  }
}

const mapDispatchToProps = dispatch => {
  return {}
}

export { mapStateToProps, EditPriceForm as Form }

export default connect(mapStateToProps, mapDispatchToProps)(EditPriceForm)
<|endoftext|>


<commit_before>import './templates/base.scss';
import crashTemplate from './templates/crash.pug';
import './templates/crash.scss';
import blockInitTemplate from './templates/block-init.pug';
import './templates/block-init.scss';
import endTemplate from './templates/end.pug';
import './templates/end.scss';
import waitTemplate from './templates/wait.pug';
import './templates/wait.scss';

/**
 * Standard Experimentation App Base class. The app is higly reconfigurable and any method
 * can be safely replaced at any time. Cannot be used as is as it lacks a proper `runTrial`
 * method implementation.
 * @constructor
 * @abstract
 */
export default class StandardXpAppBase {
  /**
   * @param  {HTMLElement} node The node where to user for the app.
   */
  constructor(node) {
    /**
     * The node where lives the app (read-only).
     * @type {HTMLElement}
     */
    Object.defineProperty(this, 'node', { value: node });
  }
  /**
   * Must be overwriten by subclasses (or dynamically replaced).
   * @param {Object} config the trial configuration
   * @return {Promise<Object>} resolved with the trial results.
   * @abstract
   */
  runTrial() {
    throw new Error('XpApp.runTrial is not implemented');
  }

  /**
   * Show the wait view.
   * @param  {String} [message] The wait message.
   */
  wait(message) {
    this.node.innerHTML = waitTemplate(message);
  }

  /**
   * By default start waiting when the app starts.
   */
  start() {
    return this.wait();
  }

  /**
   * Show the crash view.
   * @param  {String} message The error message.
   * @param  {Error} [error]  The error that has been raised.
   * @param  {Object} [run]   The current run.
   */
  crash(message, error, run) {
    this.node.innerHTML = crashTemplate({
      run,
      message,
      stack: error && error.stack
    });
    const detailsButton = this.node.querySelector('.details-button');
    detailsButton.addEventListener('click', evt => {
      evt.preventDefault();
      this.node.querySelector('.xp-app-base').classList.toggle('with-details');
    });
  }

  /**
   * Show the block initialization view.
   * @param  {Object} blockInfo
   * @return {Promise}          Resolved when the user click/tap on the view.
   */
  initBlock(blockInfo) {
    return new Promise(resolve => {
      this.node.innerHTML = blockInitTemplate(blockInfo);
      const listener = evt => {
        evt.preventDefault();
        this.node.removeEventLister('click', listener);
        resolve();
      };
      this.node.addEventListener('click', listener);
    }).then(res => {
      this.wait();
      return res;
    });
  }

  /**
   * Show the end view.
   */
  end() {
    this.node.innerHTML = endTemplate();
  }
}
<commit_msg>Fix app base block handler being prematurely resolved when immediately shown after a click.<commit_after>import './templates/base.scss';
import crashTemplate from './templates/crash.pug';
import './templates/crash.scss';
import blockInitTemplate from './templates/block-init.pug';
import './templates/block-init.scss';
import endTemplate from './templates/end.pug';
import './templates/end.scss';
import waitTemplate from './templates/wait.pug';
import './templates/wait.scss';

const XP_APP_BASE_CLASSNAME = 'xp-app-base';

/**
 * Standard Experimentation App Base class. The app is higly reconfigurable and any method
 * can be safely replaced at any time. Cannot be used as is as it lacks a proper `runTrial`
 * method implementation.
 * @constructor
 * @abstract
 */
export default class StandardXpAppBase {
  /**
   * @param  {HTMLElement} node The node where to user for the app.
   */
  constructor(node) {
    /**
     * The node where lives the app (read-only).
     * @type {HTMLElement}
     */
    Object.defineProperty(this, 'node', { value: node });
  }
  /**
   * Must be overwriten by subclasses (or dynamically replaced).
   * @param {Object} config the trial configuration
   * @return {Promise<Object>} resolved with the trial results.
   * @abstract
   */
  runTrial() {
    throw new Error('XpApp.runTrial is not implemented');
  }

  /**
   * Show the wait view.
   * @param  {String} [message] The wait message.
   */
  wait(message) {
    this.node.innerHTML = waitTemplate(message);
  }

  /**
   * By default start waiting when the app starts.
   */
  start() {
    return this.wait();
  }

  /**
   * Show the crash view.
   * @param  {String} message The error message.
   * @param  {Error} [error]  The error that has been raised.
   * @param  {Object} [run]   The current run.
   */
  crash(message, error, run) {
    this.node.innerHTML = crashTemplate({
      run,
      message,
      stack: error && error.stack
    });
    const detailsButton = this.node.querySelector('.details-button');
    detailsButton.addEventListener('click', evt => {
      evt.preventDefault();
      this.node.querySelector(`.${XP_APP_BASE_CLASSNAME}`).classList.toggle('with-details');
    });
  }

  /**
   * Show the block initialization view.
   * @param  {Object} blockInfo
   * @return {Promise}          Resolved when the user click/tap on the view.
   */
  initBlock(blockInfo) {
    return new Promise(resolve => {
      this.node.innerHTML = blockInitTemplate(blockInfo);
      const appNode = this.node.querySelector(`.${XP_APP_BASE_CLASSNAME}`);
      const listener = evt => {
        evt.preventDefault();
        appNode.removeEventListener('click', listener);
        resolve();
      };
      appNode.addEventListener('click', listener);
    }).then(res => {
      this.wait();
      return res;
    });
  }

  /**
   * Show the end view.
   */
  end() {
    this.node.innerHTML = endTemplate();
  }
}
<|endoftext|>


<commit_before>var spoilerList;

// Look in storage sync for an object called 'spoilerItem'
chrome.storage.sync.get("spoilerItem", function (results) {
    spoilerList = results;
    if (spoilerList['spoilerItem'] == null) {
        spoilerList = {
            'spoilerItem': []
        };
        saveSpoilerList();
    }
});

// Listeners to listen when the page loads
$(function () {
    updateListView();
    searchForSpoilers();

    // Submit Button onclick adds item in input to list
    $('#submit-button').click(function (evt) {
        itemToAdd = $('#block-item').val().toLowerCase();
        spoilerList['spoilerItem'].push(itemToAdd);
        saveSpoilerList();
        $('#block-item').val('');
        updateListView();
        searchForSpoilers();
    });

    // Clear Button onclick removes all spoilers from list
    $('#clear-button').click(function (evt) {
        spoilerList = {
            'spoilerItem': []
        };
        saveSpoilerList();
        $('#block-item').val('');
        updateListView();
        searchForSpoilers();
    });

    // When a spoilerListItem gets clicked, remove it from the list
    $(document).on('click', '.spoilerListItem', function (item) {
        $('p:contains(' + item.currentTarget.innerHTML + ')').parents('.userContentWrapper').css('-webkit-filter', '');
        spoilerList["spoilerItem"].splice($.inArray(item.currentTarget.innerHTML, spoilerList["spoilerItem"]), 1);
        saveSpoilerList();
        updateListView();
        searchForSpoilers();
    });

    // New up an observer, and tell it what to do when it successfully observes.
    // Necessary for Facebooks "neverending" scrolling
    var observer = new MutationObserver(function (mutations, observer) {
        // fired when a mutation occurs
        searchForSpoilers();
    });

    // This part establishes what needs to be watched, and starts the watching
    observer.observe($('[id^=topnews_main_stream_]').get(0), {
        subtree: true, // watches target and it's descendants
        attributes: true // watches targets attributes
    });
});

// Handles showing the list of terms in the extention popup
function updateListView() {
    if (spoilerList["spoilerItem"] != null) {
        $('#listView').empty();
        var html = '
';
        for (var i = 0; i < spoilerList['spoilerItem'].length; i++) {
            html += '
' + spoilerList['spoilerItem'][i] + '
';
        }
        html += '
';
        $('#listView').append(html);
    }
}

// Handles searching for spoilers
function searchForSpoilers() {
    if (spoilerList["spoilerItem"] != null) {
        var searchString = '';
        spoilerList["spoilerItem"].forEach(function (item) {
            searchString = searchString + "p:contains('" + item + "'), ";
        });
        searchString = searchString.substring(0, searchString.length - 2);
        $(searchString).parents('.userContentWrapper').css('-webkit-filter', 'blur(5px)');
    }
}

// Sets spoilerList to chrome sync storage
function saveSpoilerList() {
    chrome.storage.sync.set({
        'spoilerItem': spoilerList["spoilerItem"]
    }, function (result) {
        if (chrome.runtime.error) {
            console.log(chrome.runtime.error);
        }
    });
}
<commit_msg>Adapted the original extension to function on all pages with a wider search range.<commit_after>var spoilerList;

// Look in storage sync for an object called 'spoilerItem'
chrome.storage.sync.get("spoilerItem", function (results) {
    spoilerList = results;
    if (spoilerList['spoilerItem'] == null) {
        spoilerList = {
            'spoilerItem': []
        };
        saveSpoilerList();
    }
});

// Listeners to listen when the page loads
$(function () {
    updateListView();
    searchForSpoilers();

    // Submit Button onclick adds item in input to list
    $('#submit-button').click(function (evt) {
        itemToAdd = $('#block-item').val().toLowerCase();
        spoilerList['spoilerItem'].push(itemToAdd);
        saveSpoilerList();
        $('#block-item').val('');
        updateListView();
        searchForSpoilers();
    });

    // Clear Button onclick removes all spoilers from list
    $('#clear-button').click(function (evt) {
        spoilerList = {
            'spoilerItem': []
        };
        saveSpoilerList();
        $('#block-item').val('');
        updateListView();
        searchForSpoilers();
    });

    // When a spoilerListItem gets clicked, remove it from the list
    $(document).on('click', '.spoilerListItem', function (item) {
        $('p:contains(' + item.currentTarget.innerHTML + ')').parents('.userContentWrapper').css('-webkit-filter', '');
        spoilerList["spoilerItem"].splice($.inArray(item.currentTarget.innerHTML, spoilerList["spoilerItem"]), 1);
        saveSpoilerList();
        updateListView();
        searchForSpoilers();
    });

        searchForSpoilers();
    // New up an observer, and tell it what to do when it successfully observes.
    // Necessary for Facebooks "neverending" scrolling
   /* var observer = new MutationObserver(function (mutations, observer) {
        // fired when a mutation occurs
        searchForSpoilers();
    });*/

    // This part establishes what needs to be watched, and starts the watching
    /*observer.observe($('[id^=topnews_main_stream_]').get(0), {
        subtree: true, // watches target and it's descendants
        attributes: true // watches targets attributes
    });*/
});

// Handles showing the list of terms in the extention popup
function updateListView() {
    if (spoilerList["spoilerItem"] != null) {
        $('#listView').empty();
        var html = '
';
        for (var i = 0; i < spoilerList['spoilerItem'].length; i++) {
            html += '
' + spoilerList['spoilerItem'][i] + '
';
        }
        html += '
';
        $('#listView').append(html);
    }
}

// Handles searching for spoilers
function searchForSpoilers() {
    if (spoilerList["spoilerItem"] != null) {
        var searchString = '';
        spoilerList["spoilerItem"].forEach(function (item) {
            searchString = searchString + "*:icontains('" + item + "'), ";
        });
        searchString = searchString.substring(0, searchString.length - 2);
        $(searchString).parent().css('-webkit-filter', 'blur(5px)');
    }
}

// Sets spoilerList to chrome sync storage
function saveSpoilerList() {
    chrome.storage.sync.set({
        'spoilerItem': spoilerList["spoilerItem"]
    }, function (result) {
        if (chrome.runtime.error) {
            console.log(chrome.runtime.error);
        }
    });
}

// Case insensitive jquery contains
jQuery.expr[':'].icontains = function(a, i, m) {
    return jQuery(a).text().toUpperCase()
            .indexOf(m[3].toUpperCase()) >= 0;
};
<|endoftext|>


<commit_before>/* Copyright (c) 2013, Erik Wienhold
 * All rights reserved.
 *
 * Licensed under the BSD 3-Clause License.
 */

/* global define */

define([
  'sulfur/schema/validator/all',
  'sulfur/schema/validator/property',
  'sulfur/schema/validator/prototype',
  'sulfur/util/factory'
], function (AllValidator, PropertyValidator, PrototypeValidator, Factory) {

  'use strict';

  return Factory.derive({

    initialize: function (options) {
      this._qname = options.qname;
      this._namespace = options.namespace;
      this._valueType = options.valueType;
    },

    get qname() {
      return this._qname;
    },

    get valueType() {
      return this._valueType;
    },

    get allowedElements() {
      return this.valueType.allowedElements;
    },

    isRestrictionOf: function (other) {
      return this === other;
    },

    createValidator: function () {
      var validators = [ PrototypeValidator.create(this.valueType.prototype) ];
      this.allowedElements.toArray().reduce(function (validators, element) {
        var validator = PropertyValidator.create('value',
          element.type.createValidator(), [ element.name ]);
        validators.push(validator);
        return validators;
      }, validators);
      return AllValidator.create(validators);
    }

  });

});
<commit_msg>remove obsolete property from primitive complex type<commit_after>/* Copyright (c) 2013, Erik Wienhold
 * All rights reserved.
 *
 * Licensed under the BSD 3-Clause License.
 */

/* global define */

define([
  'sulfur/schema/validator/all',
  'sulfur/schema/validator/property',
  'sulfur/schema/validator/prototype',
  'sulfur/util/factory'
], function (AllValidator, PropertyValidator, PrototypeValidator, Factory) {

  'use strict';

  return Factory.derive({

    initialize: function (options) {
      this._qname = options.qname;
      this._valueType = options.valueType;
    },

    get qname() {
      return this._qname;
    },

    get valueType() {
      return this._valueType;
    },

    get allowedElements() {
      return this.valueType.allowedElements;
    },

    isRestrictionOf: function (other) {
      return this === other;
    },

    createValidator: function () {
      var validators = [ PrototypeValidator.create(this.valueType.prototype) ];
      this.allowedElements.toArray().reduce(function (validators, element) {
        var validator = PropertyValidator.create('value',
          element.type.createValidator(), [ element.name ]);
        validators.push(validator);
        return validators;
      }, validators);
      return AllValidator.create(validators);
    }

  });

});
<|endoftext|>


<commit_before>"use strict";

var onEntityDelete = require("splat-ecs/lib/systems/box-collider").onEntityDelete;

function getCamera(entities) {
	return entities[1];
}

function resolveCollisionShortest(a, b, target) {
	var bottom = [0, b.position.y + b.size.height - a.position.y, 0, 0.5];
	var top = [0, b.position.y - a.size.height - a.position.y, 0, -0.5];
	var right = [b.position.x + b.size.width - a.position.x, 0, 0.5, 0];
	var left = [b.position.x - a.size.width - a.position.x, 0, -0.5, 0];

	var smallest = [bottom, top, right, left].reduce(function(prev, curr) {
		if (Math.abs(curr[0] + curr[1]) < Math.abs(prev[0] + prev[1])) {
			return curr;
		}
		return prev;
	});
	target = target || a;
	target.position.x += smallest[0];
	target.position.y += smallest[1];
	target.velocity.x += smallest[2];
	target.velocity.y += smallest[3];
}

function center(entity) {
	var x = entity.position.x + (entity.size.width / 2);
	var y = entity.position.y + (entity.size.height / 2);
	return { x: x, y: y };
}

function distanceSquared(a, b) {
	var ca = center(a);
	var cb = center(b);

	var dx = ca.x - cb.x;
	var dy = ca.y - cb.y;

	return dx * dx + dy * dy;
}

function calculateAspectRatio() {
	var canvas = document.getElementById("canvas");
	var canvasStyle = window.getComputedStyle(canvas);
	var ar = parseInt(canvasStyle.width) / parseInt(canvasStyle.height);
	aspectRatio = ar;
	return ar;
}
var aspectRatio = calculateAspectRatio();
window.onresize = calculateAspectRatio;

function randomFrom(array){
	return array[Math.floor(Math.random() * array.length)];
}

module.exports = function(ecs, data) { // eslint-disable-line no-unused-vars
	ecs.addEach(function(entity, elapsed) { // eslint-disable-line no-unused-vars
		var player = data.entities.entities[0];
		entity.collisions.forEach(function(id) {
			var other = data.entities.entities[id];
			if (other.sticky) {
				return;
			}

			if (other.noises && !other.silent) {
				data.sounds.play(randomFrom(other.noises));
				other.silent = true;
				setTimeout(function () {
					other.silent = false;
				}, 800);
			}

			other.velocity = { x: 0, y: 0 };
			onEntityDelete(other, data);

			var distSq = distanceSquared(player, other);
			var comparator = other.type === "obstacle" ? distSq * 1.15 : distSq;
			if (comparator < player.radius * player.radius) {
				player.area += other.size.width * other.size.height;
				other.match = {
					id: player.id,
					offsetX: other.position.x - player.position.x,
					offsetY: other.position.y - player.position.y
				};
				other.sticky = true;
				data.sounds.play("sfx-power-up");
				var message = other.name;
				var notice = data.entities.entities[2];
				notice.message = message;
			} else if (other.type === "obstacle") {
				resolveCollisionShortest(entity, other, player);
			} else {
				resolveCollisionShortest(other, entity);
			}
		});
		player.radius = Math.sqrt(player.area / Math.PI * 2);

		var size = 600;
		var viewportSize = Math.floor(player.radius * 2 * 3);
		player.scale = size / viewportSize;

		data.canvas.height = size;
		data.canvas.width = data.canvas.height * aspectRatio;

		var camera = getCamera(data.entities.entities);
		camera.size.height = Math.floor(player.radius * 2 * 3);
		camera.size.width = camera.size.height * aspectRatio;
	}, ["sticky"]);
};
<commit_msg>Better obstacle swallowing behavior.<commit_after>"use strict";

var onEntityDelete = require("splat-ecs/lib/systems/box-collider").onEntityDelete;

function getCamera(entities) {
	return entities[1];
}

function resolveCollisionShortest(a, b, target) {
	var bottom = [0, b.position.y + b.size.height - a.position.y, 0, 0.5];
	var top = [0, b.position.y - a.size.height - a.position.y, 0, -0.5];
	var right = [b.position.x + b.size.width - a.position.x, 0, 0.5, 0];
	var left = [b.position.x - a.size.width - a.position.x, 0, -0.5, 0];

	var smallest = [bottom, top, right, left].reduce(function(prev, curr) {
		if (Math.abs(curr[0] + curr[1]) < Math.abs(prev[0] + prev[1])) {
			return curr;
		}
		return prev;
	});
	target = target || a;
	target.position.x += smallest[0];
	target.position.y += smallest[1];
	target.velocity.x += smallest[2];
	target.velocity.y += smallest[3];
}

function center(entity) {
	var x = entity.position.x + (entity.size.width / 2);
	var y = entity.position.y + (entity.size.height / 2);
	return { x: x, y: y };
}

function distanceSquared(a, b) {
	var ca = center(a);
	var cb = center(b);

	var dx = ca.x - cb.x;
	var dy = ca.y - cb.y;

	return dx * dx + dy * dy;
}

function calculateAspectRatio() {
	var canvas = document.getElementById("canvas");
	var canvasStyle = window.getComputedStyle(canvas);
	var ar = parseInt(canvasStyle.width) / parseInt(canvasStyle.height);
	aspectRatio = ar;
	return ar;
}
var aspectRatio = calculateAspectRatio();
window.onresize = calculateAspectRatio;

function randomFrom(array){
	return array[Math.floor(Math.random() * array.length)];
}

module.exports = function(ecs, data) { // eslint-disable-line no-unused-vars
	ecs.addEach(function(entity, elapsed) { // eslint-disable-line no-unused-vars
		var player = data.entities.entities[0];
		entity.collisions.forEach(function(id) {
			var other = data.entities.entities[id];
			if (other.sticky) {
				return;
			}

			if (other.noises && !other.silent) {
				data.sounds.play(randomFrom(other.noises));
				other.silent = true;
				setTimeout(function () {
					other.silent = false;
				}, 800);
			}

			other.velocity = { x: 0, y: 0 };
			onEntityDelete(other, data);

			var distSq = distanceSquared(player, other);
			if (distSq < player.radius * player.radius) {
				player.area += other.size.width * other.size.height;
				other.match = {
					id: player.id,
					offsetX: other.position.x - player.position.x,
					offsetY: other.position.y - player.position.y
				};
				other.sticky = true;
				data.sounds.play("sfx-power-up");
				var message = other.name;
				var notice = data.entities.entities[2];
				notice.message = message;
			} else if (other.type === "obstacle") {
				resolveCollisionShortest(entity, other, player);
			} else {
				resolveCollisionShortest(other, entity);
			}
		});
		player.radius = Math.sqrt(player.area / Math.PI * 2);

		var size = 600;
		var viewportSize = Math.floor(player.radius * 2 * 3);
		player.scale = size / viewportSize;

		data.canvas.height = size;
		data.canvas.width = data.canvas.height * aspectRatio;

		var camera = getCamera(data.entities.entities);
		camera.size.height = Math.floor(player.radius * 2 * 3);
		camera.size.width = camera.size.height * aspectRatio;
	}, ["sticky"]);
};
<|endoftext|>


<commit_before>import React from 'react';
import noTextChildNodes from './noTextChildNodes';

class Dom2React {

  constructor(tests) {
    this.tests = tests || [];
  }

  prepareChildren(childNodeList, level) {
    const children = Array.prototype.slice.call(childNodeList).map((node, index) =>
      this.prepareNode(node, level + 1, index)
    ).filter(Boolean);
    if (!children.length) return null;
    return children;
  }

  prepareAttributes(node, reactKey) {
    const attributes = {
      key: reactKey,
    };
    if (node.className) attributes.className = node.className;

    Array.prototype.slice.call(node.attributes).map((att) => {
      switch (att.name) {
        case 'class':
        case 'style':
          break;
        case 'checked':
        case 'selected':
        case 'disabled':
        case 'autoplay':
        case 'controls':
          attributes[att.name] = att.name;
          break;
        default:
          attributes[att.name] = att.value;
      }
      return null;
    });
    return attributes;
  }

  prepareNode(_node, level, index) {
    if (!_node) return null;
    let node = _node;
    const key = `${level}-${index}`;
    const result = [];

    this.tests.forEach((test) => {
      if (test.condition(node, key, level, this)) {
        if (typeof test.modify === 'function') {
          node = test.modify(node, key, level, this);
          if (!(node instanceof Node)) {
            node = _node;
            console.warn('The `modify`-method always must return a valid DomNode (instanceof Node) - your modification will be ignored (Hint: if you want to render a React-component, use the `action`-method instead)');
          }
        }
        if (typeof test.action === 'function') {
          result.push(test.action(node, key, level, this));
        }
      }
    });

    if (result.length) return result;

    switch (node.nodeType) {
      case 1: // regular dom-node
        return React.createElement(
          node.nodeName.toLowerCase(),
          this.prepareAttributes(node, key),
          this.prepareChildren(node.childNodes, level)
        );

      case 3: // textnode
        const nodeText = node.nodeValue.toString();

        if (!node.parentNode) {
          return nodeText;
        }

        const parentNodeName = node.parentNode.nodeName.toLowerCase();

        if (noTextChildNodes.indexOf(parentNodeName) !== -1) {
          if (/\S/.test(nodeText)) {
            console.warn(`a textnode is not allowed inside '${parentNodeName}'. your text "${nodeText}" will be ignored`);
          }
          return null;
        }

        return nodeText;

      case 8: // html-comment
        // console.info(node.nodeValue.toString());
        return null;

      default:
        // console.warn(`unhandled nodetype ${node.nodeType}`);
        return null;
    }
  }

}

export default Dom2React;
<commit_msg>default level for key generation<commit_after>import React from 'react';
import noTextChildNodes from './noTextChildNodes';

class Dom2React {

  constructor(tests) {
    this.tests = tests || [];
  }

  prepareChildren(childNodeList, level) {
    const children = Array.prototype.slice.call(childNodeList).map((node, index) =>
      this.prepareNode(node, level + 1, index)
    ).filter(Boolean);
    if (!children.length) return null;
    return children;
  }

  prepareAttributes(node, reactKey) {
    const attributes = {
      key: reactKey,
    };
    if (node.className) attributes.className = node.className;

    Array.prototype.slice.call(node.attributes).map((att) => {
      switch (att.name) {
        case 'class':
        case 'style':
          break;
        case 'checked':
        case 'selected':
        case 'disabled':
        case 'autoplay':
        case 'controls':
          attributes[att.name] = att.name;
          break;
        default:
          attributes[att.name] = att.value;
      }
      return null;
    });
    return attributes;
  }

  prepareNode(_node, level = 0, index = 0) {
    if (!_node) return null;
    let node = _node;
    const key = `${level}-${index}`;
    const result = [];

    this.tests.forEach((test) => {
      if (test.condition(node, key, level, this)) {
        if (typeof test.modify === 'function') {
          node = test.modify(node, key, level, this);
          if (!(node instanceof Node)) {
            node = _node;
            console.warn('The `modify`-method always must return a valid DomNode (instanceof Node) - your modification will be ignored (Hint: if you want to render a React-component, use the `action`-method instead)');
          }
        }
        if (typeof test.action === 'function') {
          result.push(test.action(node, key, level, this));
        }
      }
    });

    if (result.length) return result;

    switch (node.nodeType) {
      case 1: // regular dom-node
        return React.createElement(
          node.nodeName.toLowerCase(),
          this.prepareAttributes(node, key),
          this.prepareChildren(node.childNodes, level)
        );

      case 3: // textnode
        const nodeText = node.nodeValue.toString();

        if (!node.parentNode) {
          return nodeText;
        }

        const parentNodeName = node.parentNode.nodeName.toLowerCase();

        if (noTextChildNodes.indexOf(parentNodeName) !== -1) {
          if (/\S/.test(nodeText)) {
            console.warn(`a textnode is not allowed inside '${parentNodeName}'. your text "${nodeText}" will be ignored`);
          }
          return null;
        }

        return nodeText;

      case 8: // html-comment
        // console.info(node.nodeValue.toString());
        return null;

      default:
        // console.warn(`unhandled nodetype ${node.nodeType}`);
        return null;
    }
  }

}

export default Dom2React;
<|endoftext|>