<commit_before>/**
 * @license
 * Copyright 2015 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.
 */

CLASS({
  package: 'foam.build',
  name: 'BuildApp',

  imports: [
    'log',
    'error'
  ],
  requires: [
    'foam.dao.NodeFileDAO as FileDAO',
    'foam.dao.File',
    'foam.core.dao.OrDAO',
    'node.dao.ModelFileDAO',
    'foam.build.WebApplication'
  ],
  properties: [
    {
      name: 'appDefinition'
    },
    {
      name: 'controller',
      help: 'Name of the main controller/model to create',
    },
    {
      model_: 'StringArrayProperty',
      name: 'coreFiles',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; }
    },
    {
      name: 'defaultView',
      help: "Default view of the controller to use.  If not set, the controller will be used as view (if it is one), or DetailView will be used"
    },
    {
      name: 'targetPath',
      help: "Directory to write output files to.  Will be created if it doesn't exist.",
      required: true
    },
    {
      model_: 'BooleanProperty',
      name: 'precompileTemplates',
      help: 'True to precompile templates of models loaded from the ModelDAO.',
      defaultValue: false
    },
    {
      model_: 'BooleanProperty',
      name: 'includeFoamCSS',
      defaultValue: false
    },
    {
      model_: 'StringProperty',
      name: 'icon'
    },
    {
      model_: 'StringProperty',
      name: 'version'
    },
    {
      model_: 'StringArrayProperty',
      name: 'resources'
    },
    {
      model_: 'BooleanProperty',
      name: 'appcacheManifest',
      defaultValue: false
    },
    {
      model_: 'StringArrayProperty',
      name: 'extraFiles',
      help: 'Extra files to both load during the build process, and include in the built image.',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; }
    },
    {
      model_: 'StringArrayProperty',
      name: 'extraModels',
      help: 'Extra models to include in the image regardless of if they were arequired or not.',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; },
      factory: function() { return ['foam.ui.FoamTagView']; }
    },
    {
      model_: 'StringArrayProperty',
      name: 'blacklistModels',
      help: 'Models to unconditionally exclude from the image, even if they are listed as required.',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; }
    },
    {
      model_: 'BooleanProperty',
      name: 'outputManifest',
      defaultValue: false,
      help: 'Set to true to write out a MANIFEST file listing all included models.'
    },
    {
      name: 'htmlFileName',
      help: 'Name of the main html file to produce.',
      defaultValue: 'main.html'
    },
    {
      model_: 'StringArrayProperty',
      name: 'htmlHeaders'
    },
    {
      name: 'formatter',
      factory: function() {
        return {
          __proto__: JSONUtil.compact,
          keys_: {},
          keyify: JSONUtil.prettyModel.keyify,
          outputObject_: function(out, obj, opt_defaultModel) {
            var first = true;

            out('{');
            if ( obj.model_.id !== opt_defaultModel ) {
              this.outputModel_(out, obj);
              first = false;
            }

            if ( Template.isInstance(obj) ) var isTemplate = true;

            for ( var key in obj.model_.properties_ ) {
              var prop = obj.model_.properties_[key];

              if ( ! this.p(prop) && ( ! isTemplate || prop.name !== 'code' ) ) continue;

              if ( prop.name === 'documentation' ) continue;

              if ( prop.name in obj.instance_ ) {
                var val = obj[prop.name];
                if ( Array.isArray(val) && ! val.length ) continue;
                if ( ! first ) out(',');
                out(this.keyify(prop.name), ': ');

                if ( prop.name === 'methods' ) {
                  out('{');
                  var ff = true;
                  for ( var i = 0 ; i < val.length ; i++ ) {
                    if ( ! ff ) out(',');

                    out(this.keyify(val[i].name), ': ');
                    out(val[i].code);
                    ff = false;
                  }
                  out('}');
                } else {
                  this.output(out, val);
                }
                first = false;
              }
            }

            out('}');
          }
        };
      }
    },
    {
      name: 'path',
      factory: function() { return require('path'); }
    },
    {
      name: 'fileDAO',
      factory: function() { return this.FileDAO.create(); }
    },
    {
      model_: 'StringArrayProperty',
      name: 'extraClassPaths',
      help: 'List of extra .js hierarchies to load models from.  Paths will be checked in the order given, finally falling back to the main FOAM js/ hierarchy.',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; }
    },
    {
      model_: 'StringProperty',
      name: 'delegate'
    }
  ],
  methods: {
    execute: function() {
      for ( var i = 0; i < this.extraClassPaths.length ; i++ ) {
        this.X.ModelDAO = this.OrDAO.create({
          delegate: this.ModelFileDAO.create({
            classpath: this.extraClassPaths[i]
          }),
          primary: this.X.ModelDAO
        });
      }

      if ( this.appDefinition ) {
        this.X.ModelDAO.find(this.appDefinition, {
          put: function(d) {
            this.copyFrom(d);
            this.execute_();
          }.bind(this),
          error: function() {
            console.log("App definition failed");
            this.execute_();
          }.bind(this)
        });
      } else {
        this.execute_();
      }
    },
    execute_: function() {
      if ( this.delegate ) {
        arequire(this.delegate)(function(DelegateModel) {
          DelegateModel.create({ builder: this }).buildApp();
        });
      } else {
        this.buildApp();
      }
    },
    buildApp: function() {
      if ( ! this.targetPath ) {
        this.error("targetPath is required");
        process.exit(1);
      }
      if ( ! this.controller ) {
        this.error("controller is required");
        process.exit(1);
      }

      for ( var i = 0 ; i < this.extraFiles.length ; i++ ) {
        require(FOAM_BOOT_DIR + this.path.sep + this.extraFiles[i] + '.js');
      }

      var view = this.defaultView ? arequire(this.defaultView) : anop;

      var seq = [view];
      for ( var i = 0; i < this.extraModels.length ; i++ ) {
        seq.push(arequire(this.extraModels[i]));
      }

      aseq(
        aseq.apply(null, seq),
        arequire(this.controller))(this.buildModel.bind(this));
    },
    buildCoreJS_: function(ret) {
      var i = 0;
      var self = this;
      var corejs = '';
      var file;
      if ( this.coreFiles.length ) var myfiles = this.coreFiles;
      else myfiles = files;
      myfiles = myfiles.concat(this.extraFiles);
      awhile(
        function() { return i < myfiles.length; },
        aif(
          function() {
            file = myfiles[i++];
            if ( Array.isArray(file) ) {
              if ( file[1] == IN_NODEJS )
                return false;
              file = file[0];
            }
            return true;
          },
          aseq(
            function(ret) {
              var path = FOAM_BOOT_DIR + this.path.sep + file + '.js';
              this.fileDAO.find(path, {
                put: ret,
                error: function() {
                  self.error.apply(["Error reading file: ", path].concat(arguments));
                }
              });
            }.bind(this),
            function(ret, file) {
              corejs += '\n';
              corejs += file.contents;
              ret();
            })))(function() { ret(corejs); });
    },
    buildAppJS_: function(ret) {
      var models = {};
      var visited = {};
      var error = this.error;
      var self = this;

      function add(require) {
        if ( visited[require] ) return;
        visited[require] = true;

        var model = X.lookup(require);
        if ( ! model ) {
          error("Could not load model: ", require);
        }
        if ( model.package &&
             self.blacklistModels.indexOf(model.id) == -1 ) {
          models[model.id] = model;
        }

        model.getAllRequires().forEach(add);
      };
      add(this.controller);
      if ( this.defaultView ) add(this.defaultView);

      for ( var i = 0; i < this.extraModels.length ; i++ ) {
        add(this.extraModels[i]);
      }

      var contents = '';

      var ids = Object.keys(models);
      if ( this.outputManifest ) {
        this.fileDAO.put(this.File.create({
          path: this.targetPath + this.path.sep + 'MANIFEST',
          contents: ids.join('\n')
        }));
      }

      for ( var i = 0; i < ids.length; i++ ) {
        var model = models[ids[i]];
        if ( this.precompileTemplates ) {
          for ( var j = 0 ; j < model.templates.length ; j++ ) {
            var t = model.templates[j];
            // It's safe to remove leading and trailing whitespace from CSS.
            if ( t.name === 'CSS' ) t.template = t.template.split('\n').map(function(s) { return s.trim(); }).join('\n');
            t.code = TemplateUtil.compile(t);
            t.clearProperty('template');
          }
        }
        contents += 'CLASS(';
        var formatter = this.precompileTemplates ? this.formatter : JSONUtil.compact;
        contents += formatter.where(NOT_TRANSIENT).stringifyObject(models[ids[i]], 'Model');
        contents += ')\n';
      }

      ret(contents);
    },
    buildModel: function(model) {
      if ( ! model ) {
        this.error('Could not find model: ', this.controller);
      }
      this.log('Building   ', model.id);
      this.log('Target is: ', this.targetPath);
      this.log(this.precompileTemplates ? '' : 'NOT ', 'pre-compiling templates.');

      var self = this;
      aseq(
        function(ret) {
          var file = this.File.create({
            path: this.targetPath + this.path.sep + this.htmlFileName,
            contents: this.HTML()
          });

          console.log('Writing: ', file.path);
          this.fileDAO.put(file, {
            put: ret,
            error: function() {
              self.error('ERROR writing file: ', file.path);
              process.exit(1);
            }
          });
        }.bind(this),
        aif(this.appcacheManifest,
            function(ret) {
              var file = this.File.create({
                path: this.targetPath + this.path.sep + "app.manifest",
                contents: this.MANIFEST()
              });
              console.log('Writing: ', file.path);
              this.fileDAO.put(file, {
                put: ret,
                error: function() {
                  this.error("ERROR writing file: ", file.path);
                  process.exit(1);
                }
              });
            }.bind(this)),
        apar(
          function(ret) { this.buildCoreJS_(ret); }.bind(this),
          function(ret) { this.buildAppJS_(ret); }.bind(this)),
        function(ret, corejs, appjs) {
          var file = this.File.create({
            path: this.targetPath + this.path.sep + 'foam.js',
            contents: corejs + appjs
          });
          console.log('Writing: ', file.path);
          this.fileDAO.put(file, {
            put: ret,
            error: function() {
              self.error('ERROR writing file: ', file.path);
              process.exit(1);
            }
          });
        }.bind(this)
      )(
        function(){
          process.exit(0);
        });
    }
  },
  templates: [
    function HTML() {/*<html<% if ( this.appcacheManifest ) { %> manifest="app.manifest"<% } %>><meta charset="utf-8"><%= this.htmlHeaders.join('') %><% if ( this.includeFoamCSS ) { %><link rel="stylesheet" type="text/css" href="foam.css"/><% } %><% if ( this.icon ) { %><link rel="icon" sizes="128x128" href="<%= this.icon %>"/><% } %><foam model="<%= this.controller %>"<% if ( this.defaultView ) { %> view="<%= this.defaultView %>"<% } %>></foam>*/},
    function MANIFEST() {/*CACHE MANIFEST
# version <%= this.version %>
<% if ( this.appDefinition ) { %># hash: <%= this.appDefinition.hashCode() %><% } %>

CACHE:
foam.js
<%= this.htmlFileName %>
<% if ( this.includeFoamCSS ) { %>foam.css<% } %>
<% for ( var i = 0 ; i < this.resources.length ; i++ ) { %><%= this.resources[i] %>
<% } %>

NETWORK:
*
*/}
  ]
});
<commit_msg>foam.build.BuildApp: Fix delegate model usage<commit_after>/**
 * @license
 * Copyright 2015 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.
 */

