<commit_before>var auth = require('./auth.js');
var config = require('./config.js');
var httpHelpers = require('./http-helpers.js');
var release = require('./release.js');
var files = require('./files.js');
var fs = require('fs');
var path = require('path');
var Future = require('fibers/future');
var _ = require('underscore');

var getLoadedPackages = _.once(function () {
  var unipackage = require('./unipackage.js');
  return unipackage.load({
    library: release.current.library,
    packages: [ 'meteor', 'livedata', 'minimongo', 'mongo-livedata' ],
    release: release.current.name
  });
});

var openPackageServerConnection = function () {
  var DDP = getLoadedPackages().livedata.DDP;
  return DDP.connect(config.getPackageServerUrl(), {
    headers: { 'User-Agent': httpHelpers.getUserAgent() }
  });
};

var loadLocalPackageData = function () {
  // XXX pretty error handling
  try {
    var data = fs.readFileSync(config.getPackageStorage(), 'utf8');
  } catch (e) {
    if (e.code !== 'ENOENT')
      throw e;
    // Default: no data, send us everything.
    return {
      // XXX have a better sync token for "all"
      syncToken: {time: 'Sun, 01 Jan 2012 00:00:00 GMT'},
      collections: null
    };
  }
  return JSON.parse(data);
};

var loadRemotePackageData = function (syncToken) {
  var conn = openPackageServerConnection();
  var collectionData = conn.call('syncNewPackageData', syncToken);
  conn.close();
  return collectionData;
};

// Takes in two javascript objects of the form:
//  { collectionName : arrayOfRecords }
// and converts them to a javascript object of the form
//  { collectionName : miniMongoCollection }
// where the miniMongo collection contains all of the records from
// both objects and the updateCollection overrides the first.
var createCollections = function (sources) {
  var finalCollections = {};
  // Start collections. Insert records.
  var meteorServer = getLoadedPackages()['meteor'];

  _.each(sources, function (source) {
    _.each(source, function (records, key) {
      if (!_.has(finalCollections, key)) {
        finalCollections[key] = new (meteorServer.Meteor.Collection)(null);
      }
      _.each(records, function (record) {
        finalCollections[key].remove(record._id);
        finalCollections[key].insert(record);
      });
    });
  });

  return finalCollections;
};

var writePackagesToDisk = function (syncToken, collectionData) {
  var finalWrite = {};
  finalWrite.syncToken = syncToken;
  finalWrite.formatVersion = "1.0";
  finalWrite.collections = {};
  _.forEach(collectionData, function(coll, name) {
    finalWrite.collections[name] = coll.find().fetch();
  });
  var filename = config.getPackageStorage();
  // XXX think about permissions?
  files.mkdir_p(path.dirname(filename));
  files.writeFileAtomically(filename, JSON.stringify(finalWrite, null, 2));
};

exports.loadPackageData = function() {
  //XXX: We can consider optimizing this with concurrency or something.
  var sources = [];

  var localData = loadLocalPackageData();
  if (localData.collections)
    sources.push(localData.collections);
  var syncToken = localData.syncToken;
  // XXX support offline use too
  var remoteData = loadRemotePackageData(syncToken);
  sources.push(remoteData.collections);

  var allPackageData = createCollections(sources);
  writePackagesToDisk(remoteData.syncToken, allPackageData);
  return allPackageData;
};

// XXX onReconnect
// Returns a logged-in DDP connection to the package server, or null if
// we cannot log in.
// XXX needs a timeout
exports.loggedInPackagesConnection = function () {
  // Make sure that we are logged in with Meteor Accounts so that we can
  // do an OAuth flow.
  if (! auth.isLoggedIn()) {
    auth.doUsernamePasswordLogin({ retry: true });
  }

  var conn = openPackageServerConnection();

  var setUpOnReconnect = function () {
    conn.onReconnect = function () {
      conn.apply('login', [{
        resume: auth.getSessionToken(config.getPackageServerDomain())
      }], { wait: true }, function () { });
    };
  };

  // Subscribe to the package server's service configurations so that we
  // can get the OAuth client ID to kick off the OAuth flow.
  var serviceConfigurations = new (getLoadedPackages().meteor.Meteor.Collection)(
    'meteor_accounts_loginServiceConfiguration',
    { connection: conn }
  );
  var serviceConfigurationsSub = conn.
        _subscribeAndWait('meteor.loginServiceConfiguration');

  var accountsConfiguration = serviceConfigurations.findOne({
    service: 'meteor-developer'
  });

  var cleanUp = function () {
    serviceConfigurationsSub.stop();
    conn.close();
  };

  if (! accountsConfiguration || ! accountsConfiguration.clientId) {
    cleanUp();
    return null;
  }

  var clientId = accountsConfiguration.clientId;
  var loginResult;

  // Try to log in with an existing login token, if we have one.
  var existingToken = auth.getSessionToken(config.getPackageServerDomain());
  if (existingToken) {
    loginResult = conn.apply('login', [{
      resume: existingToken
    }], { wait: true });

    if (loginResult && loginResult.token && loginResult.id) {
      // Success!
      setUpOnReconnect();
      return conn;
    }
  }

  // Either we didn't have an existing token, or it didn't work. Do an
  // OAuth flow to log in.
  var redirectUri = config.getPackageServerUrl() +
        '/_oauth/meteor-developer?close';
  loginResult = auth.oauthFlow(conn, {
    clientId: clientId,
    redirectUri: redirectUri,
    domain: config.getPackageServerDomain(),
    sessionType: 'package-server'
  });

  if (loginResult && ! loginResult.error) {
    setUpOnReconnect();
    return conn;
  } else {
    process.stderr.write('Error logging in to package server: ' +
                         loginResult.error + '\n');
    cleanUp();
    return null;
  }
};

var hashTarball = function (tarball) {
  var crypto = require('crypto');
  var hash = crypto.createHash('sha256');
  hash.setEncoding('base64');
  var rs = fs.createReadStream(tarball);
  var fut = new Future();
  rs.on('end', function () {
    fut.return(hash.digest('base64'));
  });
  rs.pipe(hash, { end: false });
  var tarballHash = fut.wait();
  rs.close();
  return tarballHash;
};

// XXX this is missing a few things:
//    - locking down build-time dependencies: tools version, versions
//      of all (not-built-from-source) plugins used
// in general, we need to include all the stuff that goes into the watchSet
// We include npm-shrinkwrap which does not go in the watchSet but
// probably should.
//
// In retrospect a better approach here might be to actually make "save source
// somewhere else" or perhaps "add source to tarball" be part of the package
// build itself...
exports.bundleSource = function (pkg, packageDir) {
  var name = pkg.name;
  var version = pkg.metadata.version;

  var tempDir = files.mkdtemp('build-source-package-');
  var packageTarName = name + '-' + version + '-source';
  var dirToTar = path.join(tempDir, 'source', packageTarName);
  var sourcePackageDir = path.join(
    dirToTar,
    name
  );
  if (! files.mkdir_p(sourcePackageDir)) {
    process.stderr.write('Failed to create temporary source directory: ' +
                         sourcePackageDir);
    return null;
  }

  var includeSources = _.clone(pkg.sources);
  includeSources.push('package.js');
  if (fs.existsSync('.npm/package/npm-shrinkwrap.json')) {
    includeSources.push('.npm/package/npm-shrinkwrap.json');
  }
  _.each(pkg.plugins, function (plugin, pluginName) {
    var pluginShrinkwrap = path.join('.npm/plugin/', pluginName,
                                     'npm-shrinkwrap.json');
    if (fs.existsSync(pluginShrinkwrap)) {
      includeSources.push(pluginShrinkwrap);
    }
  });

  // We copy source files into a temp directory and then tar up the temp
  // directory. It would be great if we could avoid the copy, but as far
  // as we can tell, this is the only way to get a tarball with the
  // directory structure that we want (<package name>-<version-source/
  // at the top level).
  files.cp_r(packageDir, sourcePackageDir, {
    include: includeSources
  });

  // We put this inside the temp dir because mkdtemp makes sure that the
  // temp dir gets cleaned up on process exit, so we don't have to worry
  // about cleaning up our tarball (or our copied source files)
  // ourselves.
  var sourceTarball = path.join(tempDir, packageTarName + '.tgz');
  files.createTarball(dirToTar, sourceTarball);

  var tarballHash = hashTarball(sourceTarball);

  return {
    sourceTarball: sourceTarball,
    tarballHash: tarballHash
  };
};

exports.uploadTarball = function (putUrl, tarball) {
  var size = fs.statSync(tarball).size;
  var rs = fs.createReadStream(tarball);
  httpHelpers.request({
    method: 'PUT',
    url: putUrl,
    headers: {
      'content-length': size,
      'content-type': 'application/octet-stream',
      'x-amz-acl': 'public-read'
    },
    bodyStream: rs
  });
  rs.close();
};

exports.bundleBuild = function (pkg, packageDir) {
  var tempDir = files.mkdtemp('build-package-');
  var packageTarName = pkg.name + '-' + pkg.metadata.version + '-' +
        pkg.architectures().join('+');
  var tarInputDir = path.join(tempDir, packageTarName);

  files.cp_r(path.join(packageDir, '.build'), tarInputDir);

  // Don't upload buildinfo.json. It's only of interest locally (for
  // example, it contains a watchset with local paths).
  fs.unlinkSync(path.join(tarInputDir, 'buildinfo.json'));

  var buildTarball = path.join(tempDir, packageTarName + '.tgz');
  files.createTarball(tarInputDir, buildTarball);

  var tarballHash = hashTarball(buildTarball);

  return {
    buildTarball: buildTarball,
    tarballHash: tarballHash
  };
};
<commit_msg>safety belt around removing buildinfo.json<commit_after>var auth = require('./auth.js');
var config = require('./config.js');
var httpHelpers = require('./http-helpers.js');
var release = require('./release.js');
var files = require('./files.js');
var fs = require('fs');
var path = require('path');
var Future = require('fibers/future');
var _ = require('underscore');

var getLoadedPackages = _.once(function () {
  var unipackage = require('./unipackage.js');
  return unipackage.load({
    library: release.current.library,
    packages: [ 'meteor', 'livedata', 'minimongo', 'mongo-livedata' ],
    release: release.current.name
  });
});

var openPackageServerConnection = function () {
  var DDP = getLoadedPackages().livedata.DDP;
  return DDP.connect(config.getPackageServerUrl(), {
    headers: { 'User-Agent': httpHelpers.getUserAgent() }
  });
};

var loadLocalPackageData = function () {
  // XXX pretty error handling
  try {
    var data = fs.readFileSync(config.getPackageStorage(), 'utf8');
  } catch (e) {
    if (e.code !== 'ENOENT')
      throw e;
    // Default: no data, send us everything.
    return {
      // XXX have a better sync token for "all"
      syncToken: {time: 'Sun, 01 Jan 2012 00:00:00 GMT'},
      collections: null
    };
  }
  return JSON.parse(data);
};

