<commit_before>const TextBasedChannel = require('./interface/TextBasedChannel');
const Role = require('./Role');
const EvaluatedPermissions = require('./EvaluatedPermissions');
const Constants = require('../util/Constants');
const Collection = require('../util/Collection');

/**
 * Represents a Member of a Guild on Discord
 * @implements {TextBasedChannel}
 */
class GuildMember {
  constructor(guild, data) {
    /**
     * The client that instantiated this GuildMember
     * @type {Client}
     */
    this.client = guild.client;
    Object.defineProperty(this, 'client', { enumerable: false, configurable: false });

    /**
     * The guild that this member is part of
     * @type {Guild}
     */
    this.guild = guild;

    /**
     * The user that this guild member instance Represents
     * @type {User}
     */
    this.user = {};

    this._roles = [];
    if (data) this.setup(data);
  }

  setup(data) {
    /**
     * Whether this member is deafened server-wide
     * @type {boolean}
     */
    this.serverDeaf = data.deaf;

    /**
     * Whether this member is muted server-wide
     * @type {boolean}
     */
    this.serverMute = data.mute;

    /**
     * Whether this member is self-muted
     * @type {boolean}
     */
    this.selfMute = data.self_mute;

    /**
     * Whether this member is self-deafened
     * @type {boolean}
     */
    this.selfDeaf = data.self_deaf;

    /**
     * The voice session ID of this member, if any
     * @type {?string}
     */
    this.voiceSessionID = data.session_id;

    /**
     * The voice channel ID of this member, if any
     * @type {?string}
     */
    this.voiceChannelID = data.channel_id;

    /**
     * Whether this meember is speaking
     * @type {?boolean}
     */
    this.speaking = this.speaking;

    /**
     * The nickname of this Guild Member, if they have one
     * @type {?string}
     */
    this.nickname = data.nick;

    this.user = data.user;
    this._roles = data.roles;
    this._joinDate = new Date(data.joined_at).getTime();
  }

  /**
   * The date this member joined the guild
   * @type {Date}
   */
  get joinDate() {
    return new Date(this._joinDate);
  }

  /**
   * A list of roles that are applied to this GuildMember, mapped by the role ID.
   * @type {Collection<string, Role>}
   * @readonly
   */
  get roles() {
    const list = new Collection();
    const everyoneRole = this.guild.roles.get(this.guild.id);

    if (everyoneRole) list.set(everyoneRole.id, everyoneRole);

    for (const roleID of this._roles) {
      const role = this.guild.roles.get(roleID);
      if (role) list.set(role.id, role);
    }

    return list;
  }

  /**
   * The role of the member with the highest position.
   * @type {Role}
   */
  get highestRole() {
    return this.roles.reduce((prev, role) => !prev || role.position > prev.position ? role : prev);
  }

  /**
   * Whether this member is muted in any way
   * @type {boolean}
   * @readonly
   */
  get mute() {
    return this.selfMute || this.serverMute;
  }

  /**
   * Whether this member is deafened in any way
   * @type {boolean}
   * @readonly
   */
  get deaf() {
    return this.selfDeaf || this.serverDeaf;
  }

  /**
   * The voice channel this member is in, if any
   * @type {?VoiceChannel}
   * @readonly
   */
  get voiceChannel() {
    return this.guild.channels.get(this.voiceChannelID);
  }

  /**
   * The ID of this User
   * @type {string}
   * @readonly
   */
  get id() {
    return this.user.id;
  }

  /**
   * The overall set of permissions for the guild member, taking only roles into account
   * @type {EvaluatedPermissions}
   */
  get permissions() {
    if (this.user.id === this.guild.ownerID) return new EvaluatedPermissions(this, Constants.ALL_PERMISSIONS);

    let permissions = 0;
    const roles = this.roles;
    for (const role of roles.values()) permissions |= role.permissions;

    const admin = Boolean(permissions & (Constants.PermissionFlags.ADMINISTRATOR));
    if (admin) permissions = Constants.ALL_PERMISSIONS;

    return new EvaluatedPermissions(this, permissions);
  }

  /**
   * Whether the member is kickable by the client user.
   * @type {boolean}
   */
  get kickable() {
    if (this.id === this.guild.ownerID) return false;
    if (this.id === this.client.user.id) return false;
    const clientMember = this.member(this.client.member);
    if (!clientMember.hasPermission(Constants.PermissionFlags.KICK_MEMBERS)) return false;
    return clientMember.highestRole.position > this.highestRole.positon;
  }

  /**
   * Whether the member is bannable by the client user.
   * @type {boolean}
   */
  get bannable() {
    if (this.id === this.guild.ownerID) return false;
    if (this.id === this.client.user.id) return false;
    const clientMember = this.member(this.client.member);
    if (!clientMember.hasPermission(Constants.PermissionFlags.BAN_MEMBERS)) return false;
    return clientMember.highestRole.position > this.highestRole.positon;
  }

  /**
   * Returns `channel.permissionsFor(guildMember)`. Returns evaluated permissions for a member in a guild channel.
   * @param {ChannelResolvable} channel Guild channel to use as context
   * @returns {?EvaluatedPermissions}
   */
  permissionsIn(channel) {
    channel = this.client.resolver.resolveChannel(channel);
    if (!channel || !channel.guild) throw new Error('Could not resolve channel to a guild channel.');
    return channel.permissionsFor(this);
  }

  /**
   * Checks if any of the member's roles have a permission.
   * @param {PermissionResolvable} permission The permission to check for
   * @param {boolean} [explicit=false] Whether to require the roles to explicitly have the exact permission
   * @returns {boolean}
   */
  hasPermission(permission, explicit = false) {
    if (!explicit && this.user.id === this.guild.ownerID) return true;
    return this.roles.some(r => r.hasPermission(permission, explicit));
  }

  /**
   * Checks whether the roles of the member allows them to perform specific actions.
   * @param {PermissionResolvable[]} permissions The permissions to check for
   * @param {boolean} [explicit=false] Whether to require the member to explicitly have the exact permissions
   * @returns {boolean}
   */
  hasPermissions(permissions, explicit = false) {
    if (!explicit && this.user.id === this.guild.ownerID) return true;
    return permissions.map(p => this.hasPermission(p, explicit)).every(v => v);
  }

  /**
   * Edit a Guild Member
   * @param {GuildmemberEditData} data The data to edit the member with
   * @returns {Promise<GuildMember>}
   */
  edit(data) {
    return this.client.rest.methods.updateGuildMember(this, data);
  }

  /**
   * Mute/unmute a user
   * @param {boolean} mute Whether or not the member should be muted
   * @returns {Promise<GuildMember>}
   */
  setMute(mute) {
    return this.edit({ mute });
  }

  /**
   * Deafen/undeafen a user
   * @param {boolean} deaf Whether or not the member should be deafened
   * @returns {Promise<GuildMember>}
   */
  setDeaf(deaf) {
    return this.edit({ deaf });
  }

  /**
   * Moves the Guild Member to the given channel.
   * @param {ChannelResolvable} channel The channel to move the member to
   * @returns {Promise<GuildMember>}
   */
  setVoiceChannel(channel) {
    return this.edit({ channel });
  }

  /**
   * Sets the Roles applied to the member.
   * @param {Collection<string, Role>|Role[]|string[]} roles The roles or role IDs to apply
   * @returns {Promise<GuildMember>}
   */
  setRoles(roles) {
    return this.edit({ roles });
  }

  /**
   * Adds a single Role to the member.
   * @param {Role|string} role The role or ID of the role to add
   * @returns {Promise<GuildMember>}
   */
  addRole(role) {
    return this.addRoles([role]);
  }

  /**
   * Adds multiple roles to the member.
   * @param {Collection<string, Role>|Role[]|string[]} roles The roles or role IDs to add
   * @returns {Promise<GuildMember>}
   */
  addRoles(roles) {
    let allRoles;
    if (roles instanceof Collection) {
      allRoles = this._roles.slice();
      for (const role of roles.values()) allRoles.push(role.id);
    } else {
      allRoles = this._roles.concat(roles);
    }
    return this.edit({ roles: allRoles });
  }

  /**
   * Removes a single Role from the member.
   * @param {Role|string} role The role or ID of the role to remove
   * @returns {Promise<GuildMember>}
   */
  removeRole(role) {
    return this.removeRoles([role]);
  }

  /**
   * Removes multiple roles from the member.
   * @param {Collection<string, Role>|Role[]|string[]} roles The roles or role IDs to remove
   * @returns {Promise<GuildMember>}
   */
  removeRoles(roles) {
    const allRoles = this._roles.slice();
    if (roles instanceof Collection) {
      for (const role of roles.values()) {
        const index = allRoles.indexOf(role.id);
        if (index >= 0) allRoles.splice(index, 1);
      }
    } else {
      for (const role of roles) {
        const index = allRoles.indexOf(role instanceof Role ? role.id : role);
        if (index >= 0) allRoles.splice(index, 1);
      }
    }
    return this.edit({ roles: allRoles });
  }

  /**
   * Set the nickname for the Guild Member
   * @param {string} nick The nickname for the Guild Member
   * @returns {Promise<GuildMember>}
   */
  setNickname(nick) {
    return this.edit({ nick });
  }

  /**
   * Deletes any DMs with this Guild Member
   * @returns {Promise<DMChannel>}
   */
  deleteDM() {
    return this.client.rest.methods.deleteChannel(this);
  }