CLASS({
  package: 'foam.build',
  name: 'BuildApp',

  imports: [
    'log',
    'error'
  ],
  requires: [
    'foam.dao.NodeFileDAO as FileDAO',
    'foam.dao.File',
    'foam.core.dao.OrDAO',
    'node.dao.ModelFileDAO',
    'foam.build.WebApplication'
  ],
  properties: [
    {
      name: 'appDefinition'
    },
    {
      name: 'controller',
      help: 'Name of the main controller/model to create',
    },
    {
      model_: 'StringArrayProperty',
      name: 'coreFiles',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; }
    },
    {
      name: 'defaultView',
      help: "Default view of the controller to use.  If not set, the controller will be used as view (if it is one), or DetailView will be used"
    },
    {
      name: 'targetPath',
      help: "Directory to write output files to.  Will be created if it doesn't exist.",
      required: true
    },
    {
      model_: 'BooleanProperty',
      name: 'precompileTemplates',
      help: 'True to precompile templates of models loaded from the ModelDAO.',
      defaultValue: false
    },
    {
      model_: 'BooleanProperty',
      name: 'includeFoamCSS',
      defaultValue: false
    },
    {
      model_: 'StringProperty',
      name: 'icon'
    },
    {
      model_: 'StringProperty',
      name: 'version'
    },
    {
      model_: 'StringArrayProperty',
      name: 'resources'
    },
    {
      model_: 'BooleanProperty',
      name: 'appcacheManifest',
      defaultValue: false
    },
    {
      model_: 'StringArrayProperty',
      name: 'extraFiles',
      help: 'Extra files to both load during the build process, and include in the built image.',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; }
    },
    {
      model_: 'StringArrayProperty',
      name: 'extraModels',
      help: 'Extra models to include in the image regardless of if they were arequired or not.',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; },
      factory: function() { return ['foam.ui.FoamTagView']; }
    },
    {
      model_: 'StringArrayProperty',
      name: 'blacklistModels',
      help: 'Models to unconditionally exclude from the image, even if they are listed as required.',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; }
    },
    {
      model_: 'BooleanProperty',
      name: 'outputManifest',
      defaultValue: false,
      help: 'Set to true to write out a MANIFEST file listing all included models.'
    },
    {
      name: 'htmlFileName',
      help: 'Name of the main html file to produce.',
      defaultValue: 'main.html'
    },
    {
      model_: 'StringArrayProperty',
      name: 'htmlHeaders'
    },
    {
      name: 'formatter',
      factory: function() {
        return {
          __proto__: JSONUtil.compact,
          keys_: {},
          keyify: JSONUtil.prettyModel.keyify,
          outputObject_: function(out, obj, opt_defaultModel) {
            var first = true;

            out('{');
            if ( obj.model_.id !== opt_defaultModel ) {
              this.outputModel_(out, obj);
              first = false;
            }

            if ( Template.isInstance(obj) ) var isTemplate = true;

            for ( var key in obj.model_.properties_ ) {
              var prop = obj.model_.properties_[key];

              if ( ! this.p(prop) && ( ! isTemplate || prop.name !== 'code' ) ) continue;

              if ( prop.name === 'documentation' ) continue;

              if ( prop.name in obj.instance_ ) {
                var val = obj[prop.name];
                if ( Array.isArray(val) && ! val.length ) continue;
                if ( ! first ) out(',');
                out(this.keyify(prop.name), ': ');

                if ( prop.name === 'methods' ) {
                  out('{');
                  var ff = true;
                  for ( var i = 0 ; i < val.length ; i++ ) {
                    if ( ! ff ) out(',');

                    out(this.keyify(val[i].name), ': ');
                    out(val[i].code);
                    ff = false;
                  }
                  out('}');
                } else {
                  this.output(out, val);
                }
                first = false;
              }
            }

            out('}');
          }
        };
      }
    },
    {
      name: 'path',
      factory: function() { return require('path'); }
    },
    {
      name: 'fileDAO',
      factory: function() { return this.FileDAO.create(); }
    },
    {
      model_: 'StringArrayProperty',
      name: 'extraClassPaths',
      help: 'List of extra .js hierarchies to load models from.  Paths will be checked in the order given, finally falling back to the main FOAM js/ hierarchy.',
      adapt: function(_, s) { if ( typeof s === 'string' ) return s.split(','); return s; }
    },
    {
      model_: 'StringProperty',
      name: 'delegate'
    }
  ],
  methods: {
    execute: function() {
      for ( var i = 0; i < this.extraClassPaths.length ; i++ ) {
        this.X.ModelDAO = this.OrDAO.create({
          delegate: this.ModelFileDAO.create({
            classpath: this.extraClassPaths[i]
          }),
          primary: this.X.ModelDAO
        });
      }

      if ( this.appDefinition ) {
        this.X.ModelDAO.find(this.appDefinition, {
          put: function(d) {
            this.copyFrom(d);
            this.execute_();
          }.bind(this),
          error: function() {
            console.log("App definition failed");
            this.execute_();
          }.bind(this)
        });
      } else {
        this.execute_();
      }
    },
    execute_: function() {
      if ( this.delegate ) {
        arequire(this.delegate)(function(DelegateModel) {
          DelegateModel.create({ builder: this }).buildApp();
        }.bind(this));
      } else {
        this.buildApp();
      }
    },
    buildApp: function() {
      if ( ! this.targetPath ) {
        this.error("targetPath is required");
        process.exit(1);
      }
      if ( ! this.controller ) {
        this.error("controller is required");
        process.exit(1);
      }

      for ( var i = 0 ; i < this.extraFiles.length ; i++ ) {
        require(FOAM_BOOT_DIR + this.path.sep + this.extraFiles[i] + '.js');
      }

      var view = this.defaultView ? arequire(this.defaultView) : anop;

      var seq = [view];
      for ( var i = 0; i < this.extraModels.length ; i++ ) {
        seq.push(arequire(this.extraModels[i]));
      }

      aseq(
        aseq.apply(null, seq),
        arequire(this.controller))(this.buildModel.bind(this));
    },
    buildCoreJS_: function(ret) {
      var i = 0;
      var self = this;
      var corejs = '';
      var file;
      if ( this.coreFiles.length ) var myfiles = this.coreFiles;
      else myfiles = files;
      myfiles = myfiles.concat(this.extraFiles);
      awhile(
        function() { return i < myfiles.length; },
        aif(
          function() {
            file = myfiles[i++];
            if ( Array.isArray(file) ) {
              if ( file[1] == IN_NODEJS )
                return false;
              file = file[0];
            }
            return true;
          },
          aseq(
            function(ret) {
              var path = FOAM_BOOT_DIR + this.path.sep + file + '.js';
              this.fileDAO.find(path, {
                put: ret,
                error: function() {
                  self.error.apply(["Error reading file: ", path].concat(arguments));
                }
              });
            }.bind(this),
            function(ret, file) {
              corejs += '\n';
              corejs += file.contents;
              ret();
            })))(function() { ret(corejs); });
    },
    buildAppJS_: function(ret) {
      var models = {};
      var visited = {};
      var error = this.error;
      var self = this;

      function add(require) {
        if ( visited[require] ) return;
        visited[require] = true;

        var model = X.lookup(require);
        if ( ! model ) {
          error("Could not load model: ", require);
        }
        if ( model.package &&
             self.blacklistModels.indexOf(model.id) == -1 ) {
          models[model.id] = model;
        }

        model.getAllRequires().forEach(add);
      };
      add(this.controller);
      if ( this.defaultView ) add(this.defaultView);

      for ( var i = 0; i < this.extraModels.length ; i++ ) {
        add(this.extraModels[i]);
      }

      var contents = '';

      var ids = Object.keys(models);
      if ( this.outputManifest ) {
        this.fileDAO.put(this.File.create({
          path: this.targetPath + this.path.sep + 'MANIFEST',
          contents: ids.join('\n')
        }));
      }

      for ( var i = 0; i < ids.length; i++ ) {
        var model = models[ids[i]];
        if ( this.precompileTemplates ) {
          for ( var j = 0 ; j < model.templates.length ; j++ ) {
            var t = model.templates[j];
            // It's safe to remove leading and trailing whitespace from CSS.
            if ( t.name === 'CSS' ) t.template = t.template.split('\n').map(function(s) { return s.trim(); }).join('\n');
            t.code = TemplateUtil.compile(t);
            t.clearProperty('template');
          }
        }
        contents += 'CLASS(';
        var formatter = this.precompileTemplates ? this.formatter : JSONUtil.compact;
        contents += formatter.where(NOT_TRANSIENT).stringifyObject(models[ids[i]], 'Model');
        contents += ')\n';
      }

      ret(contents);
    },
    buildModel: function(model) {
      if ( ! model ) {
        this.error('Could not find model: ', this.controller);
      }
      this.log('Building   ', model.id);
      this.log('Target is: ', this.targetPath);
      this.log(this.precompileTemplates ? '' : 'NOT ', 'pre-compiling templates.');

      var self = this;
      aseq(
        function(ret) {
          var file = this.File.create({
            path: this.targetPath + this.path.sep + this.htmlFileName,
            contents: this.HTML()
          });

          console.log('Writing: ', file.path);
          this.fileDAO.put(file, {
            put: ret,
            error: function() {
              self.error('ERROR writing file: ', file.path);
              process.exit(1);
            }
          });
        }.bind(this),
        aif(this.appcacheManifest,
            function(ret) {
              var file = this.File.create({
                path: this.targetPath + this.path.sep + "app.manifest",
                contents: this.MANIFEST()
              });
              console.log('Writing: ', file.path);
              this.fileDAO.put(file, {
                put: ret,
                error: function() {
                  this.error("ERROR writing file: ", file.path);
                  process.exit(1);
                }
              });
            }.bind(this)),
        apar(
          function(ret) { this.buildCoreJS_(ret); }.bind(this),
          function(ret) { this.buildAppJS_(ret); }.bind(this)),
        function(ret, corejs, appjs) {
          var file = this.File.create({
            path: this.targetPath + this.path.sep + 'foam.js',
            contents: corejs + appjs
          });
          console.log('Writing: ', file.path);
          this.fileDAO.put(file, {
            put: ret,
            error: function() {
              self.error('ERROR writing file: ', file.path);
              process.exit(1);
            }
          });
        }.bind(this)
      )(
        function(){
          process.exit(0);
        });
    }
  },
  templates: [
    function HTML() {/*<html<% if ( this.appcacheManifest ) { %> manifest="app.manifest"<% } %>><meta charset="utf-8"><%= this.htmlHeaders.join('') %><% if ( this.includeFoamCSS ) { %><link rel="stylesheet" type="text/css" href="foam.css"/><% } %><% if ( this.icon ) { %><link rel="icon" sizes="128x128" href="<%= this.icon %>"/><% } %><foam model="<%= this.controller %>"<% if ( this.defaultView ) { %> view="<%= this.defaultView %>"<% } %>></foam>*/},
    function MANIFEST() {/*CACHE MANIFEST
# version <%= this.version %>
<% if ( this.appDefinition ) { %># hash: <%= this.appDefinition.hashCode() %><% } %>

CACHE:
foam.js
<%= this.htmlFileName %>
<% if ( this.includeFoamCSS ) { %>foam.css<% } %>
<% for ( var i = 0 ; i < this.resources.length ; i++ ) { %><%= this.resources[i] %>
<% } %>

NETWORK:
*
*/}
  ]
});
<|endoftext|>