var loadRemotePackageData = function (syncToken) {
  var conn = openPackageServerConnection();
  var collectionData = conn.call('syncNewPackageData', syncToken);
  conn.close();
  return collectionData;
};

// Takes in two javascript objects of the form:
//  { collectionName : arrayOfRecords }
// and converts them to a javascript object of the form
//  { collectionName : miniMongoCollection }
// where the miniMongo collection contains all of the records from
// both objects and the updateCollection overrides the first.
var createCollections = function (sources) {
  var finalCollections = {};
  // Start collections. Insert records.
  var meteorServer = getLoadedPackages()['meteor'];

  _.each(sources, function (source) {
    _.each(source, function (records, key) {
      if (!_.has(finalCollections, key)) {
        finalCollections[key] = new (meteorServer.Meteor.Collection)(null);
      }
      _.each(records, function (record) {
        finalCollections[key].remove(record._id);
        finalCollections[key].insert(record);
      });
    });
  });

  return finalCollections;
};

var writePackagesToDisk = function (syncToken, collectionData) {
  var finalWrite = {};
  finalWrite.syncToken = syncToken;
  finalWrite.formatVersion = "1.0";
  finalWrite.collections = {};
  _.forEach(collectionData, function(coll, name) {
    finalWrite.collections[name] = coll.find().fetch();
  });
  var filename = config.getPackageStorage();
  // XXX think about permissions?
  files.mkdir_p(path.dirname(filename));
  files.writeFileAtomically(filename, JSON.stringify(finalWrite, null, 2));
};

exports.loadPackageData = function() {
  //XXX: We can consider optimizing this with concurrency or something.
  var sources = [];

  var localData = loadLocalPackageData();
  if (localData.collections)
    sources.push(localData.collections);
  var syncToken = localData.syncToken;
  // XXX support offline use too
  var remoteData = loadRemotePackageData(syncToken);
  sources.push(remoteData.collections);

  var allPackageData = createCollections(sources);
  writePackagesToDisk(remoteData.syncToken, allPackageData);
  return allPackageData;
};

// XXX onReconnect
// Returns a logged-in DDP connection to the package server, or null if
// we cannot log in.
// XXX needs a timeout
exports.loggedInPackagesConnection = function () {
  // Make sure that we are logged in with Meteor Accounts so that we can
  // do an OAuth flow.
  if (! auth.isLoggedIn()) {
    auth.doUsernamePasswordLogin({ retry: true });
  }

  var conn = openPackageServerConnection();

  var setUpOnReconnect = function () {
    conn.onReconnect = function () {
      conn.apply('login', [{
        resume: auth.getSessionToken(config.getPackageServerDomain())
      }], { wait: true }, function () { });
    };
  };

  // Subscribe to the package server's service configurations so that we
  // can get the OAuth client ID to kick off the OAuth flow.
  var serviceConfigurations = new (getLoadedPackages().meteor.Meteor.Collection)(
    'meteor_accounts_loginServiceConfiguration',
    { connection: conn }
  );
  var serviceConfigurationsSub = conn.
        _subscribeAndWait('meteor.loginServiceConfiguration');

  var accountsConfiguration = serviceConfigurations.findOne({
    service: 'meteor-developer'
  });

  var cleanUp = function () {
    serviceConfigurationsSub.stop();
    conn.close();
  };

  if (! accountsConfiguration || ! accountsConfiguration.clientId) {
    cleanUp();
    return null;
  }

  var clientId = accountsConfiguration.clientId;
  var loginResult;

  // Try to log in with an existing login token, if we have one.
  var existingToken = auth.getSessionToken(config.getPackageServerDomain());
  if (existingToken) {
    loginResult = conn.apply('login', [{
      resume: existingToken
    }], { wait: true });

    if (loginResult && loginResult.token && loginResult.id) {
      // Success!
      setUpOnReconnect();
      return conn;
    }
  }

  // Either we didn't have an existing token, or it didn't work. Do an
  // OAuth flow to log in.
  var redirectUri = config.getPackageServerUrl() +
        '/_oauth/meteor-developer?close';
  loginResult = auth.oauthFlow(conn, {
    clientId: clientId,
    redirectUri: redirectUri,
    domain: config.getPackageServerDomain(),
    sessionType: 'package-server'
  });

  if (loginResult && ! loginResult.error) {
    setUpOnReconnect();
    return conn;
  } else {
    process.stderr.write('Error logging in to package server: ' +
                         loginResult.error + '\n');
    cleanUp();
    return null;
  }
};

var hashTarball = function (tarball) {
  var crypto = require('crypto');
  var hash = crypto.createHash('sha256');
  hash.setEncoding('base64');
  var rs = fs.createReadStream(tarball);
  var fut = new Future();
  rs.on('end', function () {
    fut.return(hash.digest('base64'));
  });
  rs.pipe(hash, { end: false });
  var tarballHash = fut.wait();
  rs.close();
  return tarballHash;
};

// XXX this is missing a few things:
//    - locking down build-time dependencies: tools version, versions
//      of all (not-built-from-source) plugins used
// in general, we need to include all the stuff that goes into the watchSet
// We include npm-shrinkwrap which does not go in the watchSet but
// probably should.
//
// In retrospect a better approach here might be to actually make "save source
// somewhere else" or perhaps "add source to tarball" be part of the package
// build itself...
exports.bundleSource = function (pkg, packageDir) {
  var name = pkg.name;
  var version = pkg.metadata.version;

  var tempDir = files.mkdtemp('build-source-package-');
  var packageTarName = name + '-' + version + '-source';
  var dirToTar = path.join(tempDir, 'source', packageTarName);
  var sourcePackageDir = path.join(
    dirToTar,
    name
  );
  if (! files.mkdir_p(sourcePackageDir)) {
    process.stderr.write('Failed to create temporary source directory: ' +
                         sourcePackageDir);
    return null;
  }

  var includeSources = _.clone(pkg.sources);
  includeSources.push('package.js');
  if (fs.existsSync('.npm/package/npm-shrinkwrap.json')) {
    includeSources.push('.npm/package/npm-shrinkwrap.json');
  }
  _.each(pkg.plugins, function (plugin, pluginName) {
    var pluginShrinkwrap = path.join('.npm/plugin/', pluginName,
                                     'npm-shrinkwrap.json');
    if (fs.existsSync(pluginShrinkwrap)) {
      includeSources.push(pluginShrinkwrap);
    }
  });

  // We copy source files into a temp directory and then tar up the temp
  // directory. It would be great if we could avoid the copy, but as far
  // as we can tell, this is the only way to get a tarball with the
  // directory structure that we want (<package name>-<version-source/
  // at the top level).
  files.cp_r(packageDir, sourcePackageDir, {
    include: includeSources
  });

  // We put this inside the temp dir because mkdtemp makes sure that the
  // temp dir gets cleaned up on process exit, so we don't have to worry
  // about cleaning up our tarball (or our copied source files)
  // ourselves.
  var sourceTarball = path.join(tempDir, packageTarName + '.tgz');
  files.createTarball(dirToTar, sourceTarball);

  var tarballHash = hashTarball(sourceTarball);

  return {
    sourceTarball: sourceTarball,
    tarballHash: tarballHash
  };
};

exports.uploadTarball = function (putUrl, tarball) {
  var size = fs.statSync(tarball).size;
  var rs = fs.createReadStream(tarball);
  httpHelpers.request({
    method: 'PUT',
    url: putUrl,
    headers: {
      'content-length': size,
      'content-type': 'application/octet-stream',
      'x-amz-acl': 'public-read'
    },
    bodyStream: rs
  });
  rs.close();
};

exports.bundleBuild = function (pkg, packageDir) {
  var tempDir = files.mkdtemp('build-package-');
  var packageTarName = pkg.name + '-' + pkg.metadata.version + '-' +
        pkg.architectures().join('+');
  var tarInputDir = path.join(tempDir, packageTarName);

  files.cp_r(path.join(packageDir, '.build'), tarInputDir);

  // Don't upload buildinfo.json. It's only of interest locally (for
  // example, it contains a watchset with local paths).
  var buildInfoPath = path.join(tarInputDir, 'buildinfo.json');
  if (fs.existsSync(buildInfoPath))
    fs.unlinkSync(buildInfoPath);

  var buildTarball = path.join(tempDir, packageTarName + '.tgz');
  files.createTarball(tarInputDir, buildTarball);

  var tarballHash = hashTarball(buildTarball);

  return {
    buildTarball: buildTarball,
    tarballHash: tarballHash
  };
};
<|endoftext|>


<commit_before>function MtkMediaElement (settings) {
    MtkWidget.call (this, settings);
    this.InitFromXaml ("<MediaElement/>");
    this.AfterConstructed ();
}

<commit_msg>Implemented MediaElement<commit_after>function MtkMediaElement (settings) {
    MtkWidget.call (this, settings);
    this.InitFromXaml ("<MediaElement/>");

    this.play_timeout = null;
    this.LoopPlayback = false;
    this.AllowReplay = true;

    this.MapProperties ([
        "AutoPlay",
        "CurrentState",
        "DownloadProgress",
        "BufferingProgress",
        "BufferingTime",
        "Position",
        "NaturalDuration",
        "CanPause",
        "CanSeek",
        "IsMuted",
        "Volume"
    ]);

    this.Override ("OnRealize", function () {
        this.$OnRealize$ ();
        if (!this.IsRealized) {
            return;
        }

        this.Xaml.AddEventListener ("CurrentStateChanged", delegate (this, this.OnCurrentStateChanged));
        this.Xaml.AddEventListener ("BufferingProgressChanged", delegate (this, this.OnBufferingProgressChanged));
        this.Xaml.AddEventListener ("DownloadProgressChanged", delegate (this, this.OnDownloadProgressChanged));
        this.Xaml.AddEventListener ("MediaOpened", delegate (this, this.OnMediaOpened));
        this.Xaml.AddEventListener ("MediaEnded", delegate (this, this.OnMediaEnded));
    });

    this.Virtual ("OnIdle", function () this.RaiseEvent ("Idle"));

    this.Virtual ("OnCurrentStateChanged", function () {
        MtkConsole.Log ("Media Element State Change: " + this.CurrentState);

        switch (this.CurrentState) {
            case "Playing":
                this.play_timeout = setInterval (delegate (this, this.OnPlayTick), 500);
                break;
            case "Paused":
            case "Stopped":
                clearInterval (this.play_timeout);
                this.play_timeout = null;

                if (this.CurrentState == "Stopped") {
                    this.Xaml.Source = null;
                    if (!this.AllowReplay) {
                        this.source = null;
                    }
                }
                break;
        }

        this.RaiseEvent ("CurrentStateChanged", this.CurrentState);
    });

    this.Virtual ("OnPlayTick", function () {
        var live = this.IsLive;
        var pos = this.Position;
        var dur = this.NaturalDuration;
        this.RaiseEvent ("PlayTick", pos, dur, live ? 0 : pos.Seconds / dur.Seconds, live);
    });

    this.Virtual ("OnMediaOpened", function () this.RaiseEvent ("MediaOpened"));

    this.Virtual ("OnMediaEnded", function () {
        this.OnIdle ();

        if (this.LoopPlayback) {
            this.Play ();
        } else {
            this.Stop ();
        }
    });

    this.Virtual ("OnBufferingProgressChanged", function () {

    });

    this.Virtual ("OnDownloadProgressChanged", function () {

    });

    this.__defineGetter__ ("IsLive", function () this.NaturalDuration == null);
    this.__defineGetter__ ("IsPlaying", function () this.CurrentState == "Playing");

    this.Play = function () {
        if (!this.Source && this.CurrentState == "Closed" && this.source) {
            this.Source = this.source;
        }

        this.Xaml.Play ();
    };

    this.Pause = function () this.Xaml.Pause ();
    this.Stop = function () this.Xaml.Stop ();

    this.TogglePlaying = function () {
        if (this.CurrentState == "Playing") {
            this.Pause ();
        } else {
            this.Play ();
        }
    };

    this.source = null;
    this.__defineGetter__ ("Source", function () this.Xaml.Source);
    this.__defineSetter__ ("Source", function (x) {
        this.source = x;
        this.Xaml.Source = x;
    });

    this.AfterConstructed ();
}
<|endoftext|>