  /**
   * Kick this member from the Guild
   * @returns {Promise<GuildMember>}
   */
  kick() {
    return this.client.rest.methods.kickGuildMember(this.guild, this);
  }

  /**
   * Ban this Guild Member
   * @param {number} [deleteDays=0] The amount of days worth of messages from this member that should
   * also be deleted. Between `0` and `7`.
   * @returns {Promise<GuildMember>}
   * @example
   * // ban a guild member
   * guildMember.ban(7);
   */
  ban(deleteDays = 0) {
    return this.client.rest.methods.banGuildMember(this.guild, this, deleteDays);
  }

  /**
   * When concatenated with a string, this automatically concatenates the User's mention instead of the Member object.
   * @returns {string}
   * @example
   * // logs: Hello from <@123456789>!
   * console.log(`Hello from ${member}!`);
   */
  toString() {
    return String(this.user);
  }

  // These are here only for documentation purposes - they are implemented by TextBasedChannel
  sendMessage() { return; }
  sendTTSMessage() { return; }
  sendFile() { return; }
  sendCode() { return; }
}

TextBasedChannel.applyToClass(GuildMember);

module.exports = GuildMember;
<commit_msg>Replace local usages of GuildMember.id with user.id<commit_after>const TextBasedChannel = require('./interface/TextBasedChannel');
const Role = require('./Role');
const EvaluatedPermissions = require('./EvaluatedPermissions');
const Constants = require('../util/Constants');
const Collection = require('../util/Collection');

/**
 * Represents a Member of a Guild on Discord
 * @implements {TextBasedChannel}
 */
class GuildMember {
  constructor(guild, data) {
    /**
     * The client that instantiated this GuildMember
     * @type {Client}
     */
    this.client = guild.client;
    Object.defineProperty(this, 'client', { enumerable: false, configurable: false });

    /**
     * The guild that this member is part of
     * @type {Guild}
     */
    this.guild = guild;

    /**
     * The user that this guild member instance Represents
     * @type {User}
     */
    this.user = {};

    this._roles = [];
    if (data) this.setup(data);
  }

  setup(data) {
    /**
     * Whether this member is deafened server-wide
     * @type {boolean}
     */
    this.serverDeaf = data.deaf;

    /**
     * Whether this member is muted server-wide
     * @type {boolean}
     */
    this.serverMute = data.mute;

    /**
     * Whether this member is self-muted
     * @type {boolean}
     */
    this.selfMute = data.self_mute;

    /**
     * Whether this member is self-deafened
     * @type {boolean}
     */
    this.selfDeaf = data.self_deaf;

    /**
     * The voice session ID of this member, if any
     * @type {?string}
     */
    this.voiceSessionID = data.session_id;

    /**
     * The voice channel ID of this member, if any
     * @type {?string}
     */
    this.voiceChannelID = data.channel_id;

    /**
     * Whether this meember is speaking
     * @type {?boolean}
     */
    this.speaking = this.speaking;

    /**
     * The nickname of this Guild Member, if they have one
     * @type {?string}
     */
    this.nickname = data.nick;

    this.user = data.user;
    this._roles = data.roles;
    this._joinDate = new Date(data.joined_at).getTime();
  }

  /**
   * The date this member joined the guild
   * @type {Date}
   */
  get joinDate() {
    return new Date(this._joinDate);
  }

  /**
   * A list of roles that are applied to this GuildMember, mapped by the role ID.
   * @type {Collection<string, Role>}
   * @readonly
   */
  get roles() {
    const list = new Collection();
    const everyoneRole = this.guild.roles.get(this.guild.id);

    if (everyoneRole) list.set(everyoneRole.id, everyoneRole);

    for (const roleID of this._roles) {
      const role = this.guild.roles.get(roleID);
      if (role) list.set(role.id, role);
    }

    return list;
  }

  /**
   * The role of the member with the highest position.
   * @type {Role}
   */
  get highestRole() {
    return this.roles.reduce((prev, role) => !prev || role.position > prev.position ? role : prev);
  }

  /**
   * Whether this member is muted in any way
   * @type {boolean}
   * @readonly
   */
  get mute() {
    return this.selfMute || this.serverMute;
  }

  /**
   * Whether this member is deafened in any way
   * @type {boolean}
   * @readonly
   */
  get deaf() {
    return this.selfDeaf || this.serverDeaf;
  }

  /**
   * The voice channel this member is in, if any
   * @type {?VoiceChannel}
   * @readonly
   */
  get voiceChannel() {
    return this.guild.channels.get(this.voiceChannelID);
  }

  /**
   * The ID of this User
   * @type {string}
   * @readonly
   */
  get id() {
    return this.user.id;
  }

  /**
   * The overall set of permissions for the guild member, taking only roles into account
   * @type {EvaluatedPermissions}
   */
  get permissions() {
    if (this.user.id === this.guild.ownerID) return new EvaluatedPermissions(this, Constants.ALL_PERMISSIONS);

    let permissions = 0;
    const roles = this.roles;
    for (const role of roles.values()) permissions |= role.permissions;

    const admin = Boolean(permissions & (Constants.PermissionFlags.ADMINISTRATOR));
    if (admin) permissions = Constants.ALL_PERMISSIONS;

    return new EvaluatedPermissions(this, permissions);
  }

  /**
   * Whether the member is kickable by the client user.
   * @type {boolean}
   */
  get kickable() {
    if (this.user.id === this.guild.ownerID) return false;
    if (this.user.id === this.client.user.id) return false;
    const clientMember = this.member(this.client.member);
    if (!clientMember.hasPermission(Constants.PermissionFlags.KICK_MEMBERS)) return false;
    return clientMember.highestRole.position > this.highestRole.positon;
  }

  /**
   * Whether the member is bannable by the client user.
   * @type {boolean}
   */
  get bannable() {
    if (this.user.id === this.guild.ownerID) return false;
    if (this.user.id === this.client.user.id) return false;
    const clientMember = this.member(this.client.member);
    if (!clientMember.hasPermission(Constants.PermissionFlags.BAN_MEMBERS)) return false;
    return clientMember.highestRole.position > this.highestRole.positon;
  }

  /**
   * Returns `channel.permissionsFor(guildMember)`. Returns evaluated permissions for a member in a guild channel.
   * @param {ChannelResolvable} channel Guild channel to use as context
   * @returns {?EvaluatedPermissions}
   */
  permissionsIn(channel) {
    channel = this.client.resolver.resolveChannel(channel);
    if (!channel || !channel.guild) throw new Error('Could not resolve channel to a guild channel.');
    return channel.permissionsFor(this);
  }

  /**
   * Checks if any of the member's roles have a permission.
   * @param {PermissionResolvable} permission The permission to check for
   * @param {boolean} [explicit=false] Whether to require the roles to explicitly have the exact permission
   * @returns {boolean}
   */
  hasPermission(permission, explicit = false) {
    if (!explicit && this.user.id === this.guild.ownerID) return true;
    return this.roles.some(r => r.hasPermission(permission, explicit));
  }

  /**
   * Checks whether the roles of the member allows them to perform specific actions.
   * @param {PermissionResolvable[]} permissions The permissions to check for
   * @param {boolean} [explicit=false] Whether to require the member to explicitly have the exact permissions
   * @returns {boolean}
   */
  hasPermissions(permissions, explicit = false) {
    if (!explicit && this.user.id === this.guild.ownerID) return true;
    return permissions.map(p => this.hasPermission(p, explicit)).every(v => v);
  }

  /**
   * Edit a Guild Member
   * @param {GuildmemberEditData} data The data to edit the member with
   * @returns {Promise<GuildMember>}
   */
  edit(data) {
    return this.client.rest.methods.updateGuildMember(this, data);
  }

  /**
   * Mute/unmute a user
   * @param {boolean} mute Whether or not the member should be muted
   * @returns {Promise<GuildMember>}
   */
  setMute(mute) {
    return this.edit({ mute });
  }

  /**
   * Deafen/undeafen a user
   * @param {boolean} deaf Whether or not the member should be deafened
   * @returns {Promise<GuildMember>}
   */
  setDeaf(deaf) {
    return this.edit({ deaf });
  }

  /**
   * Moves the Guild Member to the given channel.
   * @param {ChannelResolvable} channel The channel to move the member to
   * @returns {Promise<GuildMember>}
   */
  setVoiceChannel(channel) {
    return this.edit({ channel });
  }

  /**
   * Sets the Roles applied to the member.
   * @param {Collection<string, Role>|Role[]|string[]} roles The roles or role IDs to apply
   * @returns {Promise<GuildMember>}
   */
  setRoles(roles) {
    return this.edit({ roles });
  }

  /**
   * Adds a single Role to the member.
   * @param {Role|string} role The role or ID of the role to add
   * @returns {Promise<GuildMember>}
   */
  addRole(role) {
    return this.addRoles([role]);
  }

  /**
   * Adds multiple roles to the member.
   * @param {Collection<string, Role>|Role[]|string[]} roles The roles or role IDs to add
   * @returns {Promise<GuildMember>}
   */
  addRoles(roles) {
    let allRoles;
    if (roles instanceof Collection) {
      allRoles = this._roles.slice();
      for (const role of roles.values()) allRoles.push(role.id);
    } else {
      allRoles = this._roles.concat(roles);
    }
    return this.edit({ roles: allRoles });
  }