<commit_before>import Controller from '@ember/controller';
import { computed, get, set, observer } from '@ember/object';
import { next } from '@ember/runloop';
import C from 'ui/utils/constants';

const HEADERS = [
  {
    name:           'state',
    sort:           ['state', 'name'],
    translationKey: 'generic.state',
    type:           'string',
    width:          125,
  },
  {
    name:           'name',
    sort:           ['name'],
    translationKey: 'rolesPage.index.table.name',
  },
  {
    name:           'builtin',
    sort:           ['builtin'],
    translationKey: 'rolesPage.index.table.builtin',
    width:          120,
  },
  {
    name:           'Default',
    sort:           ['newUserDefault', 'clusterCreatorDefault', 'projectCreatorDefault'],
    translationKey: 'rolesPage.index.table.global',
    width:          120,
  },
  {
    classNames:     'text-right pr-20',
    name:           'created',
    sort:           ['created'],
    translationKey: 'generic.created',
    width:          250,
  },
];

export default Controller.extend({
  queryParams:      ['context'],

  sortBy:           'name',
  context:          'global',
  searchText:       '',
  headers:          null,
  showOnlyDefaults: false,

  _showOnlyDefaults: observer('showOnlyDefaults', function() {
    this.send('changeView', get(this, 'context'));
  }),

  readableMode: computed('context', function() {
    return get(this, 'context').capitalize();
  }),

  globalRows: computed('model.globalRoles.@each.{name,state}', function() {
    return get(this, 'model.globalRoles');
  }),

  projectRows: computed('model.roleTemplates.@each.{name,state}', function() {
    // context should not be blank but if it is include it here as well, we removed it from the UI but you could still create a role without context via api
    return get(this, 'model.roleTemplates').filter( (role ) => !get(role, 'hidden') && (get(role, 'context') !== 'cluster' || !role.hasOwnProperty('context')));
  }),

  clusterRows: computed('model.roleTemplates.@each.{name,state}', function() {
    // context should not be blank but if it is include it here as well, we removed it from the UI but you could still create a role without context via api
    return get(this, 'model.roleTemplates').filter( (role ) => !get(role, 'hidden') && (get(role, 'context') !== 'project') || !role.hasOwnProperty('context'));
  }),

  filteredContent: computed('context', 'model.roleTemplates.@each.{name,state,transitioning}', function() {
    let content                       = null;
    const { context, showOnlyDefaults } = this;
    let headers                       = [...HEADERS];
    const dynamicHeader               = headers.findBy('name', 'Default');
    let nueTranslationKey             = '';

    switch (context) {
    case 'cluster':
      content = get(this, 'clusterRows');

      if (showOnlyDefaults) {
        content = content.filterBy('clusterCreatorDefault');
      }

      nueTranslationKey = 'rolesPage.index.table.cluster';

      break;
    case 'project':
      content = get(this, 'projectRows');

      if (showOnlyDefaults) {
        content = content.filterBy('projectCreatorDefault');
      }

      nueTranslationKey = 'rolesPage.index.table.project';

      break;
    case 'global':
      content = get(this, 'globalRows');
      headers = headers.filter((header) => header.name !== 'builtin');

      if (showOnlyDefaults) {
        content = content.filterBy('newUserDefault');
      }

      nueTranslationKey = 'rolesPage.index.table.global';

      break;
    default:
      break;
    }

    set(dynamicHeader, 'translationKey', nueTranslationKey);

    next(() => {
      set(this, 'headers', headers);
    })

    return content.filter((row) => C.ACTIVEISH_STATES.includes(row.state));
  }),
});
<commit_msg>Remove call to missing action for roles page<commit_after>import Controller from '@ember/controller';
import { computed, get, set, observer } from '@ember/object';
import { next } from '@ember/runloop';
import C from 'ui/utils/constants';

const HEADERS = [
  {
    name:           'state',
    sort:           ['state', 'name'],
    translationKey: 'generic.state',
    type:           'string',
    width:          125,
  },
  {
    name:           'name',
    sort:           ['name'],
    translationKey: 'rolesPage.index.table.name',
  },
  {
    name:           'builtin',
    sort:           ['builtin'],
    translationKey: 'rolesPage.index.table.builtin',
    width:          120,
  },
  {
    name:           'Default',
    sort:           ['newUserDefault', 'clusterCreatorDefault', 'projectCreatorDefault'],
    translationKey: 'rolesPage.index.table.global',
    width:          120,
  },
  {
    classNames:     'text-right pr-20',
    name:           'created',
    sort:           ['created'],
    translationKey: 'generic.created',
    width:          250,
  },
];

export default Controller.extend({
  queryParams:      ['context'],

  sortBy:           'name',
  context:          'global',
  searchText:       '',
  headers:          null,
  showOnlyDefaults: false,

  readableMode: computed('context', function() {
    return get(this, 'context').capitalize();
  }),

  globalRows: computed('model.globalRoles.@each.{name,state}', function() {
    return get(this, 'model.globalRoles');
  }),

  projectRows: computed('model.roleTemplates.@each.{name,state}', function() {
    // context should not be blank but if it is include it here as well, we removed it from the UI but you could still create a role without context via api
    return get(this, 'model.roleTemplates').filter( (role ) => !get(role, 'hidden') && (get(role, 'context') !== 'cluster' || !role.hasOwnProperty('context')));
  }),

  clusterRows: computed('model.roleTemplates.@each.{name,state}', function() {
    // context should not be blank but if it is include it here as well, we removed it from the UI but you could still create a role without context via api
    return get(this, 'model.roleTemplates').filter( (role ) => !get(role, 'hidden') && (get(role, 'context') !== 'project') || !role.hasOwnProperty('context'));
  }),

  filteredContent: computed('context', 'model.roleTemplates.@each.{name,state,transitioning}', 'showOnlyDefaults', function() {
    let content                       = null;
    const { context, showOnlyDefaults } = this;
    let headers                       = [...HEADERS];
    const dynamicHeader               = headers.findBy('name', 'Default');
    let nueTranslationKey             = '';

    switch (context) {
    case 'cluster':
      content = get(this, 'clusterRows');

      if (showOnlyDefaults) {
        content = content.filterBy('clusterCreatorDefault');
      }

      nueTranslationKey = 'rolesPage.index.table.cluster';

      break;
    case 'project':
      content = get(this, 'projectRows');

      if (showOnlyDefaults) {
        content = content.filterBy('projectCreatorDefault');
      }

      nueTranslationKey = 'rolesPage.index.table.project';

      break;
    case 'global':
      content = get(this, 'globalRows');
      headers = headers.filter((header) => header.name !== 'builtin');

      if (showOnlyDefaults) {
        content = content.filterBy('newUserDefault');
      }

      nueTranslationKey = 'rolesPage.index.table.global';

      break;
    default:
      break;
    }

    set(dynamicHeader, 'translationKey', nueTranslationKey);

    next(() => {
      set(this, 'headers', headers);
    })

    return content.filter((row) => C.ACTIVEISH_STATES.includes(row.state) || row.type === 'globalRole');
  }),
});
<|endoftext|>


<commit_before>import React from 'react';

export default class BookmarkButton extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      bookmarked: false,
      pageId: null,
      token: null,
    };

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

  componentWillMount() {
    // FIXME(property?)
    this.setState({
      pageId: $('#content-main').data('page-id'),
      token: $('#bookmark-button').data('csrftoken'),
    });
  }

  componentDidMount() {
    $.get('/_api/bookmarks.get', {page_id: this.state.pageId}, (res) => {
      if (res.ok) {
        if (res.bookmark) {
          this.markBookmarked();
        }
      }
    });
  }

  handleClick(event) {
    event.preventDefault();

    const token = this.state.token;
    const pageId = this.state.pageId;

    if (!this.state.bookmarked) {
      $.post('/_api/bookmarks.add', {_csrf: token, page_id: pageId}, (res) => {
        if (res.ok && res.bookmark) {
          this.markBookmarked();
        }
      });
    } else {
      $.post('/_api/bookmarks.remove', {_csrf: token, page_id: pageId}, (res) => {
        if (res.ok) {
          this.markUnBookmarked();
        }
      });
    }
  }

  markBookmarked() {
    this.setState({bookmarked: true});
  }

  markUnBookmarked() {
    this.setState({bookmarked: false});
  }

  render() {
    const className = this.state.bookmarked ? 'fa fa-star' : 'fa fa-star-o';

    return (

    );
  }
}
<commit_msg>Use Icon component<commit_after>import React from 'react';

import Icon from './Common/Icon'

export default class BookmarkButton extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      bookmarked: false,
      pageId: null,
      token: null,
    };

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

  componentWillMount() {
    // FIXME(property?)
    this.setState({
      pageId: $('#content-main').data('page-id'),
      token: $('#bookmark-button').data('csrftoken'),
    });
  }

  componentDidMount() {
    $.get('/_api/bookmarks.get', {page_id: this.state.pageId}, (res) => {
      if (res.ok) {
        if (res.bookmark) {
          this.markBookmarked();
        }
      }
    });
  }

  handleClick(event) {
    event.preventDefault();

    const token = this.state.token;
    const pageId = this.state.pageId;

    if (!this.state.bookmarked) {
      $.post('/_api/bookmarks.add', {_csrf: token, page_id: pageId}, (res) => {
        if (res.ok && res.bookmark) {
          this.markBookmarked();
        }
      });
    } else {
      $.post('/_api/bookmarks.remove', {_csrf: token, page_id: pageId}, (res) => {
        if (res.ok) {
          this.markUnBookmarked();
        }
      });
    }
  }

  markBookmarked() {
    this.setState({bookmarked: true});
  }

  markUnBookmarked() {
    this.setState({bookmarked: false});
  }

  render() {
    const iconName = this.state.bookmarked ? 'star' : 'star-o';

    return (

        <Icon name={iconName} />

    );
  }
}
<|endoftext|>