<commit_before>import _ from 'lodash';
import React from 'react/addons';
import {Input} from 'react-bootstrap';
import {SelectorMenu} from 'sprintly-ui';

var DropdownFilter = React.createClass({

  propTypes: {
    name: React.PropTypes.string.isRequired,
    updateFilters: React.PropTypes.func,
    options: React.PropTypes.array
  },

  getDefaultProps: function() {
    return {
      options: [],
      updateFilters: function() {}
    }
  },

  onChange: function(member) {
    let value = member.value;
    this.props.updateFilters(this.props.name, value)
  },

  update: function(field, value, ev) {
    let checked = ev.target.checked;
    let criteria = '';
    let options = {};

    if (!checked) {
      options.unset = true;
    }

    if (checked && field === 'me') {
      criteria = value;
    }
    this.props.updateFilters(this.props.name, criteria, options);
  },

  renderMembers: function(option) {
    let active = _.findWhere(option.members, { id: this.props.criteria });
    let defaultSelection = active ? `${active.first_name} ${active.last_name.slice(0,1)}.` : '';

    let members = _.map(option.members, function(member) {
      let title = `${member.first_name} ${member.last_name.slice(0,1)}.`;
      return {
        title,
        value: member.id
      }
    }, this);

    return (

        <SelectorMenu
          optionsList={_.sortBy(members, 'title')}
          defaultSelection={defaultSelection}
          onSelectionChange={(title) => {
            this.onChange(_.findWhere(members, { title }))
          }}
        />

    );
  },

  renderCriteriaFormField: function(option) {
    if (option.members) {
      return this.renderMembers(option);
    }

    let checked = this.props.criteria.length === 0 ? option.default :
      _.contains(this.props.criteria, option.field);

    return (
      <Input
        key={`filter-checkbox-${option.field}`}
        type="checkbox"
        label={option.label}
        wrapperClassName="col-xs-offset-1"
        onChange={_.partial(this.update, option.field, option.value)}
        defaultChecked={checked} />
    );
  },

  render: function() {
    var classes = React.addons.classSet({
      'form-horizontal': true,
      'filter__criteria-selector': true,
      visible: this.props.visible
    });
    return (
      <form className={classes} onClick={(e) => e.stopPropagation() }>
        {_.map(this.props.options, this.renderCriteriaFormField)}
      </form>
    )
  }
})

export default DropdownFilter;
<commit_msg>use SelectorMenu as a controlled component<commit_after>import _ from 'lodash';
import React from 'react/addons';
import {Input} from 'react-bootstrap';
import {SelectorMenu} from 'sprintly-ui';

var DropdownFilter = React.createClass({

  propTypes: {
    name: React.PropTypes.string.isRequired,
    updateFilters: React.PropTypes.func,
    options: React.PropTypes.array
  },

  getDefaultProps: function() {
    return {
      options: [],
      updateFilters: function() {}
    }
  },

  onChange: function(member) {
    let value = member.value;
    this.props.updateFilters(this.props.name, value)
  },

  update: function(field, value, ev) {
    let checked = ev.target.checked;
    let criteria = '';
    let options = {};

    if (!checked) {
      options.unset = true;
    }

    if (checked && field === 'me') {
      criteria = value;
    }
    this.props.updateFilters(this.props.name, criteria, options);
  },

  renderMembers: function(option) {
    let active = _.findWhere(option.members, { id: this.props.criteria });
    let selection = active ? `${active.first_name} ${active.last_name.slice(0,1)}.` : '';

    let members = _.map(option.members, function(member) {
      let title = `${member.first_name} ${member.last_name.slice(0,1)}.`;
      return {
        title,
        value: member.id
      }
    }, this);

    return (

        <SelectorMenu
          optionsList={_.sortBy(members, 'title')}
          selection={selection}
          onSelectionChange={(title) => {
            this.onChange(_.findWhere(members, { title }))
          }}
        />

    );
  },

  renderCriteriaFormField: function(option) {
    if (option.members) {
      return this.renderMembers(option);
    }

    let checked = this.props.criteria.length === 0 ? option.default :
      _.contains(this.props.criteria, option.field);

    return (
      <Input
        key={`filter-checkbox-${option.field}`}
        type="checkbox"
        label={option.label}
        wrapperClassName="col-xs-offset-1"
        onChange={_.partial(this.update, option.field, option.value)}
        defaultChecked={checked} />
    );
  },

  render: function() {
    var classes = React.addons.classSet({
      'form-horizontal': true,
      'filter__criteria-selector': true,
      visible: this.props.visible
    });
    return (
      <form className={classes} onClick={(e) => e.stopPropagation() }>
        {_.map(this.props.options, this.renderCriteriaFormField)}
      </form>
    )
  }
})

export default DropdownFilter;
<|endoftext|>


<commit_before>import Ember from 'ember';

let hasInitialized = false;

function abortBeforeTransitioning() {
  const activeTransition = this.router.router.activeTransition;

  if (activeTransition != null) {
    activeTransition.abort();
  }

  return this._super(...arguments);
}

export function initialize() {
  if (!hasInitialized) {
    hasInitialized = true;

    Ember.Router.reopen({
      transitionTo: abortBeforeTransitioning,
    });
  }
}

export default {
  name: 'abort-early-patch',
  initialize: initialize
};
<commit_msg>fixup! FIXME: abort the activeTransition before redirect forces Router#willTransition to be triggered when redirecting fixes a bug where the prefetch hook is not called on the routes to which the application has redirected<commit_after>import Ember from 'ember';

let hasInitialized = false;

function abortBeforeTransitioning() {
  const activeTransition = this.router.activeTransition;

  if (activeTransition != null) {
    activeTransition.abort();
  }

  return this._super(...arguments);
}

export function initialize() {
  if (!hasInitialized) {
    hasInitialized = true;

    Ember.Router.reopen({
      transitionTo: abortBeforeTransitioning,
    });
  }
}

export default {
  name: 'abort-early-patch',
  initialize: initialize
};
<|endoftext|>


<commit_before>import Ember from 'ember';
import FdEditformControl from '../objects/fd-editform-control';
import FdEditformGroup from '../objects/fd-editform-group';
import FdEditformRow from '../objects/fd-editform-row';
import FdEditformTab from '../objects/fd-editform-tab';
import FdEditformTabgroup from '../objects/fd-editform-tabgroup';
import { Query } from 'ember-flexberry-data';
const { Builder, FilterOperator } = Query;