  /**
   * Removes a single Role from the member.
   * @param {Role|string} role The role or ID of the role to remove
   * @returns {Promise<GuildMember>}
   */
  removeRole(role) {
    return this.removeRoles([role]);
  }

  /**
   * Removes multiple roles from the member.
   * @param {Collection<string, Role>|Role[]|string[]} roles The roles or role IDs to remove
   * @returns {Promise<GuildMember>}
   */
  removeRoles(roles) {
    const allRoles = this._roles.slice();
    if (roles instanceof Collection) {
      for (const role of roles.values()) {
        const index = allRoles.indexOf(role.id);
        if (index >= 0) allRoles.splice(index, 1);
      }
    } else {
      for (const role of roles) {
        const index = allRoles.indexOf(role instanceof Role ? role.id : role);
        if (index >= 0) allRoles.splice(index, 1);
      }
    }
    return this.edit({ roles: allRoles });
  }

  /**
   * Set the nickname for the Guild Member
   * @param {string} nick The nickname for the Guild Member
   * @returns {Promise<GuildMember>}
   */
  setNickname(nick) {
    return this.edit({ nick });
  }

  /**
   * Deletes any DMs with this Guild Member
   * @returns {Promise<DMChannel>}
   */
  deleteDM() {
    return this.client.rest.methods.deleteChannel(this);
  }

  /**
   * Kick this member from the Guild
   * @returns {Promise<GuildMember>}
   */
  kick() {
    return this.client.rest.methods.kickGuildMember(this.guild, this);
  }

  /**
   * Ban this Guild Member
   * @param {number} [deleteDays=0] The amount of days worth of messages from this member that should
   * also be deleted. Between `0` and `7`.
   * @returns {Promise<GuildMember>}
   * @example
   * // ban a guild member
   * guildMember.ban(7);
   */
  ban(deleteDays = 0) {
    return this.client.rest.methods.banGuildMember(this.guild, this, deleteDays);
  }

  /**
   * When concatenated with a string, this automatically concatenates the User's mention instead of the Member object.
   * @returns {string}
   * @example
   * // logs: Hello from <@123456789>!
   * console.log(`Hello from ${member}!`);
   */
  toString() {
    return String(this.user);
  }

  // These are here only for documentation purposes - they are implemented by TextBasedChannel
  sendMessage() { return; }
  sendTTSMessage() { return; }
  sendFile() { return; }
  sendCode() { return; }
}

TextBasedChannel.applyToClass(GuildMember);

module.exports = GuildMember;
<|endoftext|>


<commit_before>// Currently all the tests based on ActiveRecord are running synchronously
// Making test Stub using decorator
var ActiveRecordStub = function(name) {
  var stub = ActiveRecord();
  stub.table = name;
  stub.wrapSave = Meteor.wrapAsync(stub.save.bind(stub));
  stub.wrapFetch = Meteor.wrapAsync(stub.fetch.bind(stub));
  return stub;
};

/**
* Simple table test
*/
var testTasksTable = {
  text: ['$string', '$notnull']
};

var testUserTable = {
  username: ['$string', '$notnull'],
  age: ['$number']
};

if (Meteor.isServer) {
  var testTasks = ActiveRecordStub('testTasks');
  testTasks.dropTable().wrapSave(null, null);
  testTasks.createTable(testTasksTable).wrapSave(null, null);
  testTasks.insert({ text: 'testing1' }).wrapSave(null, null);
  testTasks.insert({ text: 'testing2' }).wrapSave(null, null);
  testTasks.insert({ text: 'testing3' }).wrapSave(null, null);
  for ( var i = 0; i < 5; i++) {
    testTasks.insert({ text: 'testing1' }).wrapSave(null, null);
  }

  var testUser = ActiveRecordStub('testUser');
  testUser.dropTable().wrapSave(null, null);
  testUser.createTable(testUserTable).wrapSave(null, null);
  for (var i = 0; i < 3; i++) {
    testUser.insert({ username: 'eddie' + i, age: 2 * i }).wrapSave(null, null);
    testUser.insert({ username: 'paulo', age: 27}).wrapSave(null, null);
  }

  //Should test the operation defined in the ActiveRecord and return result successfully
  Tinytest.addAsync('activerecord - basic - success', function(test, onComplete) {
    var findOneResult1 = testTasks.findOne().wrapFetch(null, null);
    var findOneResult2 = testTasks.findOne(1).wrapFetch(null, null);
    test.equal(typeof findOneResult1.rows[0], 'object');
    test.equal(findOneResult1.rows.length, 1);
    test.equal(findOneResult1.rows[0].text, 'testing1');
    test.equal(typeof findOneResult2.rows[0], 'object');
    test.equal(findOneResult2.rows.length, 1);
    test.equal(findOneResult2.rows[0].text, 'testing1');

    //select
    var result = testTasks.select().where('text = ?', 'testing1').wrapFetch(null, null);
    //select + limit
    var result2 = testTasks.select().where('text = ?', 'testing1').limit(3).wrapFetch(null, null);
    //select + limit + offset
    var result3 = testTasks.select().where('text = ?', 'testing1').limit(3).offset(2).wrapFetch(null, null);
    //select + offset
    var result4 = testTasks.select().where('text = ?', 'testing1').offset(2).wrapFetch(null, null);
    var result5 = testTasks.select().where('text = ?', 'testing1').offset(6).wrapFetch(null, null);
    var result6 = testTasks.select().where('text = ?', 'testing1').offset(8).wrapFetch(null, null);
    //order default and DESC/ASC
    var result7 = testTasks.select().order('text').wrapFetch(null, null);
    var result8 = testTasks.select().order('text ASC').wrapFetch(null, null);
    var result9 = testTasks.select().order('text DESC').wrapFetch(null, null);
    //chaining order
    var result10 = testTasks.select().where('text = ?', 'testing1').order('id DESC').offset(2).limit(3).wrapFetch(null, null);
    var result11 = testTasks.select().where('text = ?', 'testing1').offset(2).order('id DESC').limit(3).wrapFetch(null, null);

    test.equal(typeof result.rows, 'object');
    test.equal(result.rows.length, 6);
    _.each(result.rows, function(item) {
      test.equal(item.text, 'testing1');
    });
    test.equal(result2.rows.length, 3);
    _.each(result2.rows, function(item) {
      test.equal(item.text, 'testing1');
    });
    test.equal(result3.rows.length, 3);
    _.each(result3.rows, function(item) {
      test.equal(item.text, 'testing1');
    });
    test.equal(result4.rows.length, 4);
    _.each(result4.rows, function(item) {
      test.equal(item.text, 'testing1');
    });
    test.equal(result5.rows.length, 0);
    test.equal(result6.rows.length, 0);
    test.equal(result7.rows, result8.rows);
    test.equal(result7.rows[7], result9.rows[0]);
    test.equal(result10.rows, result11.rows);

    // Non-overreiden first, last, take
    var result1 = testTasks.select().offset(2).where('text = ?', 'testing1').order('id DESC').limit(3).first().wrapFetch(null, null);
    var result2 = testTasks.select().first(2).wrapFetch(null, null);
    var result3 = testTasks.select().last(4).wrapFetch(null, null);
    var result4 = testTasks.select().offset(2).where('text = ?', 'testing1').order('id DESC').limit(3).last().wrapFetch(null, null);
    var result5 = testTasks.select().offset(2).order('id DESC').limit(3).take().wrapFetch(null, null);
    var result6 = testTasks.select().take().wrapSave(null, null);
    //should consider chainging order for first, last, take?
    test.equal(result1.rows[0], result2.rows[0]);
    test.equal(result3.rows[0], result4.rows[0]);
    test.equal(result3.rows[1].id, 7);
    test.equal(result5.rows, result6.rows);

    //update and remove
    // update coverage should take another args, currently just 1 arg
    // should better add the rule that forbid changes in id?
    var origin = testTasks.select().where('text = ?', 'testing1').wrapSave(null, null);
    testTasks.update({ text: 'testing1' }).where('text = ?', 'testing2').wrapSave(null, null);
    var result1 = testTasks.select().where('text = ?', 'testing1').wrapFetch(null, null);
    test.equal(origin.rows.length + 1, result1.rows.length);
    testTasks.update( {text: 'testing3'} ).wrapSave(null, null);
    var result2 = testTasks.select().where('text = ?', 'testing1').wrapFetch(null, null);
    var result3 = testTasks.select().where('text = ?', 'testing3').wrapFetch(null, null);
    test.equal(result2.rows.length, 0);
    test.equal(result3.rows.length, 8);

    testTasks.where('id = ?', '2').remove().wrapSave(null, null);
    var result1 = testTasks.select().wrapFetch(null, null);
    test.equal(result1.rows.length, 7);
    testTasks.remove().wrapSave(null, null);
    var result2 = testTasks.select().wrapFetch(null, null);
    test.equal(result2.rows.length, 0);

    // branch coverage TODO
    // select args not empty branch
      // not empty and no distinct
    // var result1 = testUser.select('testUser.username', 'testUser.age').
      // not empty and has distinct

    // update args > 1 branch
    testUser.update({username: 'PaulOS', age: 100}).where('username = ?', 'notexist').wrapSave(null, null);
    var result1 = testUser.select().where('username = ?', 'PaulOS').wrapFetch(null, null);
    test.equal(result1.rows.length, 0);

    testUser.update({username: 'PaulOS', age: 100}).where('username = ?', 'paulo').wrapSave(null, null);
    var result2 = testUser.select().where('username = ?', 'PaulOS').wrapFetch(null, null);
    test.equal(result2.rows.length, 3);
    _.each(result2.rows, function(item) {
      test.equal(item.username, 'PaulOS');
      test.equal(item.age, 100);
    });

    onComplete();
  });

  //Should throw error for the test failed case
  Tinytest.addAsync('activerecord - basic - failure', function(test, onComplete) {
    // create already existed throw error
    test.throws(function() {
      testTasks.createTable(testTasks).wrapSave(null, null);
    });
    // throw error is schema different
    test.throws(function() {
      testTasks.insert({ text: 'failure', username: 'eric'}).wrapSave(null, null);
    });
    //update error
    test.throws(function() {
      testTasks.update( {username: 'kate'} ).where('text = ?', 'testing3').wrapSave(null, null);
    });

    // How should update behavior for non-existed where?
    // test.throws(function() {
    //   testTasks.update( {text: 'testing2'} ).where('text = ?', 'testing2').wrapSave(null, null);
    // });
    // Should not throw error if drop an unexisted table

    try {
      var expectedError;
      testTasks.dropTable('notExistedTable').wrapSave(null, null);
    } catch(error) {
      expectedError = error;
    }
    test.isTrue(!expectedError);
    //findOne can only find id
    test.throws(function() {
      testTasks.findOne('testing1').wrapFetch(null, null);
    });

    //Clear the table after use
    testTasks.dropTable().wrapSave(null, null);
    testUser.dropTable().wrapSave(null, null);
    onComplete();
  });

  //Complex table
  // Todo: createRelationShip
  //       Join table test
  var testTree = ActiveRecordStub('testTree');
  var testLocation = ActiveRecordStub('testLocation');
  var testSpecies = ActiveRecordStub('testSpecies');

  var testTreeTable = {
    id: ['$number', '$notnull'],
    treename: ['$string', '$notnull'],
    locationid: ['$number', '$notnull'],
    speciesid: ['$number', '$notnull']
  };

  var testLocationTable = {
    id: ['$number', '$notnull'],
    longitude: ['$float', '$notnull'],
    latitude: ['$float', '$notnull']
  };

  var testSpeciesTable = {
    id: ['$number', '$notnull'],
    species: ['$string', '$notnull']
  };

  testTree.dropTable().wrapSave(null, null);
  testLocation.dropTable().wrapSave(null, null);
  testSpecies.dropTable().wrapSave(null, null);

  var testTree = ActiveRecordStub('testTree');
  var testLocation = ActiveRecordStub('testLocationTable');
  var testSpecies = ActiveRecordStub('testSpeciesTable');

  Tinytest.addAsync('activerecord - advanced - success', function(test, onComplete) {
    testTree.dropTable().wrapSave(null, null);
    testLocation.dropTable().wrapSave(null, null);
    testSpecies.dropTable().wrapSave(null, null);
    onComplete();
  });
}