<commit_before>
'use strict';

var debug = require('debug')('proxive:organizations');

function organizations(config) {

  function getAll(cb) {
    config.mysql.getConnection(function(err, connection) {
      if(err) return cb(err);
      connection.query('SELECT * FROM organizations;', function(err, rows) {
        connection.release();
        debug('getAll: Organizations fetched: '+rows.length);
        cb(err, rows);
      });
    });
  }
  function getAllFiltered(selects, cb) {
    config.mysql.getConnection(function(err, connection) {
      if(err) return cb(err);
      for (var i = selects.length - 1; i >= 0; i--) {
        selects[i] = connection.escapeId(selects[i]);
      }
      debug('getAllFiltered: Selects: '+selects.join(', '));
      connection.query('SELECT '+selects.join(', ')+' FROM organizations;', function(err, rows) {
        connection.release();
        debug('getAllFiltered: Organizations fetched: '+rows.length);
        cb(err, rows);
      });
    });
  }

  function getOrgFromUser(userId, cb) {
    config.mysql.getConnection(function(err, connection) {
      if(err) return cb(err);
      debug('getOrgFromUser: userId: '+userId);
      connection.query('SELECT '+
        'O.organization_id AS id, '+
        'O.organization_name AS name, '+
        'O.organization_assigned_ipv4 AS assignedIPv4, '+
        'O.organization_user_agreement AS userAgreement, '+
        'O.organization_user_email AS userEmail, '+
        'O.organization_email AS email, '+
        'O.organization_direct_to_url AS directToUrl, '+
        'O.organization_direct_url AS directUrl, '+
        'O.organization_homepage_html AS homepageHtml, '+
        'O.organization_pubmed_otool AS pubmedOtool, '+
        'O.organization_wiu_password AS wiuPassword, '+
        'O.organization_wiu_ips AS wiuIps, '+
        'O.organization_wiu_emails AS wiuEmails '+
        'FROM organizations AS O '+
        'INNER JOIN users U ON O.organization_id = U.user_organization_id '+
        'WHERE U.user_id = '+connection.escape(userId)+';',
        function(err, rows) {
          if(err) return cb(err);
          connection.release();
          if(rows.length === 0) {
            debug('getOrgFromUser: No organization found!');
            return cb('no-org', null);
          }
          cb(null, rows[0]);
        }
      );
    });
  }

  function getLimitedOrgFromUser(userId, cb) {
    config.mysql.getConnection(function(err, connection) {
      if(err) return cb(err);
      debug('getOrgFromUser: userId: '+userId);
      connection.query('SELECT O.organization_id AS id, '+
        'O.organization_user_agreement AS userAgreement, '+
        'O.organization_direct_to_url AS directToUrl, '+
        'O.organization_direct_url AS directUrl, '+
        'O.organization_email AS email '+
        'FROM organizations O '+
        'INNER JOIN users U ON O.organization_id = U.user_organization_id '+
        'WHERE U.user_id = '+connection.escape(userId)+';', function(err, rows) {
        connection.release();
        if(rows.length === 0) {
          debug('getOrgFromUser: No organization found!');
          return cb('no-org', null);
        }
        cb(null, rows[0]);
      });
    });
  }

  function getConnectIp(userId, cb) {
    debug('getConnectIp: userId:'+userId);
    if(typeof userId !== 'string' && typeof userId !== 'number')
      return cb('invalid-input');
    config.redisClient.get('users-org-ip:'+userId, function(err, reply) {
      if(err) return cb(err);
      if(reply !== null) {
        return cb(null, reply);
      }
      debug('getConnectIp: redis didn\'t have the ip');
      config.mysql.getConnection(function(err, connection) {
        if(err) return cb(err);
        connection.query('SELECT O.organization_assigned_ipv4 AS assignedIp FROM organizations O '+
          'INNER JOIN users U ON O.organization_id = U.user_organization_id '+
          'WHERE U.user_id = '+connection.escape(userId)+';', function(err, rows) {
          connection.release();
          if(err) return cb(err);
          if(rows.length === 0) {
            return cb('organization-not-found');
          }
          config.redisClient.set('users-org-ip:'+userId, rows[0].assignedIp, function(err) {
            if(err) return cb(err);
            debug('getConnectIp: redis should have the ip now');
            cb(null, rows[0].assignedIp);
          });
        });
      });
    });
  }

  function organization() {
    return true;
  }

  organization.getAll             = getAll;
  organization.getAllFiltered     = getAllFiltered;
  organization.getLimitedFromUser = getLimitedOrgFromUser;
  organization.getFromUser        = getOrgFromUser;
  organization.getConnectIp       = getConnectIp;

  return organization;
}

module.exports = organizations;<commit_msg>Add email title field to database<commit_after>
'use strict';

var debug = require('debug')('proxive:organizations');

function organizations(config) {

  function getAll(cb) {
    config.mysql.getConnection(function(err, connection) {
      if(err) return cb(err);
      connection.query('SELECT * FROM organizations;', function(err, rows) {
        connection.release();
        debug('getAll: Organizations fetched: '+rows.length);
        cb(err, rows);
      });
    });
  }
  function getAllFiltered(selects, cb) {
    config.mysql.getConnection(function(err, connection) {
      if(err) return cb(err);
      for (var i = selects.length - 1; i >= 0; i--) {
        selects[i] = connection.escapeId(selects[i]);
      }
      debug('getAllFiltered: Selects: '+selects.join(', '));
      connection.query('SELECT '+selects.join(', ')+' FROM organizations;', function(err, rows) {
        connection.release();
        debug('getAllFiltered: Organizations fetched: '+rows.length);
        cb(err, rows);
      });
    });
  }

  function getOrgFromUser(userId, cb) {
    config.mysql.getConnection(function(err, connection) {
      if(err) return cb(err);
      debug('getOrgFromUser: userId: '+userId);
      connection.query('SELECT '+
        'O.organization_id AS id, '+
        'O.organization_name AS name, '+
        'O.organization_assigned_ipv4 AS assignedIPv4, '+
        'O.organization_user_agreement AS userAgreement, '+
        'O.organization_user_email_title AS userEmailTitle, '+
        'O.organization_user_email AS userEmail, '+
        'O.organization_email AS email, '+
        'O.organization_direct_to_url AS directToUrl, '+
        'O.organization_direct_url AS directUrl, '+
        'O.organization_homepage_html AS homepageHtml, '+
        'O.organization_pubmed_otool AS pubmedOtool, '+
        'O.organization_wiu_password AS wiuPassword, '+
        'O.organization_wiu_ips AS wiuIps, '+
        'O.organization_wiu_emails AS wiuEmails '+
        'FROM organizations AS O '+
        'INNER JOIN users U ON O.organization_id = U.user_organization_id '+
        'WHERE U.user_id = '+connection.escape(userId)+';',
        function(err, rows) {
          if(err) return cb(err);
          connection.release();
          if(rows.length === 0) {
            debug('getOrgFromUser: No organization found!');
            return cb('no-org', null);
          }
          cb(null, rows[0]);
        }
      );
    });
  }

  function getLimitedOrgFromUser(userId, cb) {
    config.mysql.getConnection(function(err, connection) {
      if(err) return cb(err);
      debug('getOrgFromUser: userId: '+userId);
      connection.query('SELECT O.organization_id AS id, '+
        'O.organization_user_agreement AS userAgreement, '+
        'O.organization_direct_to_url AS directToUrl, '+
        'O.organization_direct_url AS directUrl, '+
        'O.organization_email AS email '+
        'FROM organizations O '+
        'INNER JOIN users U ON O.organization_id = U.user_organization_id '+
        'WHERE U.user_id = '+connection.escape(userId)+';', function(err, rows) {
        connection.release();
        if(rows.length === 0) {
          debug('getOrgFromUser: No organization found!');
          return cb('no-org', null);
        }
        cb(null, rows[0]);
      });
    });
  }

  function getConnectIp(userId, cb) {
    debug('getConnectIp: userId:'+userId);
    if(typeof userId !== 'string' && typeof userId !== 'number')
      return cb('invalid-input');
    config.redisClient.get('users-org-ip:'+userId, function(err, reply) {
      if(err) return cb(err);
      if(reply !== null) {
        return cb(null, reply);
      }
      debug('getConnectIp: redis didn\'t have the ip');
      config.mysql.getConnection(function(err, connection) {
        if(err) return cb(err);
        connection.query('SELECT O.organization_assigned_ipv4 AS assignedIp FROM organizations O '+
          'INNER JOIN users U ON O.organization_id = U.user_organization_id '+
          'WHERE U.user_id = '+connection.escape(userId)+';', function(err, rows) {
          connection.release();
          if(err) return cb(err);
          if(rows.length === 0) {
            return cb('organization-not-found');
          }
          config.redisClient.set('users-org-ip:'+userId, rows[0].assignedIp, function(err) {
            if(err) return cb(err);
            debug('getConnectIp: redis should have the ip now');
            cb(null, rows[0].assignedIp);
          });
        });
      });
    });
  }

  function organization() {
    return true;
  }

  organization.getAll             = getAll;
  organization.getAllFiltered     = getAllFiltered;
  organization.getLimitedFromUser = getLimitedOrgFromUser;
  organization.getFromUser        = getOrgFromUser;
  organization.getConnectIp       = getConnectIp;

  return organization;
}

module.exports = organizations;<|endoftext|>


<commit_before>//This guy is inteneded to map a "User Id" to socket io session Id.  Usefull for our api

var userManager = require("./userManager");
var utils = require("./utils");

function sendMessage(userId, data){
	var socket = userManager.getUser( userId );
	socket.emit('message', data);
}

function createRoom(room, users){
	for(var i = 0,  l = users.length; i < l; i ++){
		var user = userManager.getUser(users[i]);
		console.log("user" + user.id);
		user.joinRoom(room);
	}
}

function sendRoomMessage(room, username, message){
	io.sockets.in( room.toString() ).emit('roomMessage', {room: room, username: username, message: message});
}

//Now so we can communicate with other web services
var journey = require('journey'),
	http = require('http');

var router = new(journey.Router);