export default Ember.Route.extend({

  currentProjectContext: Ember.inject.service('fd-current-project-context'),

  model: function(params) {
    let stageId = this.get('currentProjectContext').getCurrentStage();
    let _this = this;
    let modelHash = {
      editform: undefined,
      dataobject: undefined,
      typemap: undefined,
      enums: undefined,
      types: undefined
    };

    return new Ember.RSVP.Promise(function (resolve, reject) {
      // TODO: Replace promises to use fd-preload-stage-metadata and store.peekRecord().
      // Load «editform».
      let loadClassesPromise = new Ember.RSVP.Promise(function (resolveLoadClasses, rejectLoadClasses) {
        let predicateEditformId = new Query.SimplePredicate('id', FilterOperator.Eq, params.id);

        let builderEditform = new  Builder(_this.store, 'fd-dev-class').
        select('id,name,caption,description,formViews,formViews.view,formViews.view.class,formViews.view.class.id,formViews.view.definition').
        where(predicateEditformId);

        _this.store.query('fd-dev-class', builderEditform.build()).then((result) => {
          let editform = result.objectAt(0);
          modelHash.editform = editform;
          return editform;
        }, rejectLoadClasses).then((editform) => {
          // Load dataobject «implementation».
          let dataobjectId = editform.get('formViews').objectAt(0).get('view.class.id'); // TODO: Check array.
          let predicateDataobjectId = new Query.SimplePredicate('id', FilterOperator.Eq, dataobjectId);

          let builderDataobject = new  Builder(_this.store, 'fd-dev-class').
          select('id,name,caption,description').
          where(predicateDataobjectId);

          _this.store.query('fd-dev-class', builderDataobject.build()).then((resultDataobject) => {
            modelHash.dataobject = resultDataobject.objectAt(0);
            resolveLoadClasses(modelHash);
          }, rejectLoadClasses);
        }, reject);
      });

      // Stage with type map.
      let predicateId = new Query.SimplePredicate('id', FilterOperator.Eq, stageId);

      let builderStage = new  Builder(_this.store, 'fd-dev-stage').
      select('id,typeMapCSStr').
      where(predicateId);

      let loadTypemapPromise = _this.store.query('fd-dev-stage', builderStage.build()).then((result) => {
        let stage = result.objectAt(0);
        modelHash.typemap = stage.get('typeMapCSStr');
        return modelHash;
      }, reject);

      let predicateStageId = new Query.SimplePredicate('stage.id', FilterOperator.Eq, stageId);

      // Enums
      let predicateEnumerationStereorype = new Query.SimplePredicate('stereotype', FilterOperator.Eq, '«enumeration»');
      let predicateEnumeration = new Query.ComplexPredicate(Query.Condition.And, predicateStageId, predicateEnumerationStereorype);

      let builderEnumeration = new  Builder(_this.store, 'fd-dev-class').
      select('id,name,caption,description,stereotype,stage.id').
      where(predicateEnumeration);

      let promiseEnumeration = _this.store.query('fd-dev-class', builderEnumeration.build()).then((result) => {
        modelHash.enums = result;
        return modelHash;
      }, reject);

      // Type
      let predicateTypeStereorype = new Query.SimplePredicate('stereotype', FilterOperator.Eq, '«type»');
      let predicateType = new Query.ComplexPredicate(Query.Condition.And, predicateStageId, predicateTypeStereorype);

      let builderType = new  Builder(_this.store, 'fd-dev-class').
      select('id,name,caption,description,stereotype,stage.id').
      where(predicateType);

      let promiseType = _this.store.query('fd-dev-class', builderType.build()).then((result) => {
        modelHash.types = result;
        return modelHash;
      }, reject);

      Ember.RSVP.all([loadClassesPromise, loadTypemapPromise, promiseEnumeration, promiseType]).then(() => {
        let controlTree = Ember.A();

        let definition = modelHash.editform.get('formViews.firstObject.view.definition');
        for (let i = 0; i < definition.length; i++) {
          let propertyDefinition = definition[i];
          if (!propertyDefinition.visible) {
            continue;
          }

          _this._locateControl(controlTree, propertyDefinition, propertyDefinition.path);
        }

        modelHash.controls = controlTree;
        resolve(modelHash);
      });
    });
  },

  /**
      Locate control by path.

      @method _locateControl
      @param {Object} controlTree Controls tree.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @param {String} path Property path from view.
      @return {Object} Modified controlTree with placed control.
  */
  _locateControl: function (controlTree, propertyDefinition, path) {
    if (!path || path === '') {
      let row  = FdEditformRow.create({ controls: Ember.A(), columnsCount: 0 });

      if (controlTree.get('rows')) {
        controlTree.get('rows').pushObject(row);
      } else {
        controlTree.pushObject(row);
      }

      this._locateControlInRow(row, propertyDefinition);

      return controlTree;
    }

    if (path.charAt(0) === '|') {
      return this._locateTabs(controlTree, propertyDefinition, path);
    }

    if (path.charAt(0) === '-') {
      return this._locateGroup(controlTree, propertyDefinition, path);
    }

    if (path.charAt(0) === '#') {
      return this._locateColumn(controlTree, propertyDefinition, path);
    }

    // TODO: Show error and fix it.
  },

  /**
      Locate control in row by path.

      @method _locateControlInRow
      @param {FdEditformRow} row Row for control placement.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @return {Object} Modified controlTree with placed control.
  */
  _locateControlInRow: function (row, propertyDefinition) {
    // TODO: вычислить type контрола из метаданных атрибута или FormControl и width из path.
    let control = FdEditformControl.create({ caption: propertyDefinition.caption || propertyDefinition.name, type: 'string', width: '100*' });

    row.get('controls').pushObject(control);
    row.set('columnsCount', row.get('columnsCount') + 1);

    return row;
  },

  /**
      Locate tabs for control.

      @method _locateTabs
      @param {Object} controlTree Controls tree.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @param {String} path Property path from view.
      @return {Object} Modified controlTree with placed tabs.
  */
  _locateTabs: function(controlTree, propertyDefinition, path) {
    let pathLength = path.length;
    let splitterIndex = path.indexOf('\\');
    let tabCaptionEndIndex = splitterIndex > -1 ? splitterIndex : pathLength;

    let tabCaption = path.slice(1, tabCaptionEndIndex);

    let row;
    let tabGroup;
    let tab;
    let rowsCollection;

    if (controlTree.get('rows')) {
      rowsCollection = controlTree.get('rows');
    } else {
      rowsCollection = controlTree;
    }

    for (let i = 0; i < rowsCollection.get('length'); i++) {
      let rowInCollection = rowsCollection[i];
      if (rowInCollection instanceof FdEditformRow) {
        for (let j = 0; j < rowInCollection.get('controls.length'); j++) {
          let controlInRow = rowInCollection.controls[j];
          if (controlInRow instanceof FdEditformTabgroup) {
            row = rowInCollection;
            tabGroup = controlInRow;
            for (let k = 0; k < controlInRow.get('tabs.length'); k++) {
              let tabInTabgroup = controlInRow.tabs[k];
              if (tabInTabgroup.caption === tabCaption) {
                tab = tabInTabgroup;
              }
            }
          }
        }
      }
    }

    if (!row) {
      row  = FdEditformRow.create({ controls: Ember.A(), columnsCount: 0 });

      if (controlTree.get('rows')) {
        controlTree.get('rows').pushObject(row);
      } else {
        controlTree.pushObject(row);
      }
    }

    if (!tabGroup) {
      tabGroup  = FdEditformTabgroup.create({ tabs: Ember.A(), width: '100*' });
      row.get('controls').pushObject(tabGroup);
    }

    if (!tab) {
      tab  = FdEditformTab.create({ rows: Ember.A(), caption: tabCaption });
      tabGroup.get('tabs').pushObject(tab);
    }

    let nextPath = path.slice(tabCaptionEndIndex + 1, pathLength);

    return this._locateControl(tab, propertyDefinition, nextPath);
  },

  /**
      Locate group for control.

      @method _locateGroup
      @param {Object} controlTree Controls tree.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @param {String} path Property path from view.
      @return {Object} Modified controlTree with placed group.
  */
  _locateGroup: function(controlTree, propertyDefinition, path) {
    let pathLength = path.length;
    let splitterIndex = path.indexOf('\\');
    let groupCaptionEndIndex = splitterIndex > -1 ? splitterIndex : pathLength;

    let groupCaption = path.slice(1, groupCaptionEndIndex);

    let row;
    let group;
    let rowsCollection;

    if (controlTree.get('rows')) {
      rowsCollection = controlTree.get('rows');
    } else {
      rowsCollection = controlTree;
    }

    for (let i = 0; i < rowsCollection.get('length'); i++) {
      let rowInCollection = rowsCollection[i];
      if (rowInCollection instanceof FdEditformRow) {
        for (let j = 0; j < rowInCollection.get('controls.length'); j++) {
          let controlInRow = rowInCollection.controls[j];
          if (controlInRow instanceof FdEditformGroup && controlInRow.get('caption') === groupCaption) {
            row = rowInCollection;
            group = controlInRow;
          }
        }
      }
    }

    if (!row) {
      row  = FdEditformRow.create({ controls: Ember.A(), columnsCount: 0 });

      if (controlTree.get('rows')) {
        controlTree.get('rows').pushObject(row);
      } else {
        controlTree.pushObject(row);
      }
    }

    if (!group) {
      group  = FdEditformGroup.create({ rows: Ember.A(), width: '100*', caption: groupCaption });
      row.get('controls').pushObject(group);
    }

    let nextPath = path.slice(groupCaptionEndIndex + 1, pathLength);

    return this._locateControl(group, propertyDefinition, nextPath);
  },

  /**
      Locate column for control.

      @method _locateColumn
      @param {Object} controlTree Controls tree.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @param {String} path Property path from view.
      @return {Object} Modified controlTree with placed column.
  */
  _locateColumn: function(controlTree, propertyDefinition, path) {
    let pathLength = path.length;
    let splitterIndex = path.indexOf('\\');
    let columnDefinitionEndIndex = splitterIndex > -1 ? splitterIndex : pathLength;

    let columnDefinition = path.slice(1, columnDefinitionEndIndex);

    let braceIndex = columnDefinition.indexOf('(');

    if (braceIndex === -1) {
      braceIndex = columnDefinition.length;
    }

    let columnIndex = parseInt(columnDefinition.slice(0, braceIndex));

    let rowsCollection;

    if (controlTree.get('rows')) {
      rowsCollection = controlTree.get('rows');
    } else {
      rowsCollection = controlTree;
    }

    let row = rowsCollection.get('lastObject');

    // Current columns count in row must be match column index else it will be another row.
    if (row && row.get('columnsCount') + 1 !== columnIndex) {
      row = undefined;
    }

    if (!row) {
      row  = FdEditformRow.create({ controls: Ember.A(), columnsCount: 0 });

      if (controlTree.get('rows')) {
        controlTree.get('rows').pushObject(row);
      } else {
        controlTree.pushObject(row);
      }
    }

    let nextPath = path.slice(columnDefinitionEndIndex + 1, pathLength);

    if (nextPath) {
      // TODO: may be another group or tabs there?
      return this._locateControl(row, propertyDefinition, nextPath);
    } else {
      return this._locateControlInRow(row, propertyDefinition);
    }
  }
});
<commit_msg>Fix fd-editform-constructor form use class name when caption empty<commit_after>import Ember from 'ember';
import FdEditformControl from '../objects/fd-editform-control';
import FdEditformGroup from '../objects/fd-editform-group';
import FdEditformRow from '../objects/fd-editform-row';
import FdEditformTab from '../objects/fd-editform-tab';
import FdEditformTabgroup from '../objects/fd-editform-tabgroup';
import { Query } from 'ember-flexberry-data';
const { Builder, FilterOperator } = Query;