// Connection test, should be added after the default connect string removed
Meteor.isServer && Tinytest.add('activerecord - connection failure',
  function(test) {

  }
);

<commit_msg>(test) where new feature<commit_after>// Currently all the tests based on ActiveRecord are running synchronously
// Making test Stub using decorator
var ActiveRecordStub = function(name) {
  var stub = ActiveRecord();
  stub.table = name;
  stub.wrapSave = Meteor.wrapAsync(stub.save.bind(stub));
  stub.wrapFetch = Meteor.wrapAsync(stub.fetch.bind(stub));
  return stub;
};

/**
* Simple table test
*/
var testTasksTable = {
  text: ['$string', '$notnull']
};

var testUserTable = {
  username: ['$string', '$notnull'],
  age: ['$number']
};

if (Meteor.isServer) {
  var testTasks = ActiveRecordStub('testTasks');
  testTasks.dropTable().wrapSave(null, null);
  testTasks.createTable(testTasksTable).wrapSave(null, null);
  testTasks.insert({ text: 'testing1' }).wrapSave(null, null);
  testTasks.insert({ text: 'testing2' }).wrapSave(null, null);
  testTasks.insert({ text: 'testing3' }).wrapSave(null, null);
  for ( var i = 0; i < 5; i++) {
    testTasks.insert({ text: 'testing1' }).wrapSave(null, null);
  }

  var testUser = ActiveRecordStub('testUser');
  testUser.dropTable().wrapSave(null, null);
  testUser.createTable(testUserTable).wrapSave(null, null);
  for (var i = 0; i < 3; i++) {
    testUser.insert({ username: 'eddie' + i, age: 2 * i }).wrapSave(null, null);
    testUser.insert({ username: 'paulo', age: 27}).wrapSave(null, null);
  }

  //Should test the operation defined in the ActiveRecord and return result successfully
  Tinytest.addAsync('activerecord - basic - success', function(test, onComplete) {
    var findOneResult1 = testTasks.findOne().wrapFetch(null, null);
    var findOneResult2 = testTasks.findOne(1).wrapFetch(null, null);
    test.equal(typeof findOneResult1.rows[0], 'object');
    test.equal(findOneResult1.rows.length, 1);
    test.equal(findOneResult1.rows[0].text, 'testing1');
    test.equal(typeof findOneResult2.rows[0], 'object');
    test.equal(findOneResult2.rows.length, 1);
    test.equal(findOneResult2.rows[0].text, 'testing1');

    //select
    var result = testTasks.select().where('text = ?', 'testing1').wrapFetch(null, null);
    //select + limit
    var result2 = testTasks.select().where('text = ?', 'testing1').limit(3).wrapFetch(null, null);
    //select + limit + offset
    var result3 = testTasks.select().where('text = ?', 'testing1').limit(3).offset(2).wrapFetch(null, null);
    //select + offset
    var result4 = testTasks.select().where('text = ?', 'testing1').offset(2).wrapFetch(null, null);
    var result5 = testTasks.select().where('text = ?', 'testing1').offset(6).wrapFetch(null, null);
    var result6 = testTasks.select().where('text = ?', 'testing1').offset(8).wrapFetch(null, null);
    //order default and DESC/ASC
    var result7 = testTasks.select().order('text').wrapFetch(null, null);
    var result8 = testTasks.select().order('text ASC').wrapFetch(null, null);
    var result9 = testTasks.select().order('text DESC').wrapFetch(null, null);
    //chaining order
    var result10 = testTasks.select().where('text = ?', 'testing1').order('id DESC').offset(2).limit(3).wrapFetch(null, null);
    var result11 = testTasks.select().where('text = ?', 'testing1').offset(2).order('id DESC').limit(3).wrapFetch(null, null);

    test.equal(typeof result.rows, 'object');
    test.equal(result.rows.length, 6);
    _.each(result.rows, function(item) {
      test.equal(item.text, 'testing1');
    });
    test.equal(result2.rows.length, 3);
    _.each(result2.rows, function(item) {
      test.equal(item.text, 'testing1');
    });
    test.equal(result3.rows.length, 3);
    _.each(result3.rows, function(item) {
      test.equal(item.text, 'testing1');
    });
    test.equal(result4.rows.length, 4);
    _.each(result4.rows, function(item) {
      test.equal(item.text, 'testing1');
    });
    test.equal(result5.rows.length, 0);
    test.equal(result6.rows.length, 0);
    test.equal(result7.rows, result8.rows);
    test.equal(result7.rows[7], result9.rows[0]);
    test.equal(result10.rows, result11.rows);

    var result12 = testTasks.select().where('text = ?', ['testing1', 'testing2']).wrapFetch(null, null);
    var result13 = testTasks.select().where('text = ?', ['testing1']).wrapFetch(null, null);
    var result14 = testTasks.select().where('id = ? AND text = ?', 2, 'testing1').wrapFetch(null, null);
    var result15 = testTasks.select().where('id = ? AND text = ?', [1, 2, 3], ['testing1', 'testing2']).wrapFetch(null, null);
    test.equal(result12.rows.length, 7);
    test.equal(result12.rows[1].text, 'testing2');
    test.equal(result13.rows, result.rows);
    test.equal(result14.rows.length, 0);
    test.equal(result15.rows.length, 2);
    test.equal(result15.rows[0].id, 1);
    test.equal(result15.rows[1].id, 2);
    test.equal(result15.rows[0].text, 'testing1');
    test.equal(result15.rows[1].text, 'testing2');
    // Non-overreiden first, last, take
    var result1 = testTasks.select().offset(2).where('text = ?', 'testing1').order('id DESC').limit(3).first().wrapFetch(null, null);
    var result2 = testTasks.select().first(2).wrapFetch(null, null);
    var result3 = testTasks.select().last(4).wrapFetch(null, null);
    var result4 = testTasks.select().offset(2).where('text = ?', 'testing1').order('id DESC').limit(3).last().wrapFetch(null, null);
    var result5 = testTasks.select().offset(2).order('id DESC').limit(3).take().wrapFetch(null, null);
    var result6 = testTasks.select().take().wrapSave(null, null);
    //should consider chainging order for first, last, take?
    test.equal(result1.rows[0], result2.rows[0]);
    test.equal(result3.rows[0], result4.rows[0]);
    test.equal(result3.rows[1].id, 7);
    test.equal(result5.rows, result6.rows);

    //update and remove
    // update coverage should take another args, currently just 1 arg
    // should better add the rule that forbid changes in id?
    var origin = testTasks.select().where('text = ?', 'testing1').wrapSave(null, null);
    testTasks.update({ text: 'testing1' }).where('text = ?', 'testing2').wrapSave(null, null);
    var result1 = testTasks.select().where('text = ?', 'testing1').wrapFetch(null, null);
    test.equal(origin.rows.length + 1, result1.rows.length);
    testTasks.update( {text: 'testing3'} ).wrapSave(null, null);
    var result2 = testTasks.select().where('text = ?', 'testing1').wrapFetch(null, null);
    var result3 = testTasks.select().where('text = ?', 'testing3').wrapFetch(null, null);
    test.equal(result2.rows.length, 0);
    test.equal(result3.rows.length, 8);

    testTasks.where('id = ?', '2').remove().wrapSave(null, null);
    var result1 = testTasks.select().wrapFetch(null, null);
    test.equal(result1.rows.length, 7);
    testTasks.remove().wrapSave(null, null);
    var result2 = testTasks.select().wrapFetch(null, null);
    test.equal(result2.rows.length, 0);

    // branch coverage TODO
    // select args not empty branch
      // not empty and no distinct
    // var result1 = testUser.select('testUser.username', 'testUser.age').
      // not empty and has distinct

    // update args > 1 branch
    testUser.update({username: 'PaulOS', age: 100}).where('username = ?', 'notexist').wrapSave(null, null);
    var result1 = testUser.select().where('username = ?', 'PaulOS').wrapFetch(null, null);
    test.equal(result1.rows.length, 0);

    testUser.update({username: 'PaulOS', age: 100}).where('username = ?', 'paulo').wrapSave(null, null);
    var result2 = testUser.select().where('username = ?', 'PaulOS').wrapFetch(null, null);
    test.equal(result2.rows.length, 3);
    _.each(result2.rows, function(item) {
      test.equal(item.username, 'PaulOS');
      test.equal(item.age, 100);
    });

    onComplete();
  });

  //Should throw error for the test failed case
  Tinytest.addAsync('activerecord - basic - failure', function(test, onComplete) {
    // create already existed throw error
    test.throws(function() {
      testTasks.createTable(testTasks).wrapSave(null, null);
    });
    // throw error is schema different
    test.throws(function() {
      testTasks.insert({ text: 'failure', username: 'eric'}).wrapSave(null, null);
    });
    //update error
    test.throws(function() {
      testTasks.update( {username: 'kate'} ).where('text = ?', 'testing3').wrapSave(null, null);
    });

    // How should update behavior for non-existed where?
    // test.throws(function() {
    //   testTasks.update( {text: 'testing2'} ).where('text = ?', 'testing2').wrapSave(null, null);
    // });
    // Should not throw error if drop an unexisted table

    try {
      var expectedError;
      testTasks.dropTable('notExistedTable').wrapSave(null, null);
    } catch(error) {
      expectedError = error;
    }
    test.isTrue(!expectedError);
    //findOne can only find id
    test.throws(function() {
      testTasks.findOne('testing1').wrapFetch(null, null);
    });

    //Clear the table after use
    testTasks.dropTable().wrapSave(null, null);
    testUser.dropTable().wrapSave(null, null);
    onComplete();
  });

  //Complex table
  // Todo: createRelationShip
  //       Join table test
  var testTree = ActiveRecordStub('testTree');
  var testLocation = ActiveRecordStub('testLocation');
  var testSpecies = ActiveRecordStub('testSpecies');

  var testTreeTable = {
    id: ['$number', '$notnull'],
    treename: ['$string', '$notnull'],
    locationid: ['$number', '$notnull'],
    speciesid: ['$number', '$notnull']
  };

  var testLocationTable = {
    id: ['$number', '$notnull'],
    longitude: ['$float', '$notnull'],
    latitude: ['$float', '$notnull']
  };

  var testSpeciesTable = {
    id: ['$number', '$notnull'],
    species: ['$string', '$notnull']
  };

  testTree.dropTable().wrapSave(null, null);
  testLocation.dropTable().wrapSave(null, null);
  testSpecies.dropTable().wrapSave(null, null);

  var testTree = ActiveRecordStub('testTree');
  var testLocation = ActiveRecordStub('testLocationTable');
  var testSpecies = ActiveRecordStub('testSpeciesTable');

  Tinytest.addAsync('activerecord - advanced - success', function(test, onComplete) {
    testTree.dropTable().wrapSave(null, null);
    testLocation.dropTable().wrapSave(null, null);
    testSpecies.dropTable().wrapSave(null, null);
    onComplete();
  });
}