router.map(function () {
    this.root.bind(function (req, res) { res.send("Welcome") });
    router.get('/test').bind(function (req, res, params){
    	res.send(200, {}, "Success");
    });
    router.post('/command').bind(function (req, res, params) {
    	var data = JSON.parse( params.data );
    	console.log(params.command);
    	console.log(utils.dump(data));
    	switch(params.command){
    		case "send":
    			sendMessage(data.userId, data.data);
    			res.send(200, {}, {success:true});
    			break;
    		case "createRoom":
    			createRoom(data.room, data.users);
    			res.send(200, {}, {success:true});
    			break;

    	}
	});
});

var api = http.createServer(function (request, response) {
    var body = "";

    request.addListener('data', function (chunk) { body += chunk });
    request.addListener('end', function () {
        //
        // Dispatch the request to the router
        //
        router.handle(request, body, function (result) {
            response.writeHead(result.status, result.headers);
            response.end(result.body);
        });
    });
});

api.listen(8080);
//Bellow is the socket io magic, love this tuff
var io = require('socket.io').listen(api);

io.sockets.on('connection', function (socket) {
	socket.on('register', function (data) {
		console.log("Regiser: " + data.userId + " , " + socket.id);
		var user =  userManager.addUser(data.userId, socket);
		//setUpRooms(user);
	});

	socket.on('room', function( data ){
		console.log("room msg recieved");
		sendRoomMessage(data.room, data.username, data.message);
	});

	socket.on('disconnect', function (data) {
		userManager.removeUser(socket.id);
     });
});
<commit_msg>found bug that caused regular message send ot fail<commit_after>//This guy is inteneded to map a "User Id" to socket io session Id.  Usefull for our api

var userManager = require("./userManager");
var utils = require("./utils");

function sendMessage(userId, data){
	var user = userManager.getUser( userId );
	user.socket.emit('message', data);
}

function createRoom(room, users){
	for(var i = 0,  l = users.length; i < l; i ++){
		var user = userManager.getUser(users[i]);
		console.log("user" + user.id);
		user.joinRoom(room);
	}
}

function sendRoomMessage(room, username, message){
	io.sockets.in( room.toString() ).emit('roomMessage', {room: room, username: username, message: message});
}

//Now so we can communicate with other web services
var journey = require('journey'),
	http = require('http');

var router = new(journey.Router);

router.map(function () {
    this.root.bind(function (req, res) { res.send("Welcome") });
    router.get('/test').bind(function (req, res, params){
    	res.send(200, {}, "Success");
    });
    router.post('/command').bind(function (req, res, params) {
    	var data = JSON.parse( params.data );
    	console.log(params.command);
    	console.log(utils.dump(data));
    	switch(params.command){
    		case "send":
    			sendMessage(data.userId, data.data);
    			res.send(200, {}, {success:true});
    			break;
    		case "createRoom":
    			createRoom(data.room, data.users);
    			res.send(200, {}, {success:true});
    			break;

    	}
	});
});

var api = http.createServer(function (request, response) {
    var body = "";

    request.addListener('data', function (chunk) { body += chunk });
    request.addListener('end', function () {
        //
        // Dispatch the request to the router
        //
        router.handle(request, body, function (result) {
            response.writeHead(result.status, result.headers);
            response.end(result.body);
        });
    });
});

api.listen(8080);
//Bellow is the socket io magic, love this tuff
var io = require('socket.io').listen(api);

io.sockets.on('connection', function (socket) {
	socket.on('register', function (data) {
		console.log("Regiser: " + data.userId + " , " + socket.id);
		var user =  userManager.addUser(data.userId, socket);
		//setUpRooms(user);
	});

	socket.on('room', function( data ){
		console.log("room msg recieved");
		sendRoomMessage(data.room, data.username, data.message);
	});

	socket.on('disconnect', function (data) {
		userManager.removeUser(socket.id);
     });
});
<|endoftext|>


<commit_before>/**
 * Class description
 *
 * @class ClassName
 * @constructor
 * @param x {Number} the x coordinate on the canvas
 * @param y {Number} the y coordinate on the canvas
 */

var TemplateSelector = Class.create( {

    initialize: function(isStartupTemplateSelector) {
        this.mainDiv = new Element('div', {'class': 'template-picture-container'});
        this.mainDiv.update("Loading list of templates...");
        this.dialog = new MS.widgets.ModalPopup(this.mainDiv, false, {extraClassName: "pedigree-template-chooser", title: "Please select a pedigree template", displayCloseButton: !isStartupTemplateSelector});
        isStartupTemplateSelector && this.dialog.show();
        new Ajax.Request(new XWiki.Document('WebHome').getRestURL('objects/PhenoTips.PedigreeClass/'), {
            method: 'GET',
            onSuccess: this.onTemplateListAvailable.bind(this)
        });
    },
    onTemplateListAvailable: function(response) {
        this.mainDiv.update();
        var objects = response.responseXML.documentElement.getElementsByTagName('objectSummary');
        for (var i = 0; i < objects.length; ++i) {
            var pictureBox = new Element('div', {'class': 'picture-box'});
            pictureBox.update("Loading...");
            this.mainDiv.insert(pictureBox);
            new Ajax.Request(objects[i].querySelector("link[rel='http://www.xwiki.org/rel/properties']").getAttribute("href"), {
                method: 'GET',
                onSuccess: this.onTemplateAvailable.bind(this, pictureBox)
            });
        }
    },

    onTemplateAvailable: function(pictureBox, response) {
        pictureBox.innerHTML = response.responseXML.documentElement.querySelector("property[name='data'] > value").textContent.replace(/&/, '&');
        pictureBox.pedigreeData = JSON.parse(pictureBox.textContent);
        pictureBox.innerHTML = response.responseXML.documentElement.querySelector("property[name='image'] > value").textContent.replace(/&/, '&');
        pictureBox.innerHTML = pictureBox.textContent;
        pictureBox.observe('click', this.onTemplateSelected.bindAsEventListener(this, pictureBox));
    },

    onTemplateSelected: function(event, pictureBox) {
        this.dialog.close();
        editor.getSaveLoadEngine().load(pictureBox.pedigreeData);
    },

    show: function() {
        this.dialog.show();
    },

    hide: function() {
        this.dialog.close();
    }
});<commit_msg>Changed template selector to use undo-able load method<commit_after>/**
 * Class description
 *
 * @class ClassName
 * @constructor
 * @param x {Number} the x coordinate on the canvas
 * @param y {Number} the y coordinate on the canvas
 */

var TemplateSelector = Class.create( {

    initialize: function(isStartupTemplateSelector) {
        this._isStartupTemplateSelector = isStartupTemplateSelector;
        this.mainDiv = new Element('div', {'class': 'template-picture-container'});
        this.mainDiv.update("Loading list of templates...");
        var closeShortcut = isStartupTemplateSelector ? [] : ['Esc'];
        this.dialog = new MS.widgets.ModalPopup(this.mainDiv, {close: {method : this.closeDialog.bind(this), keys : closeShortcut}}, {extraClassName: "pedigree-template-chooser", title: "Please select a pedigree template", displayCloseButton: !isStartupTemplateSelector});
        isStartupTemplateSelector && this.dialog.show();
        new Ajax.Request(new XWiki.Document('WebHome').getRestURL('objects/PhenoTips.PedigreeClass/'), {
            method: 'GET',
            onSuccess: this.onTemplateListAvailable.bind(this)
        });
    },

    isStartupTemplateSelector: function() {
        return this._isStartupTemplateSelector;
    },

    onTemplateListAvailable: function(response) {
        this.mainDiv.update();
        var objects = response.responseXML.documentElement.getElementsByTagName('objectSummary');
        for (var i = 0; i < objects.length; ++i) {
            var pictureBox = new Element('div', {'class': 'picture-box'});
            pictureBox.update("Loading...");
            this.mainDiv.insert(pictureBox);
            new Ajax.Request(objects[i].querySelector("link[rel='http://www.xwiki.org/rel/properties']").getAttribute("href"), {
                method: 'GET',
                onSuccess: this.onTemplateAvailable.bind(this, pictureBox)
            });
        }
    },

    closeDialog: function() {
        this.dialog.closeDialog();
    },

    onTemplateAvailable: function(pictureBox, response) {
        pictureBox.innerHTML = response.responseXML.documentElement.querySelector("property[name='data'] > value").textContent.replace(/&/, '&');
        pictureBox.pedigreeData = JSON.parse(pictureBox.textContent);
        pictureBox.innerHTML = response.responseXML.documentElement.querySelector("property[name='image'] > value").textContent.replace(/&/, '&');
        pictureBox.innerHTML = pictureBox.textContent;
        pictureBox.observe('click', this.onTemplateSelected.bindAsEventListener(this, pictureBox));
    },

    onTemplateSelected: function(event, pictureBox) {
        this.dialog.close();
        alert(this.isStartupTemplateSelector())
        if(this.isStartupTemplateSelector()) {
            editor.getSaveLoadEngine().load(pictureBox.pedigreeData);
        }
        else {
            editor.getSaveLoadEngine().loadTemplateAction(pictureBox.pedigreeData);
        }
    },

    show: function() {
        this.dialog.show();
    },

    hide: function() {
        this.dialog.close();
    }
});<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2014 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.
 */

CLASS({
  package: 'foam.demos',
  name: 'PageView',
  extends: 'foam.ui.SimpleView',
  requires: [
    'foam.ui.navigation.PageView',
    'foam.ui.navigation.TopToolbar',
    'foam.ui.StaticHTML',
  ],
  templates: [
    function toHTML() {/*
      <%=
        this.PageView.create({
          header: this.TopToolbar.create({
            label: 'This is a toolbar',
          }),
          body: this.StaticHTML.create({
            content: 'Hello World',
          }),
          footer: this.TopToolbar.create({
            label: 'This is a toolbar being used as a footer',
          }),
        })
      %>
    */}
  ],
});
<commit_msg>Formatting.<commit_after>/**
 * @license
 * Copyright 2014 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.
 */