export default Ember.Route.extend({

  currentProjectContext: Ember.inject.service('fd-current-project-context'),

  model: function(params) {
    let stageId = this.get('currentProjectContext').getCurrentStage();
    let _this = this;
    let modelHash = {
      editform: undefined,
      dataobject: undefined,
      typemap: undefined,
      enums: undefined,
      types: undefined
    };

    return new Ember.RSVP.Promise(function (resolve, reject) {
      // TODO: Replace promises to use fd-preload-stage-metadata and store.peekRecord().
      // Load «editform».
      let loadClassesPromise = new Ember.RSVP.Promise(function (resolveLoadClasses, rejectLoadClasses) {
        let predicateEditformId = new Query.SimplePredicate('id', FilterOperator.Eq, params.id);

        let builderEditform = new  Builder(_this.store, 'fd-dev-class').
        select('id,name,caption,description,formViews,formViews.view,formViews.view.class,formViews.view.class.id,formViews.view.definition').
        where(predicateEditformId);

        _this.store.query('fd-dev-class', builderEditform.build()).then((result) => {
          let editform = result.objectAt(0);
          if (!editform.get('caption')) {
            editform.set('caption', editform.get('name'));
          }

          modelHash.editform = editform;
          return editform;
        }, rejectLoadClasses).then((editform) => {
          // Load dataobject «implementation».
          let dataobjectId = editform.get('formViews').objectAt(0).get('view.class.id'); // TODO: Check array.
          let predicateDataobjectId = new Query.SimplePredicate('id', FilterOperator.Eq, dataobjectId);

          let builderDataobject = new  Builder(_this.store, 'fd-dev-class').
          select('id,name,caption,description').
          where(predicateDataobjectId);

          _this.store.query('fd-dev-class', builderDataobject.build()).then((resultDataobject) => {
            modelHash.dataobject = resultDataobject.objectAt(0);
            resolveLoadClasses(modelHash);
          }, rejectLoadClasses);
        }, reject);
      });

      // Stage with type map.
      let predicateId = new Query.SimplePredicate('id', FilterOperator.Eq, stageId);

      let builderStage = new  Builder(_this.store, 'fd-dev-stage').
      select('id,typeMapCSStr').
      where(predicateId);

      let loadTypemapPromise = _this.store.query('fd-dev-stage', builderStage.build()).then((result) => {
        let stage = result.objectAt(0);
        modelHash.typemap = stage.get('typeMapCSStr');
        return modelHash;
      }, reject);

      let predicateStageId = new Query.SimplePredicate('stage.id', FilterOperator.Eq, stageId);

      // Enums
      let predicateEnumerationStereorype = new Query.SimplePredicate('stereotype', FilterOperator.Eq, '«enumeration»');
      let predicateEnumeration = new Query.ComplexPredicate(Query.Condition.And, predicateStageId, predicateEnumerationStereorype);

      let builderEnumeration = new  Builder(_this.store, 'fd-dev-class').
      select('id,name,caption,description,stereotype,stage.id').
      where(predicateEnumeration);

      let promiseEnumeration = _this.store.query('fd-dev-class', builderEnumeration.build()).then((result) => {
        modelHash.enums = result;
        return modelHash;
      }, reject);

      // Type
      let predicateTypeStereorype = new Query.SimplePredicate('stereotype', FilterOperator.Eq, '«type»');
      let predicateType = new Query.ComplexPredicate(Query.Condition.And, predicateStageId, predicateTypeStereorype);

      let builderType = new  Builder(_this.store, 'fd-dev-class').
      select('id,name,caption,description,stereotype,stage.id').
      where(predicateType);

      let promiseType = _this.store.query('fd-dev-class', builderType.build()).then((result) => {
        modelHash.types = result;
        return modelHash;
      }, reject);

      Ember.RSVP.all([loadClassesPromise, loadTypemapPromise, promiseEnumeration, promiseType]).then(() => {
        let controlTree = Ember.A();

        let definition = modelHash.editform.get('formViews.firstObject.view.definition');
        for (let i = 0; i < definition.length; i++) {
          let propertyDefinition = definition[i];
          if (!propertyDefinition.visible) {
            continue;
          }

          _this._locateControl(controlTree, propertyDefinition, propertyDefinition.path);
        }

        modelHash.controls = controlTree;
        resolve(modelHash);
      });
    });
  },

  /**
      Locate control by path.

      @method _locateControl
      @param {Object} controlTree Controls tree.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @param {String} path Property path from view.
      @return {Object} Modified controlTree with placed control.
  */
  _locateControl: function (controlTree, propertyDefinition, path) {
    if (!path || path === '') {
      let row  = FdEditformRow.create({ controls: Ember.A(), columnsCount: 0 });

      if (controlTree.get('rows')) {
        controlTree.get('rows').pushObject(row);
      } else {
        controlTree.pushObject(row);
      }

      this._locateControlInRow(row, propertyDefinition);

      return controlTree;
    }

    if (path.charAt(0) === '|') {
      return this._locateTabs(controlTree, propertyDefinition, path);
    }

    if (path.charAt(0) === '-') {
      return this._locateGroup(controlTree, propertyDefinition, path);
    }

    if (path.charAt(0) === '#') {
      return this._locateColumn(controlTree, propertyDefinition, path);
    }

    // TODO: Show error and fix it.
  },

  /**
      Locate control in row by path.

      @method _locateControlInRow
      @param {FdEditformRow} row Row for control placement.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @return {Object} Modified controlTree with placed control.
  */
  _locateControlInRow: function (row, propertyDefinition) {
    // TODO: вычислить type контрола из метаданных атрибута или FormControl и width из path.
    let control = FdEditformControl.create({ caption: propertyDefinition.caption || propertyDefinition.name, type: 'string', width: '100*' });

    row.get('controls').pushObject(control);
    row.set('columnsCount', row.get('columnsCount') + 1);

    return row;
  },

  /**
      Locate tabs for control.

      @method _locateTabs
      @param {Object} controlTree Controls tree.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @param {String} path Property path from view.
      @return {Object} Modified controlTree with placed tabs.
  */
  _locateTabs: function(controlTree, propertyDefinition, path) {
    let pathLength = path.length;
    let splitterIndex = path.indexOf('\\');
    let tabCaptionEndIndex = splitterIndex > -1 ? splitterIndex : pathLength;

    let tabCaption = path.slice(1, tabCaptionEndIndex);

    let row;
    let tabGroup;
    let tab;
    let rowsCollection;

    if (controlTree.get('rows')) {
      rowsCollection = controlTree.get('rows');
    } else {
      rowsCollection = controlTree;
    }

    for (let i = 0; i < rowsCollection.get('length'); i++) {
      let rowInCollection = rowsCollection[i];
      if (rowInCollection instanceof FdEditformRow) {
        for (let j = 0; j < rowInCollection.get('controls.length'); j++) {
          let controlInRow = rowInCollection.controls[j];
          if (controlInRow instanceof FdEditformTabgroup) {
            row = rowInCollection;
            tabGroup = controlInRow;
            for (let k = 0; k < controlInRow.get('tabs.length'); k++) {
              let tabInTabgroup = controlInRow.tabs[k];
              if (tabInTabgroup.caption === tabCaption) {
                tab = tabInTabgroup;
              }
            }
          }
        }
      }
    }

    if (!row) {
      row  = FdEditformRow.create({ controls: Ember.A(), columnsCount: 0 });

      if (controlTree.get('rows')) {
        controlTree.get('rows').pushObject(row);
      } else {
        controlTree.pushObject(row);
      }
    }

    if (!tabGroup) {
      tabGroup  = FdEditformTabgroup.create({ tabs: Ember.A(), width: '100*' });
      row.get('controls').pushObject(tabGroup);
    }

    if (!tab) {
      tab  = FdEditformTab.create({ rows: Ember.A(), caption: tabCaption });
      tabGroup.get('tabs').pushObject(tab);
    }

    let nextPath = path.slice(tabCaptionEndIndex + 1, pathLength);

    return this._locateControl(tab, propertyDefinition, nextPath);
  },

  /**
      Locate group for control.

      @method _locateGroup
      @param {Object} controlTree Controls tree.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @param {String} path Property path from view.
      @return {Object} Modified controlTree with placed group.
  */
  _locateGroup: function(controlTree, propertyDefinition, path) {
    let pathLength = path.length;
    let splitterIndex = path.indexOf('\\');
    let groupCaptionEndIndex = splitterIndex > -1 ? splitterIndex : pathLength;

    let groupCaption = path.slice(1, groupCaptionEndIndex);

    let row;
    let group;
    let rowsCollection;

    if (controlTree.get('rows')) {
      rowsCollection = controlTree.get('rows');
    } else {
      rowsCollection = controlTree;
    }

    for (let i = 0; i < rowsCollection.get('length'); i++) {
      let rowInCollection = rowsCollection[i];
      if (rowInCollection instanceof FdEditformRow) {
        for (let j = 0; j < rowInCollection.get('controls.length'); j++) {
          let controlInRow = rowInCollection.controls[j];
          if (controlInRow instanceof FdEditformGroup && controlInRow.get('caption') === groupCaption) {
            row = rowInCollection;
            group = controlInRow;
          }
        }
      }
    }

    if (!row) {
      row  = FdEditformRow.create({ controls: Ember.A(), columnsCount: 0 });

      if (controlTree.get('rows')) {
        controlTree.get('rows').pushObject(row);
      } else {
        controlTree.pushObject(row);
      }
    }

    if (!group) {
      group  = FdEditformGroup.create({ rows: Ember.A(), width: '100*', caption: groupCaption });
      row.get('controls').pushObject(group);
    }

    let nextPath = path.slice(groupCaptionEndIndex + 1, pathLength);

    return this._locateControl(group, propertyDefinition, nextPath);
  },

  /**
      Locate column for control.

      @method _locateColumn
      @param {Object} controlTree Controls tree.
      @param {FdDefinition} propertyDefinition Property definition from view.
      @param {String} path Property path from view.
      @return {Object} Modified controlTree with placed column.
  */
  _locateColumn: function(controlTree, propertyDefinition, path) {
    let pathLength = path.length;
    let splitterIndex = path.indexOf('\\');
    let columnDefinitionEndIndex = splitterIndex > -1 ? splitterIndex : pathLength;

    let columnDefinition = path.slice(1, columnDefinitionEndIndex);

    let braceIndex = columnDefinition.indexOf('(');

    if (braceIndex === -1) {
      braceIndex = columnDefinition.length;
    }

    let columnIndex = parseInt(columnDefinition.slice(0, braceIndex));

    let rowsCollection;

    if (controlTree.get('rows')) {
      rowsCollection = controlTree.get('rows');
    } else {
      rowsCollection = controlTree;
    }

    let row = rowsCollection.get('lastObject');

    // Current columns count in row must be match column index else it will be another row.
    if (row && row.get('columnsCount') + 1 !== columnIndex) {
      row = undefined;
    }

    if (!row) {
      row  = FdEditformRow.create({ controls: Ember.A(), columnsCount: 0 });

      if (controlTree.get('rows')) {
        controlTree.get('rows').pushObject(row);
      } else {
        controlTree.pushObject(row);
      }
    }

    let nextPath = path.slice(columnDefinitionEndIndex + 1, pathLength);

    if (nextPath) {
      // TODO: may be another group or tabs there?
      return this._locateControl(row, propertyDefinition, nextPath);
    } else {
      return this._locateControlInRow(row, propertyDefinition);
    }
  }
});
<|endoftext|>


<commit_before>var backAction=null;
var extraButtonAction=null;
var parentWindow=null;

var buttonFactory=require(WPATH('button'));

// set default app icon, in case no icon is provided
$.appicon.backgroundImage='/appicon.png'

function openInflater(evt){
	// need to code this part
	alert('Open the Inflater');
}

$.headerbar.addEventListener('click',function(evt){
	// this cancels the click event that get's fired
	// when the parent window is clicked
	evt.cancelBubble=true;
})

$.backbutton.addEventListener('click',function(evt){
	evt.cancelBubble=true;
})

$.backbutton.addEventListener('touchstart',function(evt){
	this.backgroundColor="#000"
	this.opacity=0.2;
});

$.backbutton.addEventListener('touchend',function(evt){
	this.backgroundColor='transparent';
	this.opacity=1;
	(!backAction)?parentWindow.close():backAction();
});

function setTitle(args){
	$.headertitle.text=args.text;
	$.headertitle.color=args.color;
}

function setTitleAction(action){
	$.headertitle.addEventListener('click',action);
}

function setBack(action){
	backAction=action;
}

function setBlackAngle(){
	$.backangle.backgroundImage=WPATH('light-back-angle.png');
}

function setWhiteAngle(){
	$.backangle.backgroundImage=WPATH('white-back-angle.png');
}