// Connection test, should be added after the default connect string removed
Meteor.isServer && Tinytest.add('activerecord - connection failure',
  function(test) {

  }
);

<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import Immutable from 'immutable';
import moment from 'moment';
import _ from 'lodash';

import TimeInput from '../../../TimeInput';
import * as periodUtils from '../../../../../common/periodUtils';

import styles from './less/PeriodsForm.less';

function findType(types, value) {
    return types.find((type) => type.get('pty_id') === value);
}

export default class extends React.Component {
    static propTypes = {
        period: React.PropTypes.instanceOf(Immutable.Map).isRequired,
        types: React.PropTypes.instanceOf(Immutable.List).isRequired,
        dayTargetTime: React.PropTypes.objectOf(moment.duration).isRequired,
        index: React.PropTypes.number.isRequired,
        onRemove: React.PropTypes.func.isRequired,
        onUpdate: React.PropTypes.func.isRequired,
    };

    constructor(props, context) {
        super(props, context);
        this.handleComment = this.handleComment.bind(this);
        this.handleDurationChange = this.handleDurationChange.bind(this);
        this.handleTimeChange = this.handleTimeChange.bind(this);
        this.handleTypeChange = this.handleTypeChange.bind(this);
        this.renderDurationRadio = this.renderDurationRadio.bind(this);
        this.renderSelectOption = this.renderSelectOption.bind(this);
        let period = props.period;
        if (!period.get('type')) {
            period = period.merge({
                type: findType(props.types, 'Work'),
            });
        }
        // handle default duration to be the first duration found in the config
        if (!period.get('duration')) {
            period = period.merge({
                duration: period.get('type').get('pty_config').get('types').keySeq().first(),
            });
            // add duration per_duration object if needed
            period = period.merge(this.addDurationTime(period));
        }

        this.state = { period };
    }

    componentDidMount() {
        // focus on select on first creation
        ReactDOM.findDOMNode(this.refs.selectType).focus();
    }

    handleTypeChange(event) {
        const type = findType(this.props.types, event.target.value);
        const cfg = type.get('pty_config').get('types').toJS();
        const defaultDuration = _.findKey(cfg, (value) => value) || periodUtils.NONE;

        const period = this.state.period.merge({
            type,
            duration: cfg[this.state.period.get('duration')] ? this.state.period.get('duration') : defaultDuration,
        });
        this.updateState(period);
    }

    handleDurationChange(event) {
        let period = this.state.period.merge({
            duration: event.target.value,
        });

        // if duration type is not period, remove it
        if (event.target.value !== periodUtils.PERIOD) {
            period = period.merge({
                per_start: null,
                per_stop: null,
                per_break: null,
            });
        }

        this.updateState(period);
    }

    handleTimeChange(name, duration) {
        const value = {};
        value[name] = duration;
        const period = this.state.period.merge(value);

        this.updateState(period);
    }

    handleComment(event) {
        const period = this.state.period.merge({
            per_comment: event.target.value,
        });
        this.updateState(period);
    }

    addDurationTime(period) {
        return period.merge({
            per_duration: periodUtils.calculateDuration(period, this.props.dayTargetTime),
        });
    }

    updateState(period) {
        // add duration per_duration object if needed
        const updatedPeriod = period.merge(this.addDurationTime(period));
        this.props.onUpdate(updatedPeriod);
        this.setState({ updatedPeriod });
    }

    renderSelectOption(type) {
        return (
            <option value={type.get('pty_id')} key={type.get('pty_id')}>{type.get('pty_name')}</option>
        );
    }

    renderDurationRadio(elementName, value, duration, index) {
        const id = `${elementName}-${duration.name}`;

        return (

                    <input type="radio" name={ `${elementName}[duration]` } id={id} value={duration.name}
                        checked={duration.name === value}
                        onChange={this.handleDurationChange}
                    />
                    {duration.description}

        );
    }

    renderErrorMessages() {
        const period = this.state.period;
        const errors = periodUtils.getAllErrors(period);

        return (

                {errors.map((msg, index) => {msg})}

        );
    }