CLASS({
  package: 'foam.demos',
  name: 'PageView',
  extends: 'foam.ui.SimpleView',

  requires: [
    'foam.ui.navigation.PageView',
    'foam.ui.navigation.TopToolbar',
    'foam.ui.StaticHTML'
  ],

  templates: [
    function toHTML() {/*
      <%=
        this.PageView.create({
          header: this.TopToolbar.create({
            label: 'This is a toolbar',
          }),
          body: this.StaticHTML.create({
            content: 'Hello World',
          }),
          footer: this.TopToolbar.create({
            label: 'This is a toolbar being used as a footer',
          }),
        })
      %>
    */}
  ]
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 */

'use strict';

import type {TestResult} from 'types/TestResult';

const ansiEscapes = require('ansi-escapes');
const chalk = require('chalk');
const {getTerminalWidth} = require('./lib/terminalUtils');
const stringLength = require('string-length');
const Prompt = require('./lib/Prompt');
const formatTestNameByPattern = require('./lib/formatTestNameByPattern');

const pluralizeTest = (total: number) => (total === 1 ? 'test' : 'tests');

const usage = () =>
  `\n ${chalk.bold('Pattern Mode Usage')}\n` +
  ` ${chalk.dim('\u203A Press')} Esc ${chalk.dim('to exit pattern mode.')}\n` +
  ` ${chalk.dim('\u203A Press')} Enter ` +
  `${chalk.dim('to apply pattern to all tests.')}\n` +
  `\n`;

const usageRows = usage().split('\n').length;

module.exports = class TestNamePatternPrompt {
  _cachedTestResults: Array<TestResult>;
  _pipe: stream$Writable | tty$WriteStream;
  _prompt: Prompt;

  constructor(pipe: stream$Writable | tty$WriteStream, prompt: Prompt) {
    this._pipe = pipe;
    this._prompt = prompt;
  }

  run(onSuccess: Function, onCancel: Function) {
    this._pipe.write(ansiEscapes.cursorHide);
    this._pipe.write(ansiEscapes.clearScreen);
    this._pipe.write(usage());
    this._pipe.write(ansiEscapes.cursorShow);

    this._prompt.enter(this._onChange.bind(this), onSuccess, onCancel);
  }

  _onChange(pattern: string) {
    this._pipe.write(ansiEscapes.eraseLine);
    this._pipe.write(ansiEscapes.cursorLeft);
    this._printTypeahead(pattern, 10);
  }

  _printTypeahead(pattern: string, max: number) {
    const matchedTests = this._getMatchedTests(pattern);

    const total = matchedTests.length;
    const results = matchedTests.slice(0, max);
    const inputText = `${chalk.dim(' pattern \u203A')} ${pattern}`;

    this._pipe.write(ansiEscapes.eraseDown);
    this._pipe.write(inputText);
    this._pipe.write(ansiEscapes.cursorSavePosition);

    if (pattern) {
      if (total) {
        this._pipe.write(
          `\n\n Pattern matches ${total} ${pluralizeTest(total)}`,
        );
      } else {
        this._pipe.write(`\n\n Pattern matches no tests`);
      }

      this._pipe.write(' from cached test suites.');

      const width = getTerminalWidth();

      results.forEach(name => {
        const testName = formatTestNameByPattern(name, pattern, width - 4);

        this._pipe.write(`\n ${chalk.dim('\u203A')} ${testName}`);
      });

      if (total > max) {
        const more = total - max;
        this._pipe.write(
          // eslint-disable-next-line max-len
          `\n  ${chalk.dim(`\u203A and ${more} more ${pluralizeTest(more)}`)}`,
        );
      }
    } else {
      this._pipe.write(
        // eslint-disable-next-line max-len
        `\n\n ${chalk.italic.yellow('Start typing to filter by a test name regex pattern.')}`,
      );
    }

    this._pipe.write(
      ansiEscapes.cursorTo(stringLength(inputText), usageRows - 1),
    );
    this._pipe.write(ansiEscapes.cursorRestorePosition);
  }

  _getMatchedTests(pattern: string) {
    let regex;

    try {
      regex = new RegExp(pattern, 'i');
    } catch (e) {
      return [];
    }

    const matchedTests = [];

    this._cachedTestResults.forEach(({testResults}) =>
      testResults.forEach(({title}) => {
        if (regex.test(title)) {
          matchedTests.push(title);
        }
      }),
    );

    return matchedTests;
  }

  updateCachedTestResults(testResults: Array<TestResult>) {
    this._cachedTestResults = testResults || [];
  }
};
<commit_msg>Fix spacing in test name pattern typeahead (#3315)<commit_after>/**
 * Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 */

'use strict';

import type {TestResult} from 'types/TestResult';

const ansiEscapes = require('ansi-escapes');
const chalk = require('chalk');
const {getTerminalWidth} = require('./lib/terminalUtils');
const stringLength = require('string-length');
const Prompt = require('./lib/Prompt');
const formatTestNameByPattern = require('./lib/formatTestNameByPattern');

const pluralizeTest = (total: number) => (total === 1 ? 'test' : 'tests');

const usage = () =>
  `\n ${chalk.bold('Pattern Mode Usage')}\n` +
  ` ${chalk.dim('\u203A Press')} Esc ${chalk.dim('to exit pattern mode.')}\n` +
  ` ${chalk.dim('\u203A Press')} Enter ` +
  `${chalk.dim('to apply pattern to all tests.')}\n` +
  `\n`;

const usageRows = usage().split('\n').length;

module.exports = class TestNamePatternPrompt {
  _cachedTestResults: Array<TestResult>;
  _pipe: stream$Writable | tty$WriteStream;
  _prompt: Prompt;

  constructor(pipe: stream$Writable | tty$WriteStream, prompt: Prompt) {
    this._pipe = pipe;
    this._prompt = prompt;
  }

  run(onSuccess: Function, onCancel: Function) {
    this._pipe.write(ansiEscapes.cursorHide);
    this._pipe.write(ansiEscapes.clearScreen);
    this._pipe.write(usage());
    this._pipe.write(ansiEscapes.cursorShow);

    this._prompt.enter(this._onChange.bind(this), onSuccess, onCancel);
  }

  _onChange(pattern: string) {
    this._pipe.write(ansiEscapes.eraseLine);
    this._pipe.write(ansiEscapes.cursorLeft);
    this._printTypeahead(pattern, 10);
  }

  _printTypeahead(pattern: string, max: number) {
    const matchedTests = this._getMatchedTests(pattern);

    const total = matchedTests.length;
    const results = matchedTests.slice(0, max);
    const inputText = `${chalk.dim(' pattern \u203A')} ${pattern}`;

    this._pipe.write(ansiEscapes.eraseDown);
    this._pipe.write(inputText);
    this._pipe.write(ansiEscapes.cursorSavePosition);

    if (pattern) {
      if (total) {
        this._pipe.write(
          `\n\n Pattern matches ${total} ${pluralizeTest(total)}`,
        );
      } else {
        this._pipe.write(`\n\n Pattern matches no tests`);
      }

      this._pipe.write(' from cached test suites.');

      const width = getTerminalWidth();

      results.forEach(name => {
        const testName = formatTestNameByPattern(name, pattern, width - 4);

        this._pipe.write(`\n ${chalk.dim('\u203A')} ${testName}`);
      });

      if (total > max) {
        const more = total - max;
        this._pipe.write(
          // eslint-disable-next-line max-len
          `\n ${chalk.dim(`\u203A and ${more} more ${pluralizeTest(more)}`)}`,
        );
      }
    } else {
      this._pipe.write(
        // eslint-disable-next-line max-len
        `\n\n ${chalk.italic.yellow('Start typing to filter by a test name regex pattern.')}`,
      );
    }

    this._pipe.write(
      ansiEscapes.cursorTo(stringLength(inputText), usageRows - 1),
    );
    this._pipe.write(ansiEscapes.cursorRestorePosition);
  }

  _getMatchedTests(pattern: string) {
    let regex;

    try {
      regex = new RegExp(pattern, 'i');
    } catch (e) {
      return [];
    }

    const matchedTests = [];

    this._cachedTestResults.forEach(({testResults}) =>
      testResults.forEach(({title}) => {
        if (regex.test(title)) {
          matchedTests.push(title);
        }
      }),
    );

    return matchedTests;
  }

  updateCachedTestResults(testResults: Array<TestResult>) {
    this._cachedTestResults = testResults || [];
  }
};
<|endoftext|>


<commit_before>'use strict'; // eslint-disable-line

const webpack = require('webpack');
const merge = require('webpack-merge');
const CleanPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const CopyGlobsPlugin = require('copy-globs-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

const config = require('./config');

const assetsFilenames = (config.enabled.cacheBusting) ? config.cacheBusting : '[name]';

let webpackConfig = {
  context: config.paths.assets,
  entry: config.entry,
  devtool: (config.enabled.sourceMaps ? '#source-map' : undefined),
  output: {
    path: config.paths.dist,
    publicPath: config.publicPath,
    filename: `scripts/${assetsFilenames}.js`,
  },
  stats: {
    hash: false,
    version: false,
    timings: false,
    children: false,
    errors: false,
    errorDetails: false,
    warnings: false,
    chunks: false,
    modules: false,
    reasons: false,
    source: false,
    publicPath: false,
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        include: config.paths.assets,
        use: 'eslint',
      },
      {
        enforce: 'pre',
        test: /\.(js|s?[ca]ss)$/,
        include: config.paths.assets,
        loader: 'import-glob',
      },
      {
        test: /\.js$/,
        exclude: [/node_modules(?![/|\\](bootstrap|foundation-sites))/],
        use: [
          { loader: 'cache' },
          { loader: 'buble', options: { objectAssign: 'Object.assign' } },
        ],
      },
      {
        test: /\.css$/,
        include: config.paths.assets,
        use: ExtractTextPlugin.extract({
          fallback: 'style',
          use: [
            { loader: 'cache' },
            { loader: 'css', options: { sourceMap: config.enabled.sourceMaps } },
            {
              loader: 'postcss', options: {
                config: { path: __dirname, ctx: config },
                sourceMap: config.enabled.sourceMaps,
              },
            },
          ],
        }),
      },
      {
        test: /\.scss$/,
        include: config.paths.assets,
        use: ExtractTextPlugin.extract({
          fallback: 'style',
          use: [
            { loader: 'cache' },
            { loader: 'css', options: { sourceMap: config.enabled.sourceMaps } },
            {
              loader: 'postcss', options: {
                config: { path: __dirname, ctx: config },
                sourceMap: config.enabled.sourceMaps,
              },
            },
            { loader: 'resolve-url', options: { sourceMap: config.enabled.sourceMaps } },
            {
              loader: 'sass', options: {
                sourceMap: config.enabled.sourceMaps,
                sourceComments: true
              }
            },
          ],
        }),
      },
      {
        test: /\.(ttf|otf|eot|woff2?|png|jpe?g|gif|svg|ico)$/,
        include: config.paths.assets,
        loader: 'url',
        options: {
          limit: 4096,
          name: `[path]${assetsFilenames}.[ext]`,
        },
      },
      {
        test: /\.(ttf|otf|eot|woff2?|png|jpe?g|gif|svg|ico)$/,
        include: /node_modules/,
        loader: 'url',
        options: {
          limit: 4096,
          outputPath: 'vendor/',
          name: `${config.cacheBusting}.[ext]`,
        },
      },
    ],
  },
  resolve: {
    modules: [
      config.paths.assets,
      'node_modules',
    ],
    enforceExtension: false,
  },
  resolveLoader: {
    moduleExtensions: ['-loader'],
  },
  externals: {
    jquery: 'jQuery',
  },
  plugins: [
    new CleanPlugin([config.paths.dist], {
      root: config.paths.root,
      verbose: false,
    }),
    /**
     * It would be nice to switch to copy-webpack-plugin, but
     * unfortunately it doesn't provide a reliable way of
     * tracking the before/after file names
     */
    new CopyGlobsPlugin({
      pattern: config.copy,
      output: `[path]${assetsFilenames}.[ext]`,
      manifest: config.manifest,
    }),
    new ExtractTextPlugin({
      filename: `styles/${assetsFilenames}.css`,
      allChunks: true,
      disable: (config.enabled.watcher),
    }),
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      Popper: 'popper.js/dist/umd/popper.js',
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: config.enabled.optimize,
      debug: config.enabled.watcher,
      stats: { colors: true },
    }),
    new webpack.LoaderOptionsPlugin({
      test: /\.s?css$/,
      options: {
        output: { path: config.paths.dist },
        context: config.paths.assets,
      },
    }),
    new webpack.LoaderOptionsPlugin({
      test: /\.js$/,
      options: {
        eslint: { failOnWarning: false, failOnError: true },
      },
    }),
    new StyleLintPlugin({
      failOnError: !config.enabled.watcher,
      syntax: 'scss',
    }),
    new FriendlyErrorsWebpackPlugin(),
  ],
};