function hideAngle(){
	//$.backangle.width='0';
	$.backangle.visible=false;
}

function showAngle(){
	//$.backangle.width='14dp';
	$.backangle.visible=true;
}

function setAppIcon(icon){
	$.appicon.backgroundImage=icon;
}

function setParentContainer(handle){
	parentWindow=handle;
}

function setBackground(args){
	(args.image)?$.headerbar.backgroundImage=args.image:$.headerbar.backgroundImage=WPATH('lightbg.png');
	$.headerbar.backgroundColor=args.color;

	$.headerbar.backgroundRepeat= true;
}

function showBottomLine(){
	$.bottomline.visible=true;
}

function hideBottomLine(){
	$.bottomline.visible=false;
}

function setTop(top){
	this.headerbar.top=top;
}

function setActionButtons(args){
	if (args.visible){
		args.visible.forEach(function(button){
			var payload={
				image:button.icon,
				action: button.action,
				title: button.title
			}
			var tbbutton=buttonFactory.getButton(payload);
			$.actionButtons.add(tbbutton);
		})
	}

	if (args.inflater){
		var menuoptions='';
		var payload={
			image: WPATH('ic_menu_moreoverflow_normal_holo_light.png')
		}

		var inflater=buttonFactory.getButton(payload);
		args.inflater.forEach(function(button){
			// here I gather all the menu options and build a dropdown menu
			menuoptions+=button.title
		});
		inflater.addEventListener('click',openInflater);

		$.actionButtons.add(inflater);
	}

	if (args.androidmenu){
		parentWindow.activity.onCreateOptionsMenu = function(e){
			var menu = e.menu;
			args.androidmenu.forEach(function(button){
				var menuItem = menu.add({
					title: button.title,
					icon: '/ic_menu_copy_holo_light.png',
					showAsAction : Ti.Android.SHOW_AS_ACTION_NEVER
				});
				menuItem.addEventListener("click", button.action);
			})
		}
	}
}
//
exports.setTop=setTop;
exports.setActionButtons=setActionButtons;
exports.showBottomLine=showBottomLine;
exports.hideBottomLine=hideBottomLine;
exports.setBackground=setBackground;
exports.setParentContainer=setParentContainer;
exports.setAppIcon=setAppIcon;
exports.hideAngle=hideAngle;
exports.showAngle=showAngle;
exports.setBlackAngle=setBlackAngle;
exports.setWhiteAngle=setWhiteAngle;
exports.setTitle=setTitle;
exports.setBack=setBack;
<commit_msg>Update widget.js<commit_after>var backAction=null;
var extraButtonAction=null;
var parentWindow=null;

var buttonFactory=require(WPATH('button'));

// set default app icon, in case no icon is provided
$.appicon.backgroundImage='/appicon.png'

function openInflater(evt){
	// need to code this part
	alert('Open the Inflater');
}

$.headerbar.addEventListener('click',function(evt){
	// this cancels the click event that get's fired
	// when the parent window is clicked
	evt.cancelBubble=true;
})

$.backbutton.addEventListener('click',function(evt){
	evt.cancelBubble=true;
})

$.backbutton.addEventListener('touchstart',function(evt){
	this.backgroundColor="#000"
	this.opacity=0.2;
});

$.backbutton.addEventListener('touchend',function(evt){
	this.backgroundColor='transparent';
	this.opacity=1;
	(!backAction)?parentWindow.close():backAction();
});

function setTitle(args){
	$.headertitle.text=args.text;
	$.headertitle.color=args.color;
}

function setTitleAction(action){
	$.headertitle.addEventListener('click',action);
}

function setBack(action){
	backAction=action;
}

function setBlackAngle(){
	$.backangle.backgroundImage=WPATH('light-back-angle.png');
}

function setWhiteAngle(){
	$.backangle.backgroundImage=WPATH('white-back-angle.png');
}

function hideAngle(){
	//$.backangle.width='0';
	$.backangle.visible=false;
}

function showAngle(){
	//$.backangle.width='14dp';
	$.backangle.visible=true;
}

function setAppIcon(icon){
	$.appicon.backgroundImage=icon;
}

function setParentContainer(handle){
	parentWindow=handle;
}

function setBackground(args){
	(args.image)?$.headerbar.backgroundImage=args.image:$.headerbar.backgroundImage=WPATH('lightbg.png');
	$.headerbar.backgroundColor=args.color;

	$.headerbar.backgroundRepeat= true;
}

function showBottomLine(){
	$.bottomline.visible=true;
}

function hideBottomLine(){
	$.bottomline.visible=false;
}

function setTop(top){
	this.headerbar.top=top;
}

function setActionButtons(args){
	if (args.visible){
		args.visible.forEach(function(button){
			var payload={
				image:button.icon,
				action: button.action,
				title: button.title
			}
			var tbbutton=buttonFactory.getButton(payload);
			$.actionButtons.add(tbbutton);
		})
	}

	if (args.inflater){
		var menuoptions='';
		var payload={
			image: WPATH('ic_menu_moreoverflow_normal_holo_light.png')
		}

		var inflater=buttonFactory.getButton(payload);
		args.inflater.forEach(function(button){
			// here I gather all the menu options and build a dropdown menu
			menuoptions+=button.title
		});
		inflater.addEventListener('click',openInflater);

		$.actionButtons.add(inflater);
	}

	if (args.androidmenu){
		parentWindow.activity.onCreateOptionsMenu = function(e){
			var menu = e.menu;
			args.androidmenu.forEach(function(button){
				var menuItem = menu.add({
					title: button.title,
					icon: '/ic_menu_copy_holo_light.png',
					showAsAction : Ti.Android.SHOW_AS_ACTION_NEVER
				});
				menuItem.addEventListener("click", button.action);
			})
		}
	}
}
//
exports.setTop=setTop;
exports.setActionButtons=setActionButtons;
exports.showBottomLine=showBottomLine;
exports.hideBottomLine=hideBottomLine;
exports.setBackground=setBackground;
exports.setParentContainer=setParentContainer;
exports.setAppIcon=setAppIcon;
exports.hideAngle=hideAngle;
exports.showAngle=showAngle;
exports.setBlackAngle=setBlackAngle;
exports.setWhiteAngle=setWhiteAngle;
exports.setTitle=setTitle;
exports.setTitleAction=setTitleAction;
exports.setBack=setBack;
<|endoftext|>