    render() {
        const period = this.state.period;
        const isValid = periodUtils.validatePeriod(period);

        const elementName = `period-${period.get('per_id') ? period.get('per_id') : this.props.index}`;

        const cfg = period.getIn(['type', 'pty_config', 'types']) || new Immutable.Map();

        const durations = periodUtils.durationConfig.filter(d => cfg.get(d.name) === true);

        let periodElements = [];
        const elementCss = 'controls col-xs-6 col-sm-2 col-lg-1 tt-col-lg-1';
        const comment = { name: `${elementName}[per_comment]`, className: 'controls col-xs-12 col-lg-8' };
        if (period.get('duration') === periodUtils.PERIOD) {
            periodElements = [{
                id: 'per_start',
                label: 'Startzeit',
                name: `${elementName}[per_start]`,
                className: elementCss,
                placeholder: 'hh:mm',
                value: period.get('per_start'),
                required: true,
                round: -15,
            }, {
                id: 'per_stop',
                label: 'Endzeit',
                name: `${elementName}[per_stop]`,
                className: elementCss,
                placeholder: 'hh:mm',
                value: period.get('per_stop'),
                required: false,
                round: +15,
            }, {
                id: 'per_break',
                label: 'Pause',
                name: `${elementName}[per_break]`,
                className: elementCss,
                placeholder: 'hh:mm',
                value: period.get('per_break'),
                required: false,
                round: +15,
            }];

            comment.className += ' col-sm-6';
        }

        return (

                {!isValid ? this.renderErrorMessages() : ''}

                        <select className="col-xs-12 form-control"
                            name={`${elementName}[pty_id]`}
                            value={period.getIn(['type', 'pty_id'])}
                            onChange={this.handleTypeChange}
                            ref="selectType"
                        >
                            {this.props.types.toList().map(this.renderSelectOption)}
                        </select>

                    {durations.map(this.renderDurationRadio.bind(null, elementName, period.get('duration')))}

                    {periodElements.map((p, index) => <TimeInput id={p.id} label={p.label} name={p.name}
                        css={p.className} placeholder={p.placeholder}
                        time={p.value} required={p.required} key={index}
                        round={p.round}
                        onChange={this.handleTimeChange}
                    />)}

                        Kommentar
                        <input type="text" placeholder="Kommentar" className="form-control"
                            name={comment.name} id={comment.name} value={period.get('per_comment')}
                            onChange={this.handleComment}
                        />

        );
    }
}
<commit_msg>fix errors<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import Immutable from 'immutable';
import moment from 'moment';
import _ from 'lodash';

import TimeInput from '../../../TimeInput';
import * as periodUtils from '../../../../../common/periodUtils';

import styles from './less/PeriodsForm.less';

function findType(types, value) {
    return types.find(type => type.get('pty_id') === value);
}

export default class extends React.Component {
    static propTypes = {
        period: React.PropTypes.instanceOf(Immutable.Map).isRequired,
        types: React.PropTypes.instanceOf(Immutable.List).isRequired,
        dayTargetTime: React.PropTypes.objectOf(moment.duration).isRequired,
        index: React.PropTypes.number.isRequired,
        onRemove: React.PropTypes.func.isRequired,
        onUpdate: React.PropTypes.func.isRequired,
    };

    constructor(props, context) {
        super(props, context);
        this.handleComment = this.handleComment.bind(this);
        this.handleDurationChange = this.handleDurationChange.bind(this);
        this.handleTimeChange = this.handleTimeChange.bind(this);
        this.handleTypeChange = this.handleTypeChange.bind(this);
        this.renderDurationRadio = this.renderDurationRadio.bind(this);
        this.renderSelectOption = this.renderSelectOption.bind(this);
        let period = props.period;
        if (!period.get('type')) {
            period = period.merge({
                type: findType(props.types, 'Work'),
            });
        }
        // handle default duration to be the first duration found in the config
        if (!period.get('duration')) {
            period = period.merge({
                duration: period.get('type').get('pty_config').get('types').keySeq().first(),
            });
            // add duration per_duration object if needed
            period = period.merge(this.addDurationTime(period));
        }

        this.state = { period };
    }

    componentDidMount() {
        // focus on select on first creation
        ReactDOM.findDOMNode(this.refs.selectType).focus();
    }

    handleTypeChange(event) {
        const type = findType(this.props.types, event.target.value);
        const cfg = type.get('pty_config').get('types').toJS();
        const defaultDuration = _.findKey(cfg, value => value) || periodUtils.NONE;

        const period = this.state.period.merge({
            type,
            duration: cfg[this.state.period.get('duration')] ? this.state.period.get('duration') : defaultDuration,
        });
        this.updateState(period);
    }

    handleDurationChange(event) {
        let period = this.state.period.merge({
            duration: event.target.value,
        });

        // if duration type is not period, remove it
        if (event.target.value !== periodUtils.PERIOD) {
            period = period.merge({
                per_start: null,
                per_stop: null,
                per_break: null,
            });
        }

        this.updateState(period);
    }

    handleTimeChange(name, duration) {
        const value = {};
        value[name] = duration;
        const period = this.state.period.merge(value);

        this.updateState(period);
    }

    handleComment(event) {
        const period = this.state.period.merge({
            per_comment: event.target.value,
        });
        this.updateState(period);
    }

    addDurationTime(period) {
        return period.merge({
            per_duration: periodUtils.calculateDuration(period, this.props.dayTargetTime),
        });
    }

    updateState(period) {
        // add duration per_duration object if needed
        const updatedPeriod = period.merge(this.addDurationTime(period));
        this.props.onUpdate(updatedPeriod);
        this.setState({ updatedPeriod });
    }

    renderSelectOption(type) {
        return (
            <option value={type.get('pty_id')} key={type.get('pty_id')}>{type.get('pty_name')}</option>
        );
    }

    renderDurationRadio(elementName, value, duration, index) {
        const id = `${elementName}-${duration.name}`;

        return (

                    <input type="radio" name={ `${elementName}[duration]` } id={id} value={duration.name}
                        checked={duration.name === value}
                        onChange={this.handleDurationChange}
                    />
                    {duration.description}

        );
    }

    renderErrorMessages() {
        const period = this.state.period;
        const errors = periodUtils.getAllErrors(period);

        return (

                {errors.map((msg, index) => {msg})}

        );
    }