/* eslint-disable global-require */ /** Let's only load dependencies as needed */

if (config.enabled.optimize) {
  webpackConfig = merge(webpackConfig, require('./webpack.config.optimize'));
}

if (config.env.production) {
  webpackConfig.plugins.push(new webpack.NoEmitOnErrorsPlugin());
}

if (config.enabled.cacheBusting) {
  const WebpackAssetsManifest = require('webpack-assets-manifest');

  webpackConfig.plugins.push(
    new WebpackAssetsManifest({
      output: 'assets.json',
      space: 2,
      writeToDisk: false,
      assets: config.manifest,
      replacer: require('./util/assetManifestsFormatter'),
    })
  );
}

if (config.enabled.watcher) {
  webpackConfig.entry = require('./util/addHotMiddleware')(webpackConfig.entry);
  webpackConfig = merge(webpackConfig, require('./webpack.config.watch'));
}

module.exports = webpackConfig;
<commit_msg>Add missing trailing commas in 2f51b51<commit_after>'use strict'; // eslint-disable-line

const webpack = require('webpack');
const merge = require('webpack-merge');
const CleanPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const CopyGlobsPlugin = require('copy-globs-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

const config = require('./config');

const assetsFilenames = (config.enabled.cacheBusting) ? config.cacheBusting : '[name]';

let webpackConfig = {
  context: config.paths.assets,
  entry: config.entry,
  devtool: (config.enabled.sourceMaps ? '#source-map' : undefined),
  output: {
    path: config.paths.dist,
    publicPath: config.publicPath,
    filename: `scripts/${assetsFilenames}.js`,
  },
  stats: {
    hash: false,
    version: false,
    timings: false,
    children: false,
    errors: false,
    errorDetails: false,
    warnings: false,
    chunks: false,
    modules: false,
    reasons: false,
    source: false,
    publicPath: false,
  },
  module: {
    rules: [
      {
        enforce: 'pre',
        test: /\.js$/,
        include: config.paths.assets,
        use: 'eslint',
      },
      {
        enforce: 'pre',
        test: /\.(js|s?[ca]ss)$/,
        include: config.paths.assets,
        loader: 'import-glob',
      },
      {
        test: /\.js$/,
        exclude: [/node_modules(?![/|\\](bootstrap|foundation-sites))/],
        use: [
          { loader: 'cache' },
          { loader: 'buble', options: { objectAssign: 'Object.assign' } },
        ],
      },
      {
        test: /\.css$/,
        include: config.paths.assets,
        use: ExtractTextPlugin.extract({
          fallback: 'style',
          use: [
            { loader: 'cache' },
            { loader: 'css', options: { sourceMap: config.enabled.sourceMaps } },
            {
              loader: 'postcss', options: {
                config: { path: __dirname, ctx: config },
                sourceMap: config.enabled.sourceMaps,
              },
            },
          ],
        }),
      },
      {
        test: /\.scss$/,
        include: config.paths.assets,
        use: ExtractTextPlugin.extract({
          fallback: 'style',
          use: [
            { loader: 'cache' },
            { loader: 'css', options: { sourceMap: config.enabled.sourceMaps } },
            {
              loader: 'postcss', options: {
                config: { path: __dirname, ctx: config },
                sourceMap: config.enabled.sourceMaps,
              },
            },
            { loader: 'resolve-url', options: { sourceMap: config.enabled.sourceMaps } },
            {
              loader: 'sass', options: {
                sourceMap: config.enabled.sourceMaps,
                sourceComments: true,
              },
            },
          ],
        }),
      },
      {
        test: /\.(ttf|otf|eot|woff2?|png|jpe?g|gif|svg|ico)$/,
        include: config.paths.assets,
        loader: 'url',
        options: {
          limit: 4096,
          name: `[path]${assetsFilenames}.[ext]`,
        },
      },
      {
        test: /\.(ttf|otf|eot|woff2?|png|jpe?g|gif|svg|ico)$/,
        include: /node_modules/,
        loader: 'url',
        options: {
          limit: 4096,
          outputPath: 'vendor/',
          name: `${config.cacheBusting}.[ext]`,
        },
      },
    ],
  },
  resolve: {
    modules: [
      config.paths.assets,
      'node_modules',
    ],
    enforceExtension: false,
  },
  resolveLoader: {
    moduleExtensions: ['-loader'],
  },
  externals: {
    jquery: 'jQuery',
  },
  plugins: [
    new CleanPlugin([config.paths.dist], {
      root: config.paths.root,
      verbose: false,
    }),
    /**
     * It would be nice to switch to copy-webpack-plugin, but
     * unfortunately it doesn't provide a reliable way of
     * tracking the before/after file names
     */
    new CopyGlobsPlugin({
      pattern: config.copy,
      output: `[path]${assetsFilenames}.[ext]`,
      manifest: config.manifest,
    }),
    new ExtractTextPlugin({
      filename: `styles/${assetsFilenames}.css`,
      allChunks: true,
      disable: (config.enabled.watcher),
    }),
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      'window.jQuery': 'jquery',
      Popper: 'popper.js/dist/umd/popper.js',
    }),
    new webpack.LoaderOptionsPlugin({
      minimize: config.enabled.optimize,
      debug: config.enabled.watcher,
      stats: { colors: true },
    }),
    new webpack.LoaderOptionsPlugin({
      test: /\.s?css$/,
      options: {
        output: { path: config.paths.dist },
        context: config.paths.assets,
      },
    }),
    new webpack.LoaderOptionsPlugin({
      test: /\.js$/,
      options: {
        eslint: { failOnWarning: false, failOnError: true },
      },
    }),
    new StyleLintPlugin({
      failOnError: !config.enabled.watcher,
      syntax: 'scss',
    }),
    new FriendlyErrorsWebpackPlugin(),
  ],
};

/* eslint-disable global-require */ /** Let's only load dependencies as needed */

if (config.enabled.optimize) {
  webpackConfig = merge(webpackConfig, require('./webpack.config.optimize'));
}

if (config.env.production) {
  webpackConfig.plugins.push(new webpack.NoEmitOnErrorsPlugin());
}

if (config.enabled.cacheBusting) {
  const WebpackAssetsManifest = require('webpack-assets-manifest');

  webpackConfig.plugins.push(
    new WebpackAssetsManifest({
      output: 'assets.json',
      space: 2,
      writeToDisk: false,
      assets: config.manifest,
      replacer: require('./util/assetManifestsFormatter'),
    })
  );
}

if (config.enabled.watcher) {
  webpackConfig.entry = require('./util/addHotMiddleware')(webpackConfig.entry);
  webpackConfig = merge(webpackConfig, require('./webpack.config.watch'));
}

module.exports = webpackConfig;
<|endoftext|>


<commit_before>'use strict';