<commit_before>(function () {
  angular
  .module('mySiteApp')
  .service('authentication', authentication);

  authentication.$inject = ['$q', '$http', '$window', '$cookies'];
  function authentication ($q, $http, $window, $cookies) {

    //----------------------------
    //--- local authentication ---
    //----------------------------
    var register = function(user) {
      return $http.post('/api/register', user)
      .success(function (data) {
        console.log('called register - success');
        console.log(data.token);
        saveToken('auth', JSON.stringify(data.token));
      })
      .error(function (err) {
        // Erase the token if the user fails to log in
        console.log('called register - error');
        removeToken('auth');
      });
    };

    var login = function(user) {
      return $http.post('/api/login', user)
      .success(function(data) {
        saveToken('auth', JSON.stringify(data.token));
      });
    };

    var unlinkLocal = function() {
      console.log("unlinkLocal: ");
      var deferred = $q.defer();

      getUserByToken('auth')
      .success(function(data) {
        console.log('unlink user ');

        if(data!=null && data=='invalid-data') {
          removeToken('auth');
          removeCookie('userCookie');
          deferred.reject(null);
        }

        //var userData = JSON.parse(data);
        console.log('********************************************************');
        console.log('******************************************************** unlinkLocal user:');
        console.log('********************************************************');
        console.log(data);
          if(data) {
              var userData = JSON.parse(data);
              console.log(userData);
              var user = userData.user;
              console.log(user);

              if(user._id) {

                $http.get('/api/unlink/local/' + user._id)
                .success(function (data) {
                  console.log("unlink");
                  console.log(data);
                  deferred.resolve(data);
                })
                .error(function(e) {
                  console.log(e);
                  deferred.reject(null);
                });

                // getUserById(user._id)
                // .success(function(data) {
                //   console.log("Obtained user by its id");
                //   console.log("getUserByToken finished with local user");
                //   console.log(data);

                //   console.log("updated user with local infos:");
                //   console.log(user);

                //   deferred.resolve(JSON.stringify(user));
                // })
                // .error(function(e) {
                //   console.log("Impossible to retrieve user by its id");
                //   console.log("getUserByToken finished without local user");
                //   deferred.resolve(JSON.stringify(user));
                // });
              }
          } else {
            removeToken('auth');
            removeCookie('userCookie');
            deferred.reject(null);
          }
      })
      .error(function(e) {
        console.log('getUserByToken error ');
        console.log(e);
        removeToken('auth');
        removeCookie('userCookie');
        deferred.reject(null);
      });

      return deferred.promise;
    };

    function isAuthLocalLoggedIn () {
      console.log("reading token: ");
      var deferred = $q.defer();

      getUserByToken('auth')
      .success(function(data) {
        console.log('isAuthLocalLoggedIn user ');
        var user = JSON.parse(data);
        console.log('user:');
        console.log(user);
          //return getUserById(data.user._id);
          if(user) {
            deferred.resolve(true);
          } else {
            deferred.resolve(false);
          }
        })
      .error(function(e) {
        console.log('isAuthLocalLoggedIn error ');
        console.log(e);
        deferred.resolve(false);
      });

      return deferred.promise;
    };

    //-----------------------------
    //--- 3dauth authentication ---
    //-----------------------------
    function isAuth3dLoggedIn () {
      console.log("reading 3dauth: ");
      var deferred = $q.defer();

      getUserByToken('3dauth')
      .success(function(data) {
        console.log('isAuth3dLoggedIn user ');
        var user = JSON.parse(data);
        console.log('user:');
        console.log(user);
          //return getUserById(data.user._id);
          if(user) {
            deferred.resolve(true);
          } else {
            deferred.resolve(false);
          }
        })
      .error(function(e) {
        console.log('isAuth3dLoggedIn error ');
        console.log(e);
        deferred.resolve(false);
      });

      return deferred.promise;
    };

    //---------------------------------------
    //--- local and 3dauth authentication ---
    //---------------------------------------
    //function to call the /users/:id REST API
    var getUserById = function (id) {
      return $http.get('/api/users/' + id);
    };

    var logout = function() {
      removeToken('auth');
      removeCookie('userCookie');
      removeCookie('connect.sid');
    };

    var isLoggedIn = function() {
      var deferred = $q.defer();

      $q.all([isAuthLocalLoggedIn(), isAuth3dLoggedIn()])
      .then(function(results) {
        console.log("Isloggedin called");
        var r0 = results[0];
        var r1 = results[1];
        console.log(r0);
        console.log(r1);
        deferred.resolve(r0 || r1);
        //return false;
      }, function(error) {
        deferred.resolve(false);
        //return false;
      }).catch(function(err){
        deferred.resolve(false);
      });
      return deferred.promise;
    };

    var saveToken = function (key, token) {
      $window.sessionStorage[key] = token;
    };

    var decodeJwtToken = function(jwtToken) {
      return $http.get('/api/decodeToken/' + jwtToken);
    };

    var getLoggedUser = function() {
      console.log("reading token: ");
      var deferred = $q.defer();
      var thirdauthData = {};

      getUserByToken('auth')
      .success(function(data) {
        console.log('getUserByToken user ');

        if(data!=null && data=='invalid-data') {
          removeToken('auth');
          removeCookie('userCookie');
          deferred.reject(null);
        }

        //var userData = JSON.parse(data);
        console.log('********************************************************');
        console.log('******************************************************** user:');
        console.log('********************************************************');
        console.log(data);
          if(data) {
              var userData = JSON.parse(data);
              console.log(userData);
              var user = userData.user;
              console.log(user);

              if(user._id) {
                getUserById(user._id)
                .success(function(data) {
                  console.log("Obtained user by its id");
                  console.log("getUserByToken finished with local user");
                  console.log(data);

                  console.log("updated user with local infos:");
                  console.log(user);

                  deferred.resolve(JSON.stringify(user));
                })
                .error(function(e) {
                  console.log("Impossible to retrieve user by its id");
                  console.log("getUserByToken finished without local user");
                  deferred.resolve(JSON.stringify(user));
                });
              }
          } else {
            removeToken('auth');
            removeCookie('userCookie');
            deferred.reject(JSON.stringify({}));
          }
      })
      .error(function(e) {
        console.log('getUserByToken error ');
        console.log(e);
        removeToken('auth');
        removeCookie('userCookie');
        deferred.reject(JSON.stringify({}));
      });
      console.log("getUserByToken finished returning...");
      return deferred.promise;
    };

    //-----------------------------------
    //--- others functions - not exposed
    //-----------------------------------
    function getToken(key) {
      return $window.sessionStorage[key];
    };
    function getUserByToken(key) {
      console.log("getUserByToken called method");
      var sessionToken = getToken(key);
      if(sessionToken) {
        console.log("getUserByToken sessionToken");
        var token = JSON.parse(sessionToken);
        console.log("getUserByToken token ");
        console.log(token);
        return decodeJwtToken(token);
      } else {
        return decodeJwtToken();
      }
    };
    function removeToken(key) {
      $window.sessionStorage.removeItem(key);
    };
    function removeCookie(key) {
      $cookies.remove(key);
    };

    return {
      register : register,
      login : login,
      unlinkLocal : unlinkLocal,
      getUserById : getUserById,
      logout : logout,
      getLoggedUser : getLoggedUser,
      isLoggedIn : isLoggedIn,
      saveToken : saveToken,
      decodeJwtToken : decodeJwtToken
    };
  }
})();<commit_msg>code improvements<commit_after>(function () {
  angular
  .module('mySiteApp')
  .service('authentication', authentication);

  authentication.$inject = ['$q', '$http', '$window', '$cookies'];
  function authentication ($q, $http, $window, $cookies) {

    //----------------------------
    //--- local authentication ---
    //----------------------------
    var register = function(user) {
      return $http.post('/api/register', user)
      .success(function (data) {
        console.log('called register - success');
        console.log(data.token);
        saveToken('auth', JSON.stringify(data.token));
      })
      .error(function (err) {
        // Erase the token if the user fails to log in
        console.log('called register - error');
        removeToken('auth');
      });
    };

    var login = function(user) {
      return $http.post('/api/login', user)
      .success(function(data) {
        saveToken('auth', JSON.stringify(data.token));
      });
    };

    var unlinkLocal = function() {
      console.log("unlinkLocal: ");
      var deferred = $q.defer();

      getUserByToken('auth')
      .success(function(data) {
        console.log('unlink user ');

        if(data !== null && data === 'invalid-data') {
          removeToken('auth');
          removeCookie('userCookie');
          deferred.reject(null);
        }

        //var userData = JSON.parse(data);
        console.log('********************************************************');
        console.log('******************************************************** unlinkLocal user:');
        console.log('********************************************************');
        console.log(data);
          if(data) {
              var userData = JSON.parse(data);
              console.log(userData);
              var user = userData.user;
              console.log(user);

              if(user._id) {

                $http.get('/api/unlink/local/' + user._id)
                .success(function (data) {
                  console.log("unlink");
                  console.log(data);
                  deferred.resolve(data);
                })
                .error(function(e) {
                  console.log(e);
                  deferred.reject(null);
                });
              }
          } else {
            removeToken('auth');
            removeCookie('userCookie');
            deferred.reject(null);
          }
      })
      .error(function(e) {
        console.log('getUserByToken error ');
        console.log(e);
        removeToken('auth');
        removeCookie('userCookie');
        deferred.reject(null);
      });

      return deferred.promise;
    };

    function isAuthLocalLoggedIn () {
      console.log("reading token: ");
      var deferred = $q.defer();

      getUserByToken('auth')
      .success(function(data) {
        console.log('isAuthLocalLoggedIn user ');
        var user = JSON.parse(data);
        console.log('user:');
        console.log(user);
          //return getUserById(data.user._id);
          if(user) {
            deferred.resolve(true);
          } else {
            deferred.resolve(false);
          }
        })
      .error(function(e) {
        console.log('isAuthLocalLoggedIn error ');
        console.log(e);
        deferred.resolve(false);
      });

      return deferred.promise;
    }

    //-----------------------------
    //--- 3dauth authentication ---
    //-----------------------------
    function isAuth3dLoggedIn () {
      console.log("reading 3dauth: ");
      var deferred = $q.defer();

      getUserByToken('3dauth')
      .success(function(data) {
        console.log('isAuth3dLoggedIn user ');
        var user = JSON.parse(data);
        console.log('user:');
        console.log(user);
          //return getUserById(data.user._id);
          if(user) {
            deferred.resolve(true);
          } else {
            deferred.resolve(false);
          }
        })
      .error(function(e) {
        console.log('isAuth3dLoggedIn error ');
        console.log(e);
        deferred.resolve(false);
      });

      return deferred.promise;
    }

    //---------------------------------------
    //--- local and 3dauth authentication ---
    //---------------------------------------
    //function to call the /users/:id REST API
    var getUserById = function (id) {
      return $http.get('/api/users/' + id);
    };

    var logout = function() {
      removeToken('auth');
      removeCookie('userCookie');
      removeCookie('connect.sid');
    };

    var isLoggedIn = function() {
      var deferred = $q.defer();

      $q.all([isAuthLocalLoggedIn(), isAuth3dLoggedIn()])
      .then(function(results) {
        console.log("Isloggedin called");
        var r0 = results[0];
        var r1 = results[1];
        console.log(r0);
        console.log(r1);
        deferred.resolve(r0 || r1);
        //return false;
      }, function(error) {
        deferred.resolve(false);
        //return false;
      }).catch(function(err){
        deferred.resolve(false);
      });
      return deferred.promise;
    };

    var saveToken = function (key, token) {
      $window.sessionStorage[key] = token;
    };

    var decodeJwtToken = function(jwtToken) {
      return $http.get('/api/decodeToken/' + jwtToken);
    };

    var getLoggedUser = function() {
      console.log("reading token: ");
      var deferred = $q.defer();
      var thirdauthData = {};

      getUserByToken('auth')
      .success(function(data) {
        console.log('getUserByToken user ');

        if(data !== null && data === 'invalid-data') {
          removeToken('auth');
          removeCookie('userCookie');
          deferred.reject(null);
        }

        //var userData = JSON.parse(data);
        console.log('********************************************************');
        console.log('******************************************************** user:');
        console.log('********************************************************');
        console.log(data);
          if(data) {
              var userData = JSON.parse(data);
              console.log(userData);
              var user = userData.user;
              console.log(user);

              if(user._id) {
                getUserById(user._id)
                .success(function(data) {
                  console.log("Obtained user by its id");
                  console.log("getUserByToken finished with local user");
                  console.log(data);

                  console.log("updated user with local infos:");
                  console.log(user);

                  deferred.resolve(JSON.stringify(user));
                })
                .error(function(e) {
                  console.log("Impossible to retrieve user by its id");
                  console.log("getUserByToken finished without local user");
                  deferred.resolve(JSON.stringify(user));
                });
              }
          } else {
            removeToken('auth');
            removeCookie('userCookie');
            deferred.reject(JSON.stringify({}));
          }
      })
      .error(function(e) {
        console.log('getUserByToken error ');
        console.log(e);
        removeToken('auth');
        removeCookie('userCookie');
        deferred.reject(JSON.stringify({}));
      });
      console.log("getUserByToken finished returning...");
      return deferred.promise;
    };

    //-----------------------------------
    //--- others functions - not exposed
    //-----------------------------------
    function getToken(key) {
      return $window.sessionStorage[key];
    }
    function getUserByToken(key) {
      console.log("getUserByToken called method");
      var sessionToken = getToken(key);
      if(sessionToken) {
        console.log("getUserByToken sessionToken");
        var token = JSON.parse(sessionToken);
        console.log("getUserByToken token ");
        console.log(token);
        return decodeJwtToken(token);
      } else {
        return decodeJwtToken();
      }
    }
    function removeToken(key) {
      $window.sessionStorage.removeItem(key);
    }
    function removeCookie(key) {
      $cookies.remove(key);
    }

    return {
      register : register,
      login : login,
      unlinkLocal : unlinkLocal,
      getUserById : getUserById,
      logout : logout,
      getLoggedUser : getLoggedUser,
      isLoggedIn : isLoggedIn,
      saveToken : saveToken,
      decodeJwtToken : decodeJwtToken
    };
  }
})();<|endoftext|>


<commit_before>import path from 'path';
import webpack from 'webpack';
import merge from 'webpack-merge';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin';

import CommonConfig from './webpack.common';

const devMode = process.env.NODE_ENV !== 'production';

function recursiveIssuer(m) {
  if (m.issuer) {
    return recursiveIssuer(m.issuer);
  }
  if (m.name) {
    return m.name;
  }
  return false;
}

let config = {
  entry: {
    splash: ['css-hot-loader/hotModuleReplacement', './src/splash.js'],
    app: ['css-hot-loader/hotModuleReplacement', './src/index.js'],
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'src', '.build'),
  },
  target: 'electron-renderer',
  module: {
    rules: [
      {
        test: /\.html$/,
        use: ['html-loader'],
      },
      {
        test: /\.css$/,
        use: [
          devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
          'css-loader',
        ],
      },
      {
        test: /\.(png|jpg|gif|svg|woff|woff2|ttf|otf|eot)$/,
        use: ['file-loader'],
      },
    ],
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        venderJS: {
          name: 'vendor',
          test: /[\\/]node_modules[\\/].+\.js$/,
          chunks: 'all',
          enforce: true,
        },
        venderStyles: {
          name: 'vender',
          test: /[\\/]node_modules[\\/].+\.css$/,
          chunks: 'all',
          enforce: true,
        },
        splashStyles: {
          name: 'splash',
          test: (m, c, entry = 'splash') => m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
          chunks: 'all',
          enforce: true,
        },
        appStyles: {
          name: 'app',
          test: (m, c, entry = 'app') => m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
          chunks: 'all',
          enforce: true,
        },
      },
    },
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
    }),
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [
        '*.html',
        'app.bundle.js',
        '*.app.bundle.js',
        'splash.bundle.js',
        '*.splash.bundle.js',
        'vendor.bundle.js',
        '*.css',
      ],
    }),
  ],
};