    render() {
        const period = this.state.period;
        const isValid = periodUtils.validatePeriod(period);

        const elementName = `period-${period.get('per_id') ? period.get('per_id') : this.props.index}`;

        const cfg = period.getIn(['type', 'pty_config', 'types']) || new Immutable.Map();

        const durations = periodUtils.durationConfig.filter(d => cfg.get(d.name) === true);

        let periodElements = [];
        const elementCss = 'controls col-xs-6 col-sm-2 col-lg-1 tt-col-lg-1';
        const comment = { name: `${elementName}[per_comment]`, className: 'controls col-xs-12 col-lg-8' };
        if (period.get('duration') === periodUtils.PERIOD) {
            periodElements = [{
                id: 'per_start',
                label: 'Startzeit',
                name: `${elementName}[per_start]`,
                className: elementCss,
                placeholder: 'hh:mm',
                value: period.get('per_start'),
                required: true,
                round: -15,
            }, {
                id: 'per_stop',
                label: 'Endzeit',
                name: `${elementName}[per_stop]`,
                className: elementCss,
                placeholder: 'hh:mm',
                value: period.get('per_stop'),
                required: false,
                round: +15,
            }, {
                id: 'per_break',
                label: 'Pause',
                name: `${elementName}[per_break]`,
                className: elementCss,
                placeholder: 'hh:mm',
                value: period.get('per_break'),
                required: false,
                round: +15,
            }];

            comment.className += ' col-sm-6';
        }

        return (

                {!isValid ? this.renderErrorMessages() : ''}

                        <select className="col-xs-12 form-control"
                            name={`${elementName}[pty_id]`}
                            value={period.getIn(['type', 'pty_id'])}
                            onChange={this.handleTypeChange}
                            ref="selectType"
                        >
                            {this.props.types.toList().map(this.renderSelectOption)}
                        </select>

                    {durations.map(this.renderDurationRadio.bind(null, elementName, period.get('duration')))}

                    {periodElements.map((p, index) => <TimeInput id={p.id} label={p.label} name={p.name}
                        css={p.className} placeholder={p.placeholder}
                        time={p.value} required={p.required} key={index}
                        round={p.round}
                        onChange={this.handleTimeChange}
                    />)}

                        Kommentar
                        <input type="text" placeholder="Kommentar" className="form-control"
                            name={comment.name} id={comment.name} value={period.get('per_comment')}
                            onChange={this.handleComment}
                        />

        );
    }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Recursively search a JSON object tree to find all the values of a key/property
 * @param {string} prop - The name of the key or property
 * @param {object} obj - The object to search within
 * @param {array} found - The list of recursively added values of found key
 */
export const searchKeyInObject = (obj, prop, found = []) => {
    if (obj && Object.keys(obj).length) {
        for (let [key, value] of Object.entries(obj)) {
            if (key === prop) {
                found.push(value);
                return found;
            }
            if (typeof obj[key] === 'object' && Object.keys(obj[key]).length) {
                searchKeyInObject(obj[key], prop, found);
            } else if (Array.isArray(obj[key]) && obj[key].length) {
                for (let item of obj[key]) {
                    if (typeof item === 'object' && Object.keys(item).length) {
                        searchKeyInObject(item, prop, found);
                    }
                }
            }
        }
    }
    return found;
};<commit_msg>:bug: Fixed bug in which 'undefined' keys in object cause errors<commit_after>'use strict';

/**
 * Recursively search a JSON object tree to find all the values of a key/property
 * @param {string} prop - The name of the key or property
 * @param {object} obj - The object to search within
 * @param {array} found - The list of recursively added values of found key
 */
export const searchKeyInObject = (obj, prop, found = []) => {
    if (obj && Object.keys(obj).length) {
        for (let [key, value] of Object.entries(obj)) {
            if (key === prop) {
                found.push(value);
                return found;
            }
            if (typeof obj[key] !== 'undefined' && obj[key] !== null) {
                if (Object.keys(obj[key]).length) {
                    searchKeyInObject(obj[key], prop, found);
                } else if (Array.isArray(obj[key]) && obj[key].length) {
                    for (let item of obj[key]) {
                        if (typeof item === 'object' && Object.keys(item).length) {
                            searchKeyInObject(item, prop, found);
                        }
                    }
                }
            }
        }
    }
    return found;
};<|endoftext|>


<commit_before>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
// @remove-on-eject-end
'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {};

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: shouldUseSourceMap ? 'source-map' : false,
  // In production, we only want to load the polyfills and the app code.
  entry: [require.resolve('./polyfills'), paths.appIndexJs],
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {
      // @remove-on-eject-begin
      // Resolve Babel runtime relative to react-scripts.
      // It usually still works on npm 3 without this but it would be
      // unfortunate to rely on, as react-scripts could be symlinked,
      // and thus babel-runtime might not be resolvable from the source.
      'babel-runtime': path.dirname(
        require.resolve('babel-runtime/package.json')
      ),
      // @remove-on-eject-end
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { parser: { requireEnsure: false } },

      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),
              // @remove-on-eject-begin
              // TODO: consider separate config for production,
              // e.g. to enable no-console and no-debugger only in production.
              baseConfig: {
                extends: [require.resolve('eslint-config-react-app')],
              },
              ignore: false,
              useEslintrc: false,
              // @remove-on-eject-end
            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc,
      },
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // "url" loader works just like "file" loader but it also embeds
          // assets smaller than specified size as data URLs to avoid requests.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve('url-loader'),
            options: {
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // Process JS with Babel.
          {
            test: /\.(js|jsx)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              // @remove-on-eject-begin
              babelrc: false,
              presets: [require.resolve('babel-preset-react-app')],
              plugins: [require.resolve('babel-plugin-relay')],
              // @remove-on-eject-end
              compact: true,
            },
          },
          // The notation here is somewhat confusing.
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader normally turns CSS into JS modules injecting <style>,
          // but unlike in development configuration, we do something different.
          // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
          // (second argument), then grabs the result CSS and puts it into a
          // separate file in our build process. This way we actually ship
          // a single CSS file in production instead of JS code injecting <style>
          // tags. If you use code splitting, however, any async bundles will still
          // use the "style" loader inside the async code so CSS from them won't be
          // in the main CSS file.
          {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract(
              Object.assign(
                {
                  fallback: {
                    loader: require.resolve('style-loader'),
                    options: {
                      hmr: false,
                    },
                  },
                  use: [
                    {
                      loader: require.resolve('css-loader'),
                      options: {
                        importLoaders: 1,
                        minimize: true,
                        sourceMap: shouldUseSourceMap,
                      },
                    },
                    {
                      loader: require.resolve('postcss-loader'),
                      options: {
                        // Necessary for external CSS imports to work
                        // https://github.com/facebookincubator/create-react-app/issues/2677
                        ident: 'postcss',
                        plugins: () => [
                          require('postcss-flexbugs-fixes'),
                          autoprefixer({
                            browsers: [
                              '>1%',
                              'last 4 versions',
                              'Firefox ESR',
                              'not ie < 9', // React doesn't support IE8 anyway
                            ],
                            flexbox: 'no-2009',
                          }),
                        ],
                      },
                    },
                  ],
                },
                extractTextPluginOptions
              )
            ),
            // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
          },
          {
            test: /\.scss$/,
            loader: ExtractTextPlugin.extract({
              fallbackLoader: 'style-loader',
              loader: 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader!sass-loader',
            }),
          },
          // "file" loader makes sure assets end up in the `build` folder.
          // When you `import` an asset, you get its filename.
          // This loader doesn't use a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            loader: require.resolve('file-loader'),
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.js$/, /\.html$/, /\.json$/],
            options: {
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // ** STOP ** Are you adding a new loader?
          // Make sure to add the new loader(s) before the "file" loader.
        ],
      },
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        // Disabled because of an issue with Uglify breaking seemingly valid code:
        // https://github.com/facebookincubator/create-react-app/issues/2376
        // Pending further investigation:
        // https://github.com/mishoo/UglifyJS2/issues/2011
        comparisons: false,
      },
      output: {
        comments: false,
        // Turned on because emoji and regex is not minified properly using default
        // https://github.com/facebookincubator/create-react-app/issues/2488
        ascii_only: true,
      },
      sourceMap: shouldUseSourceMap,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file so that tools can pick it up without
    // having to parse `index.html`.
    new ManifestPlugin({
      fileName: 'asset-manifest.json',
    }),
    // Generate a service worker script that will precache, and keep up to date,
    // the HTML & assets that are part of the Webpack build.
    new SWPrecacheWebpackPlugin({
      // By default, a cache-busting query parameter is appended to requests
      // used to populate the caches, to ensure the responses are fresh.
      // If a URL is already hashed by Webpack, then there is no concern
      // about it being stale, and the cache-busting can be skipped.
      dontCacheBustUrlsMatching: /\.\w{8}\./,
      filename: 'service-worker.js',
      logger(message) {
        if (message.indexOf('Total precache size is') === 0) {
          // This message occurs for every build and is a bit too noisy.
          return;
        }
        if (message.indexOf('Skipping static resource') === 0) {
          // This message obscures real errors so we ignore it.
          // https://github.com/facebookincubator/create-react-app/issues/2612
          return;
        }
        console.log(message);
      },
      minify: true,
      // For unknown URLs, fallback to the index page
      navigateFallback: publicUrl + '/index.html',
      // Ignores URLs starting from /__ (useful for Firebase):
      // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
      navigateFallbackWhitelist: [/^(?!\/__).*/],
      // Don't precache sourcemaps (they're large) and build asset manifest:
      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
    }),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how Webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  },
};
<commit_msg>prod css-loader<commit_after>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
// @remove-on-eject-end
'use strict';

const autoprefixer = require('autoprefixer');
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin');
const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin');
const paths = require('./paths');
const getClientEnvironment = require('./env');

// Webpack uses `publicPath` to determine where the app is being served from.
// It requires a trailing slash, or the file assets will get an incorrect path.
const publicPath = paths.servedPath;
// Some apps do not use client-side routing with pushState.
// For these, "homepage" can be set to "." to enable relative asset paths.
const shouldUseRelativeAssetPaths = publicPath === './';
// Source maps are resource heavy and can cause out of memory issue for large source files.
const shouldUseSourceMap = process.env.GENERATE_SOURCEMAP !== 'false';
// `publicUrl` is just like `publicPath`, but we will provide it to our app
// as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript.
// Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz.
const publicUrl = publicPath.slice(0, -1);
// Get environment variables to inject into our app.
const env = getClientEnvironment(publicUrl);

// Assert this just to be safe.
// Development builds of React are slow and not intended for production.
if (env.stringified['process.env'].NODE_ENV !== '"production"') {
  throw new Error('Production builds must have NODE_ENV=production.');
}

// Note: defined here because it will be used more than once.
const cssFilename = 'static/css/[name].[contenthash:8].css';

// ExtractTextPlugin expects the build output to be flat.
// (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27)
// However, our output is structured with css, js and media folders.
// To have this structure working with relative paths, we have to use custom options.
const extractTextPluginOptions = shouldUseRelativeAssetPaths
  ? // Making sure that the publicPath goes back to to build folder.
    { publicPath: Array(cssFilename.split('/').length).join('../') }
  : {};