(function (angular, buildfire) {
  angular.module('contactUsPluginWidget', ['ngRoute', 'ngTouch'])
    .config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {

      /**
       * To make href urls safe on mobile
       */
      $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|cdvfile|file):/);

      $routeProvider
        .when('/', {
          templateUrl: 'templates/home.html',
          controllerAs: 'WidgetHome',
          controller: 'WidgetHomeCtrl'
        })
        .otherwise('/');
    }])
  /*  .filter('getImageUrl', ['Buildfire', function (Buildfire) {
      return function (url, width, height, type) {
        if (type == 'resize')
          return Buildfire.imageLib.resizeImage(url, {
            width: width,
            height: height
          });
        else
          return Buildfire.imageLib.cropImage(url, {
            width: width,
            height: height
          });
      }
    }])*/
    .directive("buildFireCarousel", ["$rootScope", function ($rootScope) {
      return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
          $rootScope.$broadcast("Carousel:LOADED");
        }
      };
    }])
    .directive("googleMap", function () {
      return {
        template: "

",
        replace: true,
        scope: {coordinates: '='},
        link: function (scope, elem, attrs) {
          scope.$watch('coordinates', function (newValue, oldValue) {
            if (newValue) {
              scope.coordinates = newValue;
              if (scope.coordinates.length) {
                var map = new google.maps.Map(elem[0], {
                  center: new google.maps.LatLng(scope.coordinates[1], scope.coordinates[0]),
                  zoomControl: false,
                  streetViewControl: false,
                  mapTypeControl: false,
                  zoom: 15,
                  mapTypeId: google.maps.MapTypeId.ROADMAP
                });
                var marker = new google.maps.Marker({
                  position: new google.maps.LatLng(scope.coordinates[1], scope.coordinates[0]),
                  map: map
                });
                var styleOptions = {
                  name: "Report Error Hide Style"
                };
                var MAP_STYLE = [
                  {
                    stylers: [
                      {visibility: "on"}
                    ]
                  }];
                var mapType = new google.maps.StyledMapType(MAP_STYLE, styleOptions);
                map.mapTypes.set("Report Error Hide Style", mapType);
                map.setMapTypeId("Report Error Hide Style");
                marker.addListener('click', function () {
                  if (buildfire.context.device && buildfire.context.device.platform.toLowerCase() == 'ios')
                    buildfire.navigation.openWindow("maps://maps.apple.com?q=" + scope.coordinates[1] + "," + scope.coordinates[0], '_system');
                  else
                    buildfire.navigation.openWindow("http://maps.google.com/maps?daddr=" + scope.coordinates[1] + "," + scope.coordinates[0], '_system');
                });

              }
            }
          }, true);
        }
      }
    })
 /*   .directive("backgroundImage", ['$filter', function ($filter) {
      return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          var getImageUrlFilter = $filter("getImageUrl");
          var setBackgroundImage = function (backgroundImage) {
            if (backgroundImage) {
              element.css(
                'background', '#010101 url('
                + getImageUrlFilter(backgroundImage, 342, 770, 'resize')
                + ') repeat fixed top center');
            } else {
              element.css('background', 'none');
            }
          };
          attrs.$observe('backgroundImage', function (newValue) {
            setBackgroundImage(newValue);
          });
        }
      };
    }])*/// Directive for adding  Image carousel on widget layout 2
    .directive('imageCarousel', function () {
      return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
          scope.carousel = null;
          scope.isCarouselInitiated = false;
          function initCarousel() {
            scope.carousel = null;
            setTimeout(function () {
              var obj = {
                'slideSpeed': 300,
                'dots': false,
                'autoplay': true,
                'margin': 10
              };

              var totalImages = parseInt(attrs.imageCarousel, 10);
              if (totalImages) {
                if (totalImages > 1) {
                  obj['loop'] = true;
                }
                scope.carousel = $(elem).owlCarousel(obj);
                scope.isCarouselInitiated = true;
              }
              scope.$apply();
            }, 100);
          }

          initCarousel();

          scope.$watch("imagesUpdated", function (newVal, oldVal) {
            if (newVal) {
              if (scope.isCarouselInitiated) {
                scope.carousel.trigger("destroy.owl.carousel");
                scope.isCarouselInitiated = false;
              }
              $(elem).find(".owl-stage-outer").remove();
              initCarousel();
            }
          });
        }
      }
    })
    .run([function () {
      buildfire.navigation.onBackButtonClick = function () {
          buildfire.navigation._goBackOne();
      };
    }]).filter('cropImage', [function () {
        return function (url, width, height, noDefault) {
          if(noDefault)
          {
            if(!url)
              return '';
          }
          return buildfire.imageLib.cropImage(url, {
            width: width,
            height: height
          });
        };
      }]).directive('backImg', ["$rootScope", function ($rootScope) {
      return function (scope, element, attrs) {
        attrs.$observe('backImg', function (value) {
          var img = '';
          if (value) {
            buildfire.imageLib.local.cropImage(value, {
              width: $rootScope.deviceWidth,
              height: $rootScope.deviceHeight
            }, function (err, imgUrl) {
              if (imgUrl) {
                img = imgUrl;
                element.attr("style", 'background:url(' + img + ') !important ; background-size: cover !important;');
              } else {
                img = '';
                element.attr("style", 'background-color:white');
              }
              element.css({
                'background-size': 'cover'
              });
            });
            // img = $filter("cropImage")(value, $rootScope.deviceWidth, $rootScope.deviceHeight, true);
          }
          else {
            img = "";
            element.attr("style", 'background-color:white');
            element.css({
              'background-size': 'cover'
            });
          }
        });
      };
    }]) .directive("loadImage", ['Buildfire', function (Buildfire) {
      return {
        restrict: 'A',
        link: function (scope, element, attrs) {
         // element.attr("src", "../../../styles/media/holder-" + attrs.loadImage + ".gif");

          var _img = attrs.finalSrc;
          if (attrs.cropType == 'resize') {
            Buildfire.imageLib.local.resizeImage(_img, {
              width: attrs.cropWidth,
              height: attrs.cropHeight
            }, function (err, imgUrl) {
              _img = imgUrl;
              replaceImg(_img);
            });
          } else {
            Buildfire.imageLib.local.cropImage(_img, {
              width: attrs.cropWidth,
              height: attrs.cropHeight
            }, function (err, imgUrl) {
              _img = imgUrl;
              replaceImg(_img);
            });
          }

          function replaceImg(finalSrc) {
            var elem = $("");
            elem[0].onload = function () {
              element.attr("src", finalSrc);
              elem.remove();
            };
            elem.attr("src", finalSrc);
          }
        }
      };
    }]);
})(window.angular, window.buildfire);
<commit_msg>Fix background-size issue<commit_after>'use strict';

(function (angular, buildfire) {
  angular.module('contactUsPluginWidget', ['ngRoute', 'ngTouch'])
    .config(['$routeProvider', '$compileProvider', function ($routeProvider, $compileProvider) {

      /**
       * To make href urls safe on mobile
       */
      $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension|cdvfile|file):/);

      $routeProvider
        .when('/', {
          templateUrl: 'templates/home.html',
          controllerAs: 'WidgetHome',
          controller: 'WidgetHomeCtrl'
        })
        .otherwise('/');
    }])
  /*  .filter('getImageUrl', ['Buildfire', function (Buildfire) {
      return function (url, width, height, type) {
        if (type == 'resize')
          return Buildfire.imageLib.resizeImage(url, {
            width: width,
            height: height
          });
        else
          return Buildfire.imageLib.cropImage(url, {
            width: width,
            height: height
          });
      }
    }])*/
    .directive("buildFireCarousel", ["$rootScope", function ($rootScope) {
      return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
          $rootScope.$broadcast("Carousel:LOADED");
        }
      };
    }])
    .directive("googleMap", function () {
      return {
        template: "

",
        replace: true,
        scope: {coordinates: '='},
        link: function (scope, elem, attrs) {
          scope.$watch('coordinates', function (newValue, oldValue) {
            if (newValue) {
              scope.coordinates = newValue;
              if (scope.coordinates.length) {
                var map = new google.maps.Map(elem[0], {
                  center: new google.maps.LatLng(scope.coordinates[1], scope.coordinates[0]),
                  zoomControl: false,
                  streetViewControl: false,
                  mapTypeControl: false,
                  zoom: 15,
                  mapTypeId: google.maps.MapTypeId.ROADMAP
                });
                var marker = new google.maps.Marker({
                  position: new google.maps.LatLng(scope.coordinates[1], scope.coordinates[0]),
                  map: map
                });
                var styleOptions = {
                  name: "Report Error Hide Style"
                };
                var MAP_STYLE = [
                  {
                    stylers: [
                      {visibility: "on"}
                    ]
                  }];
                var mapType = new google.maps.StyledMapType(MAP_STYLE, styleOptions);
                map.mapTypes.set("Report Error Hide Style", mapType);
                map.setMapTypeId("Report Error Hide Style");
                marker.addListener('click', function () {
                  if (buildfire.context.device && buildfire.context.device.platform.toLowerCase() == 'ios')
                    buildfire.navigation.openWindow("maps://maps.apple.com?q=" + scope.coordinates[1] + "," + scope.coordinates[0], '_system');
                  else
                    buildfire.navigation.openWindow("http://maps.google.com/maps?daddr=" + scope.coordinates[1] + "," + scope.coordinates[0], '_system');
                });

              }
            }
          }, true);
        }
      }
    })
 /*   .directive("backgroundImage", ['$filter', function ($filter) {
      return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          var getImageUrlFilter = $filter("getImageUrl");
          var setBackgroundImage = function (backgroundImage) {
            if (backgroundImage) {
              element.css(
                'background', '#010101 url('
                + getImageUrlFilter(backgroundImage, 342, 770, 'resize')
                + ') repeat fixed top center');
            } else {
              element.css('background', 'none');
            }
          };
          attrs.$observe('backgroundImage', function (newValue) {
            setBackgroundImage(newValue);
          });
        }
      };
    }])*/// Directive for adding  Image carousel on widget layout 2
    .directive('imageCarousel', function () {
      return {
        restrict: 'A',
        link: function (scope, elem, attrs) {
          scope.carousel = null;
          scope.isCarouselInitiated = false;
          function initCarousel() {
            scope.carousel = null;
            setTimeout(function () {
              var obj = {
                'slideSpeed': 300,
                'dots': false,
                'autoplay': true,
                'margin': 10
              };

              var totalImages = parseInt(attrs.imageCarousel, 10);
              if (totalImages) {
                if (totalImages > 1) {
                  obj['loop'] = true;
                }
                scope.carousel = $(elem).owlCarousel(obj);
                scope.isCarouselInitiated = true;
              }
              scope.$apply();
            }, 100);
          }

          initCarousel();

          scope.$watch("imagesUpdated", function (newVal, oldVal) {
            if (newVal) {
              if (scope.isCarouselInitiated) {
                scope.carousel.trigger("destroy.owl.carousel");
                scope.isCarouselInitiated = false;
              }
              $(elem).find(".owl-stage-outer").remove();
              initCarousel();
            }
          });
        }
      }
    })
    .run([function () {
      buildfire.navigation.onBackButtonClick = function () {
          buildfire.navigation._goBackOne();
      };
    }]).filter('cropImage', [function () {
        return function (url, width, height, noDefault) {
          if(noDefault)
          {
            if(!url)
              return '';
          }
          return buildfire.imageLib.cropImage(url, {
            width: width,
            height: height
          });
        };
      }]).directive('backImg', ["$rootScope", function ($rootScope) {
      return function (scope, element, attrs) {
        attrs.$observe('backImg', function (value) {
          var img = '';
          if (value) {
            buildfire.imageLib.local.cropImage(value, {
              width: $rootScope.deviceWidth,
              height: $rootScope.deviceHeight
            }, function (err, imgUrl) {
              if (imgUrl) {
                img = imgUrl;
                element.attr("style", 'background:url(' + img + ') !important ; background-size: cover !important;');
              } else {
                img = '';
                element.attr("style", 'background-color:white');
              }
              element.css({
                'background-size': 'cover !important'
              });
            });
            // img = $filter("cropImage")(value, $rootScope.deviceWidth, $rootScope.deviceHeight, true);
          }
          else {
            img = "";
            element.attr("style", 'background-color:white');
            element.css({
              'background-size': 'cover !important'
            });
          }
        });
      };
    }]) .directive("loadImage", ['Buildfire', function (Buildfire) {
      return {
        restrict: 'A',
        link: function (scope, element, attrs) {
         // element.attr("src", "../../../styles/media/holder-" + attrs.loadImage + ".gif");

          var _img = attrs.finalSrc;
          if (attrs.cropType == 'resize') {
            Buildfire.imageLib.local.resizeImage(_img, {
              width: attrs.cropWidth,
              height: attrs.cropHeight
            }, function (err, imgUrl) {
              _img = imgUrl;
              replaceImg(_img);
            });
          } else {
            Buildfire.imageLib.local.cropImage(_img, {
              width: attrs.cropWidth,
              height: attrs.cropHeight
            }, function (err, imgUrl) {
              _img = imgUrl;
              replaceImg(_img);
            });
          }

          function replaceImg(finalSrc) {
            var elem = $("");
            elem[0].onload = function () {
              element.attr("src", finalSrc);
              elem.remove();
            };
            elem.attr("src", finalSrc);
          }
        }
      };
    }]);
})(window.angular, window.buildfire);
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require turbolinks
//= require twitter/bootstrap
//= require ace-rails-ap
//= require cocoon
//= require_tree ./vendor
//= require_tree ./application
//
<commit_msg>Remove ace-rails-ap requirement.<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require turbolinks
//= require twitter/bootstrap
//= require cocoon
//= require_tree ./vendor
//= require_tree ./application
//
<|endoftext|>