const htmlConfigs = {
  splash: {
    filename: 'splash.html',
    template: 'src/splash.html',
    chunks: ['vender', 'splash'],
  },
  app: {
    filename: 'index.html',
    template: 'src/index.html',
    chunks: ['vender', 'app'],
  },
};

if (devMode) {
  config = merge(config, {
    devtool: 'eval-source-map',
    devServer: {
      host: 'localhost',
      port: 3000,
      hot: true,
    },
    plugins: [
      new webpack.NamedModulesPlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new HtmlWebpackPlugin(htmlConfigs.splash),
      new HtmlWebpackPlugin(htmlConfigs.app),
      new BundleAnalyzerPlugin(),
    ],
  });
} else {
  const htmlConfig = {
    minify: {
      collapseBooleanAttributes: true,
      decodeEntities: true,
      html5: true,
      minifyCSS: true,
      minifyJS: true,
      processConditionalComments: true,
      removeComments: true,
      removeEmptyAttributes: true,
      removeOptionalTags: true,
      removeRedundantAttributes: true,
      sortAttributes: true,
      sortClassName: true,
      trimCustomFragments: true,
      useShortDoctype: true,
    },
  };
  config = merge(config, {
    plugins: [
      new OptimizeCssAssetsPlugin({
        cssProcessorOptions: { discardComments: { removeAll: true } },
      }),
      new HtmlWebpackPlugin({ ...htmlConfigs.splash, ...htmlConfig }),
      new HtmlWebpackPlugin({ ...htmlConfigs.app, ...htmlConfig }),
    ],
  });
}

export default merge(CommonConfig, config);
<commit_msg>Rename vender styles chunk<commit_after>import path from 'path';
import webpack from 'webpack';
import merge from 'webpack-merge';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
import MiniCssExtractPlugin from 'mini-css-extract-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import OptimizeCssAssetsPlugin from 'optimize-css-assets-webpack-plugin';

import CommonConfig from './webpack.common';

const devMode = process.env.NODE_ENV !== 'production';

function recursiveIssuer(m) {
  if (m.issuer) {
    return recursiveIssuer(m.issuer);
  }
  if (m.name) {
    return m.name;
  }
  return false;
}

let config = {
  entry: {
    splash: ['css-hot-loader/hotModuleReplacement', './src/splash.js'],
    app: ['css-hot-loader/hotModuleReplacement', './src/index.js'],
  },
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'src', '.build'),
  },
  target: 'electron-renderer',
  module: {
    rules: [
      {
        test: /\.html$/,
        use: ['html-loader'],
      },
      {
        test: /\.css$/,
        use: [
          devMode ? 'style-loader' : MiniCssExtractPlugin.loader,
          'css-loader',
        ],
      },
      {
        test: /\.(png|jpg|gif|svg|woff|woff2|ttf|otf|eot)$/,
        use: ['file-loader'],
      },
    ],
  },
  optimization: {
    splitChunks: {
      cacheGroups: {
        venderJS: {
          name: 'vendor',
          test: /[\\/]node_modules[\\/].+\.js$/,
          chunks: 'all',
          enforce: true,
        },
        venderStyles: {
          name: 'vender.style',
          test: /[\\/]node_modules[\\/].+\.css$/,
          chunks: 'all',
          enforce: true,
        },
        splashStyles: {
          name: 'splash',
          test: (m, c, entry = 'splash') => m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
          chunks: 'all',
          enforce: true,
        },
        appStyles: {
          name: 'app',
          test: (m, c, entry = 'app') => m.constructor.name === 'CssModule' && recursiveIssuer(m) === entry,
          chunks: 'all',
          enforce: true,
        },
      },
    },
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].css',
    }),
    new CleanWebpackPlugin({
      cleanOnceBeforeBuildPatterns: [
        '*.html',
        'app.bundle.js',
        '*.app.bundle.js',
        'splash.bundle.js',
        '*.splash.bundle.js',
        'vendor.*.js',
        '*.css',
      ],
    }),
  ],
};

const htmlConfigs = {
  splash: {
    filename: 'splash.html',
    template: 'src/splash.html',
    chunks: ['vender', 'vender.style', 'splash'],
  },
  app: {
    filename: 'index.html',
    template: 'src/index.html',
    chunks: ['vender', 'vender.style', 'app'],
  },
};

if (devMode) {
  config = merge(config, {
    devtool: 'eval-source-map',
    devServer: {
      host: 'localhost',
      port: 3000,
      hot: true,
    },
    plugins: [
      new webpack.NamedModulesPlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new HtmlWebpackPlugin(htmlConfigs.splash),
      new HtmlWebpackPlugin(htmlConfigs.app),
      new BundleAnalyzerPlugin(),
    ],
  });
} else {
  const htmlConfig = {
    minify: {
      collapseBooleanAttributes: true,
      decodeEntities: true,
      html5: true,
      minifyCSS: true,
      minifyJS: true,
      processConditionalComments: true,
      removeComments: true,
      removeEmptyAttributes: true,
      removeOptionalTags: true,
      removeRedundantAttributes: true,
      sortAttributes: true,
      sortClassName: true,
      trimCustomFragments: true,
      useShortDoctype: true,
    },
  };
  config = merge(config, {
    plugins: [
      new OptimizeCssAssetsPlugin({
        cssProcessorOptions: { discardComments: { removeAll: true } },
      }),
      new HtmlWebpackPlugin({ ...htmlConfigs.splash, ...htmlConfig }),
      new HtmlWebpackPlugin({ ...htmlConfigs.app, ...htmlConfig }),
    ],
  });
}

export default merge(CommonConfig, config);
<|endoftext|>


<commit_before>module.exports = function() {
	return {
		bail: true,
		module: {
			loaders: [
				{
					test: /\.ts$/,
					exclude: /node_modules/,
					loader: 'ts-loader',
				},
			],
		},
		resolve: {
			extensions: ['', '.webpack.js','.web.js', '.ts', '.js'],
		},
	};
};
<commit_msg>Revert "Resolve typescript files *before* resolving javascript files."<commit_after>module.exports = function() {
	return {
		bail: true,
		module: {
			loaders: [
				{
					test: /\.ts$/,
					exclude: /node_modules/,
					loader: 'ts-loader',
				},
			],
		},
		resolve: {
			extensions: ['', '.webpack.js','.web.js', '.js', '.ts'],
		},
	};
};
<|endoftext|>


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

angular.module('upsConsole').controller('ApplicationController',
  function($rootScope, $scope, $modal, pushApplication, Notifications, applications) {

  /*
   * INITIALIZATION
   */

  $scope.alerts = [];

  //let's show all the applications
  $scope.applications = applications;
  $rootScope.application = null;

  /*
   * PUBLIC METHODS
   */

  $scope.open = function (application) {
    var modalInstance = show(application, 'create-app.html');
    modalInstance.result.then(function (application) {
      pushApplication.create(application, function (newApp) {
        $scope.applications.push(newApp);
        Notifications.success('Successfully created application "' + newApp.name + '".');
      }, function () {
        Notifications.error('Something went wrong...', 'danger');
      });
    });
  };

  $scope.edit = function (application) {
    var modalInstance = show(application, 'create-app.html');
    modalInstance.result.then(function (application) {
      pushApplication.update({appId: application.pushApplicationID}, application, function () {
        Notifications.success('Successfully edited application "' + application.name + '".');
      });
    });
  };

  $scope.remove = function (application) {
    var modalInstance = show(application, 'remove-app.html');
    modalInstance.result.then(function () {
      pushApplication.remove({appId: application.pushApplicationID}, function () {
        $scope.applications.splice($scope.applications.indexOf(application), 1);
        Notifications.success('Successfully removed application "' + application.name + '".');
      });
    });
  };

  /*
   * PRIVATE METHODS
   */

  function modalController($scope, $modalInstance, application) {
    $scope.application = application;
    $scope.ok = function (application) {
      $modalInstance.close(application);
    };

    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  }

  function show(application, template) {
    return $modal.open({
      templateUrl: 'views/dialogs/' + template,
      controller: modalController,
      resolve: {
        application: function () {
          return application;
        }
      }
    });
  }
});
<commit_msg>fix editing of application AGPUSH-755<commit_after>/*
 * JBoss, Home of Professional Open Source
 * Copyright Red Hat, Inc., and individual contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

angular.module('upsConsole').controller('ApplicationController',
  function($rootScope, $scope, $modal, pushApplication, Notifications, applications) {

  /*
   * INITIALIZATION
   */

  $scope.alerts = [];

  //let's show all the applications
  $scope.applications = applications;
  $rootScope.application = null;

  /*
   * PUBLIC METHODS
   */

  $scope.open = function (application) {
    var modalInstance = show(application, 'create-app.html');
    modalInstance.result.then(function (application) {
      pushApplication.create(application, function (newApp) {
        $scope.applications.push(newApp);
        Notifications.success('Successfully created application "' + newApp.name + '".');
      }, function () {
        Notifications.error('Something went wrong...', 'danger');
      });
    });
  };

  $scope.edit = function (application) {
    var modalInstance = show(application, 'create-app.html');
    modalInstance.result.then(function (application) {
      var updateApplication = {
        name: application.name,
        description: application.description
      };
      pushApplication.update({appId: application.pushApplicationID}, updateApplication, function () {
        Notifications.success('Successfully edited application "' + application.name + '".');
      });
    });
  };

  $scope.remove = function (application) {
    var modalInstance = show(application, 'remove-app.html');
    modalInstance.result.then(function () {
      pushApplication.remove({appId: application.pushApplicationID}, function () {
        $scope.applications.splice($scope.applications.indexOf(application), 1);
        Notifications.success('Successfully removed application "' + application.name + '".');
      });
    });
  };

  /*
   * PRIVATE METHODS
   */

  function modalController($scope, $modalInstance, application) {
    $scope.application = application;
    $scope.ok = function (application) {
      $modalInstance.close(application);
    };

    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  }

  function show(application, template) {
    return $modal.open({
      templateUrl: 'views/dialogs/' + template,
      controller: modalController,
      resolve: {
        application: function () {
          return application;
        }
      }
    });
  }
});
<|endoftext|>