// This is the production configuration.
// It compiles slowly and is focused on producing a fast and minimal bundle.
// The development configuration is different and lives in a separate file.
module.exports = {
  // Don't attempt to continue if there are any errors.
  bail: true,
  // We generate sourcemaps in production. This is slow but gives good results.
  // You can exclude the *.map files from the build during deployment.
  devtool: shouldUseSourceMap ? 'source-map' : false,
  // In production, we only want to load the polyfills and the app code.
  entry: [require.resolve('./polyfills'), paths.appIndexJs],
  output: {
    // The build folder.
    path: paths.appBuild,
    // Generated JS file names (with nested folders).
    // There will be one main bundle, and one file per asynchronous chunk.
    // We don't currently advertise code splitting but Webpack supports it.
    filename: 'static/js/[name].[chunkhash:8].js',
    chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js',
    // We inferred the "public path" (such as / or /my-project) from homepage.
    publicPath: publicPath,
    // Point sourcemap entries to original disk location (format as URL on Windows)
    devtoolModuleFilenameTemplate: info =>
      path
        .relative(paths.appSrc, info.absoluteResourcePath)
        .replace(/\\/g, '/'),
  },
  resolve: {
    // This allows you to set a fallback for where Webpack should look for modules.
    // We placed these paths second because we want `node_modules` to "win"
    // if there are any conflicts. This matches Node resolution mechanism.
    // https://github.com/facebookincubator/create-react-app/issues/253
    modules: ['node_modules', paths.appNodeModules].concat(
      // It is guaranteed to exist because we tweak it in `env.js`
      process.env.NODE_PATH.split(path.delimiter).filter(Boolean)
    ),
    // These are the reasonable defaults supported by the Node ecosystem.
    // We also include JSX as a common component filename extension to support
    // some tools, although we do not recommend using it, see:
    // https://github.com/facebookincubator/create-react-app/issues/290
    // `web` extension prefixes have been added for better support
    // for React Native Web.
    extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
    alias: {
      // @remove-on-eject-begin
      // Resolve Babel runtime relative to react-scripts.
      // It usually still works on npm 3 without this but it would be
      // unfortunate to rely on, as react-scripts could be symlinked,
      // and thus babel-runtime might not be resolvable from the source.
      'babel-runtime': path.dirname(
        require.resolve('babel-runtime/package.json')
      ),
      // @remove-on-eject-end
      // Support React Native Web
      // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/
      'react-native': 'react-native-web',
    },
    plugins: [
      // Prevents users from importing files from outside of src/ (or node_modules/).
      // This often causes confusion because we only process files within src/ with babel.
      // To fix this, we prevent you from importing files out of src/ -- if you'd like to,
      // please link the files into your node_modules/ and let module-resolution kick in.
      // Make sure your source files are compiled, as they will not be processed in any way.
      new ModuleScopePlugin(paths.appSrc, [paths.appPackageJson]),
    ],
  },
  module: {
    strictExportPresence: true,
    rules: [
      // TODO: Disable require.ensure as it's not a standard language feature.
      // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176.
      // { parser: { requireEnsure: false } },

      // First, run the linter.
      // It's important to do this before Babel processes the JS.
      {
        test: /\.(js|jsx)$/,
        enforce: 'pre',
        use: [
          {
            options: {
              formatter: eslintFormatter,
              eslintPath: require.resolve('eslint'),
              // @remove-on-eject-begin
              // TODO: consider separate config for production,
              // e.g. to enable no-console and no-debugger only in production.
              baseConfig: {
                extends: [require.resolve('eslint-config-react-app')],
              },
              ignore: false,
              useEslintrc: false,
              // @remove-on-eject-end
            },
            loader: require.resolve('eslint-loader'),
          },
        ],
        include: paths.appSrc,
      },
      {
        // "oneOf" will traverse all following loaders until one will
        // match the requirements. When no loader matches it will fall
        // back to the "file" loader at the end of the loader list.
        oneOf: [
          // "url" loader works just like "file" loader but it also embeds
          // assets smaller than specified size as data URLs to avoid requests.
          {
            test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/],
            loader: require.resolve('url-loader'),
            options: {
              limit: 10000,
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // Process JS with Babel.
          {
            test: /\.(js|jsx)$/,
            include: paths.appSrc,
            loader: require.resolve('babel-loader'),
            options: {
              // @remove-on-eject-begin
              babelrc: false,
              presets: [require.resolve('babel-preset-react-app')],
              plugins: [require.resolve('babel-plugin-relay')],
              // @remove-on-eject-end
              compact: true,
            },
          },
          // The notation here is somewhat confusing.
          // "postcss" loader applies autoprefixer to our CSS.
          // "css" loader resolves paths in CSS and adds assets as dependencies.
          // "style" loader normally turns CSS into JS modules injecting <style>,
          // but unlike in development configuration, we do something different.
          // `ExtractTextPlugin` first applies the "postcss" and "css" loaders
          // (second argument), then grabs the result CSS and puts it into a
          // separate file in our build process. This way we actually ship
          // a single CSS file in production instead of JS code injecting <style>
          // tags. If you use code splitting, however, any async bundles will still
          // use the "style" loader inside the async code so CSS from them won't be
          // in the main CSS file.
          {
            test: /\.css$/,
            loader: ExtractTextPlugin.extract(
              Object.assign(
                {
                  fallback: {
                    loader: require.resolve('style-loader'),
                    options: {
                      hmr: false,
                    },
                  },
                  use: [
                    {
                      loader: require.resolve('css-loader'),
                      options: {
                        importLoaders: 1,
                        minimize: true,
                        sourceMap: shouldUseSourceMap,
                      },
                    },
                    {
                      loader: require.resolve('postcss-loader'),
                      options: {
                        // Necessary for external CSS imports to work
                        // https://github.com/facebookincubator/create-react-app/issues/2677
                        ident: 'postcss',
                        plugins: () => [
                          require('postcss-flexbugs-fixes'),
                          autoprefixer({
                            browsers: [
                              '>1%',
                              'last 4 versions',
                              'Firefox ESR',
                              'not ie < 9', // React doesn't support IE8 anyway
                            ],
                            flexbox: 'no-2009',
                          }),
                        ],
                      },
                    },
                  ],
                },
                extractTextPluginOptions
              )
            ),
            // Note: this won't work without `new ExtractTextPlugin()` in `plugins`.
          },
          {
            test: /\.scss$/,
            use: [
              'style-loader',
              // Using source maps breaks urls in the CSS loader
              // https://github.com/webpack/css-loader/issues/232
              // This comment solves it, but breaks testing from a local network
              // https://github.com/webpack/css-loader/issues/232#issuecomment-240449998
              // 'css-loader?sourceMap',
              'css-loader?importLoaders=1&modules&localIdentName=[path]___[name]__[local]___[hash:base64:5]',
              'postcss-loader',
              'sass-loader',
            ],
          },
          // "file" loader makes sure assets end up in the `build` folder.
          // When you `import` an asset, you get its filename.
          // This loader doesn't use a "test" so it will catch all modules
          // that fall through the other loaders.
          {
            loader: require.resolve('file-loader'),
            // Exclude `js` files to keep "css" loader working as it injects
            // it's runtime that would otherwise processed through "file" loader.
            // Also exclude `html` and `json` extensions so they get processed
            // by webpacks internal loaders.
            exclude: [/\.js$/, /\.html$/, /\.json$/],
            options: {
              name: 'static/media/[name].[hash:8].[ext]',
            },
          },
          // ** STOP ** Are you adding a new loader?
          // Make sure to add the new loader(s) before the "file" loader.
        ],
      },
    ],
  },
  plugins: [
    // Makes some environment variables available in index.html.
    // The public URL is available as %PUBLIC_URL% in index.html, e.g.:
    // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    // In production, it will be an empty string unless you specify "homepage"
    // in `package.json`, in which case it will be the pathname of that URL.
    new InterpolateHtmlPlugin(env.raw),
    // Generates an `index.html` file with the <script> injected.
    new HtmlWebpackPlugin({
      inject: true,
      template: paths.appHtml,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeRedundantAttributes: true,
        useShortDoctype: true,
        removeEmptyAttributes: true,
        removeStyleLinkTypeAttributes: true,
        keepClosingSlash: true,
        minifyJS: true,
        minifyCSS: true,
        minifyURLs: true,
      },
    }),
    // Makes some environment variables available to the JS code, for example:
    // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`.
    // It is absolutely essential that NODE_ENV was set to production here.
    // Otherwise React will be compiled in the very slow development mode.
    new webpack.DefinePlugin(env.stringified),
    // Minify the code.
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false,
        // Disabled because of an issue with Uglify breaking seemingly valid code:
        // https://github.com/facebookincubator/create-react-app/issues/2376
        // Pending further investigation:
        // https://github.com/mishoo/UglifyJS2/issues/2011
        comparisons: false,
      },
      output: {
        comments: false,
        // Turned on because emoji and regex is not minified properly using default
        // https://github.com/facebookincubator/create-react-app/issues/2488
        ascii_only: true,
      },
      sourceMap: shouldUseSourceMap,
    }),
    // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`.
    new ExtractTextPlugin({
      filename: cssFilename,
    }),
    // Generate a manifest file which contains a mapping of all asset filenames
    // to their corresponding output file so that tools can pick it up without
    // having to parse `index.html`.
    new ManifestPlugin({
      fileName: 'asset-manifest.json',
    }),
    // Generate a service worker script that will precache, and keep up to date,
    // the HTML & assets that are part of the Webpack build.
    new SWPrecacheWebpackPlugin({
      // By default, a cache-busting query parameter is appended to requests
      // used to populate the caches, to ensure the responses are fresh.
      // If a URL is already hashed by Webpack, then there is no concern
      // about it being stale, and the cache-busting can be skipped.
      dontCacheBustUrlsMatching: /\.\w{8}\./,
      filename: 'service-worker.js',
      logger(message) {
        if (message.indexOf('Total precache size is') === 0) {
          // This message occurs for every build and is a bit too noisy.
          return;
        }
        if (message.indexOf('Skipping static resource') === 0) {
          // This message obscures real errors so we ignore it.
          // https://github.com/facebookincubator/create-react-app/issues/2612
          return;
        }
        console.log(message);
      },
      minify: true,
      // For unknown URLs, fallback to the index page
      navigateFallback: publicUrl + '/index.html',
      // Ignores URLs starting from /__ (useful for Firebase):
      // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219
      navigateFallbackWhitelist: [/^(?!\/__).*/],
      // Don't precache sourcemaps (they're large) and build asset manifest:
      staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/],
    }),
    // Moment.js is an extremely popular library that bundles large locale files
    // by default due to how Webpack interprets its code. This is a practical
    // solution that requires the user to opt into importing specific locales.
    // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack
    // You can remove this if you don't use Moment.js:
    new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
  ],
  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  node: {
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty',
  },
};
<|endoftext|>