<commit_before>/* eslint react/prop-types: 0 */
/* eslint-disable no-shadow */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { StyleSheet, Text, FlatList, View } from 'react-native';
import moment from 'moment/min/moment-with-locales.min';

import { LoadingUserListItem, UserListItem, ViewContainer } from 'components';
import { colors, fonts, normalize } from 'config';
import { emojifyText, translate } from 'utils';
import { getUserEvents } from 'auth';
import { getNotificationsCount } from 'notifications';

const mapStateToProps = state => ({
  user: state.auth.user,
  userEvents: state.auth.events,
  locale: state.auth.locale,
  isPendingEvents: state.auth.isPendingEvents,
  accessToken: state.auth.accessToken,
});

const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      getUserEvents,
      getNotificationsCount,
    },
    dispatch
  );

const styles = StyleSheet.create({
  descriptionContainer: {
    justifyContent: 'center',
    flex: 1,
    marginLeft: 10,
    color: colors.primaryDark,
    ...fonts.fontPrimaryLight,
  },
  linkDescription: {
    ...fonts.fontPrimarySemiBold,
  },
  linkBranchDescription: {
    ...fonts.fontCode,
  },
  deletedLinkBranchDescription: {
    color: colors.greyDarkest,
    ...fonts.fontCode,
  },
  date: {
    color: colors.greyDark,
  },
  subtitleContainer: {
    paddingHorizontal: 15,
    paddingBottom: 10,
    borderBottomColor: colors.greyLight,
    borderBottomWidth: 1,
  },
  subtitle: {
    color: colors.greyDark,
    fontSize: normalize(11),
    marginTop: 1,
    ...fonts.fontPrimarySemiBold,
    marginLeft: 39,
  },
  textContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    marginHorizontal: 15,
  },
  noneTitle: {
    fontSize: normalize(14),
    textAlign: 'center',
    ...fonts.fontPrimary,
  },
});

class Events extends Component {
  componentDidMount() {
    this.getUserEvents();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.user.login && !this.props.user.login) {
      this.getUserEvents(nextProps);
    }
  }

  getUserEvents = ({ user, accessToken } = this.props) => {
    this.props.getUserEvents(user.login);
    this.props.getNotificationsCount(accessToken);
  };

  getAction = userEvent => {
    const { locale } = this.props;
    const eventType = userEvent.type;
    /* eslint-disable prefer-const */
    let { action, ref_type: object } = userEvent.payload;

    switch (eventType) {
      case 'CommitCommentEvent':
        return translate('auth.events.commitCommentEvent', locale);
      case 'CreateEvent':
        return translate('auth.events.createEvent', locale, {
          object: translate(`auth.events.objects.${object}`, locale),
        });
      case 'DeleteEvent':
        return translate('auth.events.deleteEvent', locale, {
          object: translate(`auth.events.objects.${object}`, locale),
        });
      case 'ForkEvent':
        return translate('auth.events.actions.forked', locale);
      case 'GollumEvent':
        action = userEvent.payload.pages[0].action;

        return translate(`auth.events.actions.${action}`, locale);
      case 'IssueCommentEvent': {
        const eventsByActions = {
          created: 'issueCommentEvent',
          edited: 'issueEditedEvent',
          deleted: 'issueRemovedEvent',
        };
        const event = eventsByActions[action];

        if (!event) {
          return null;
        }

        if (action === 'created') {
          action = 'commented';
        }

        const issueData = {
          type: userEvent.payload.issue.pull_request
            ? translate('auth.events.types.pullRequest', locale)
            : translate('auth.events.types.issue', locale),
          action: translate(`auth.events.actions.${action}`, locale),
        };

        return translate(`auth.events.${event}`, locale, issueData);
      }
      case 'IssuesEvent':
        return translate('auth.events.issuesEvent', locale, {
          action: translate(`auth.events.actions.${action}`, locale),
        });
      case 'MemberEvent':
        return translate(`auth.events.actions.${action}`, locale);
      case 'PublicEvent':
        return translate('auth.events.publicEvent.action', locale);
      case 'PullRequestEvent':
        return translate('auth.events.pullRequestEvent', locale, {
          action: translate(`auth.events.actions.${action}`, locale),
        });
      case 'PullRequestReviewEvent':
        return translate('auth.events.pullRequestReviewEvent', locale, {
          payload: translate(`auth.events.actions.${action}`, locale),
        });
      case 'PullRequestReviewCommentEvent': {
        if (action === 'created') {
          return translate(
            'auth.events.pullRequestReviewCommentEvent',
            locale,
            {
              action: translate('auth.events.actions.commented', locale),
            }
          );
        } else if (action === 'edited') {
          return translate('auth.events.pullRequestReviewEditedEvent', locale, {
            action: translate(`auth.events.actions.${action}`, locale),
          });
        } else if (action === 'deleted') {
          return translate(
            'auth.events.pullRequestReviewDeletedEvent',
            locale,
            {
              action: translate(`auth.events.actions.${action}`, locale),
            }
          );
        }

        return null;
      }
      case 'PushEvent':
        return translate('auth.events.actions.pushedTo', locale);
      case 'ReleaseEvent':
        return translate('auth.events.releaseEvent', locale, {
          action: translate(`auth.events.actions.${action}`, locale),
        });
      case 'RepositoryEvent':
        return translate(`auth.events.actions.${action}`, locale);
      case 'WatchEvent':
        return translate('auth.events.actions.starred', locale);
      default:
        return null;
    }
  };

  getItem(userEvent) {
    const eventType = userEvent.type;

    switch (eventType) {
      case 'CreateEvent': {
        if (
          userEvent.payload.ref_type === 'branch' ||
          userEvent.payload.ref_type === 'tag'
        ) {
          return (
            <Text style={styles.linkBranchDescription}>
              {userEvent.payload.ref}
            </Text>
          );
        } else if (userEvent.payload.ref_type === 'repository') {
          return (
            <Text
              style={styles.linkDescription}
              onPress={() => this.navigateToRepository(userEvent)}
            >
              {userEvent.repo.name}
            </Text>
          );
        }

        return null;
      }
      case 'DeleteEvent':
        return (
          <Text style={styles.deletedLinkBranchDescription}>
            {userEvent.payload.ref}
          </Text>
        ); // can only be branch or tag
      case 'ForkEvent':
      case 'WatchEvent':
      case 'PublicEvent':
        return (
          <Text
            style={styles.linkDescription}
            onPress={() => this.navigateToRepository(userEvent)}
          >
            {userEvent.repo.name}
          </Text>
        );
      case 'GollumEvent':
        return (
          <Text>
            the{' '}
            <Text
              style={styles.linkDescription}
              onPress={() => this.navigateToRepository(userEvent)}
            >
              {userEvent.repo.name}
            </Text>{' '}
            wiki
          </Text>
        );
      case 'IssueCommentEvent':
      case 'IssuesEvent':
        return (
          <Text
            style={styles.linkDescription}
            onPress={() => this.navigateToIssue(userEvent)}
          >
            {userEvent.payload.issue.title}
          </Text>
        );
      case 'MemberEvent':
        return (
          <Text
            style={styles.linkDescription}
            onPress={() => this.navigateToProfile(userEvent)}
          >
            {userEvent.payload.member.login}
          </Text>
        );
      case 'PullRequestEvent':
      case 'PullRequestReviewEvent':
      case 'PullRequestReviewCommentEvent':
        return (
          <Text
            style={styles.linkDescription}
            onPress={() => this.navigateToIssue(userEvent)}
          >
            {userEvent.payload.pull_request.title}
          </Text>
        );
      case 'PushEvent':
        return (
          <Text style={styles.linkDescription}>
            {userEvent.payload.ref.replace('refs/heads/', '')}
          </Text>
        );
      case 'ReleaseEvent':
        return `${userEvent.payload.release.id}`;
      case 'RepositoryEvent':
        return (
          <Text
            style={styles.linkDescription}
            onPress={() => {
              if (userEvent.action !== 'deleted') {
                this.navigateToRepository(userEvent);
              }
            }}
          >
            {userEvent.repo.name}
          </Text>
        );
      default:
        return null;
    }
  }

  getConnector = userEvent => {
    const { locale } = this.props;
    const eventType = userEvent.type;

    switch (eventType) {
      case 'CreateEvent': {
        if (
          userEvent.payload.ref_type === 'branch' ||
          userEvent.payload.ref_type === 'tag'
        ) {
          return translate('auth.events.atConnector', locale);
        }

        return null;
      }
      case 'ForkEvent':
      case 'MemberEvent':
        return translate('auth.events.toConnector', locale);
      case 'DeleteEvent':
      case 'IssueCommentEvent':
      case 'IssuesEvent':
      case 'PushEvent':
      case 'PullRequestEvent':
      case 'PullRequestReviewCommentEvent':
        return translate('auth.events.atConnector', locale);
      case 'PublicEvent':
        return translate('auth.events.publicEvent.connector', locale);
      default:
        return null;
    }
  };

  getSecondItem(userEvent) {
    const eventType = userEvent.type;

    switch (eventType) {
      case 'CreateEvent': {
        if (
          userEvent.payload.ref_type === 'branch' ||
          userEvent.payload.ref_type === 'tag'
        ) {
          return (
            <Text
              style={styles.linkDescription}
              onPress={() => this.navigateToRepository(userEvent)}
            >
              {userEvent.repo.name}
            </Text>
          );
        }

        return null;
      }
      case 'DeleteEvent':
      case 'IssueCommentEvent':
      case 'IssuesEvent':
      case 'PushEvent':
      case 'PullRequestEvent':
      case 'MemberEvent':
      case 'PullRequestReviewCommentEvent':
        return (
          <Text
            style={styles.linkDescription}
            onPress={() => this.navigateToRepository(userEvent)}
          >
            {userEvent.repo.name}
          </Text>
        );
      case 'ForkEvent':
        return (
          <Text
            style={styles.linkDescription}
            onPress={() => this.navigateToRepository(userEvent, true)}
          >
            {userEvent.payload.forkee.full_name}
          </Text>
        );
      default:
        return null;
    }
  }

  getIcon = userEvent => {
    const eventType = userEvent.type;

    switch (eventType) {
      case 'CommitCommentEvent':
        return 'comment-discussion';
      case 'CreateEvent':
        return 'git-branch';
      case 'DeleteEvent':
        return 'trashcan';
      case 'ForkEvent':
        return 'repo-forked';
      case 'GollumEvent':
        return 'book';
      case 'IssueCommentEvent':
        return 'comment-discussion';
      case 'IssuesEvent':
        if (userEvent.action === 'reopened') {
          return 'issue-reopened';
        } else if (userEvent.action === 'closed') {
          return 'issue-closed';
        }

        return 'issue-opened';
      case 'MemberEvent':
        return 'person';
      case 'PublicEvent':
        return 'globe';
      case 'PullRequestEvent':
        return 'git-pull-request';
      case 'PullRequestReviewEvent':
        return 'git-pull-request';
      case 'PullRequestReviewCommentEvent':
        return 'comment-discussion';
      case 'PushEvent':
        return 'git-commit';
      case 'ReleaseEvent':
        return 'tag';
      case 'RepositoryEvent':
        return 'repo';
      case 'WatchEvent':
        return 'star';
      default:
        return null;
    }
  };

  formatPullRequestObject = issue => ({
    ...issue,
    url: issue.issue_url,
    pull_request: {
      diff_url: issue.diff_url,
      html_url: issue.html_url,
      patch_url: issue.patch_url,
      url: issue.url,
    },
  });

  navigateToRepository = (userEvent, isForkEvent) => {
    this.props.navigation.navigate('Repository', {
      repository: !isForkEvent
        ? {
            ...userEvent.repo,
            name: userEvent.repo.name.substring(
              userEvent.repo.name.indexOf('/') + 1
            ),
          }
        : userEvent.payload.forkee,
    });
  };

  navigateToIssue = userEvent => {
    this.props.navigation.navigate('Issue', {
      issue:
        userEvent.payload.issue ||
        this.formatPullRequestObject(userEvent.payload.pull_request),
      isPR: !!userEvent.payload.pull_request,
      locale: this.props.locale,
    });
  };

  navigateToProfile = (userEvent, isActor) => {
    this.props.navigation.navigate('Profile', {
      user: !isActor ? userEvent.payload.member : userEvent.actor,
    });
  };

  keyExtractor = item => {
    return item.id;
  };

  renderDescription(userEvent) {
    return (
      <Text style={styles.descriptionContainer}>
        <Text
          style={styles.linkDescription}
          onPress={() => this.navigateToProfile(userEvent, true)}
        >
          {userEvent.actor.login}{' '}
        </Text>
        <Text>{this.getAction(userEvent)} </Text>
        {this.getItem(userEvent)}
        {this.getAction(userEvent) && ' '}
        {this.getConnector(userEvent)}
        {this.getItem(userEvent) && ' '}
        {this.getSecondItem(userEvent)}
        {this.getItem(userEvent) && this.getConnector(userEvent) && ' '}
        <Text style={styles.date}>
          {moment(userEvent.created_at).fromNow()}
        </Text>
      </Text>
    );
  }

  render() {
    const { isPendingEvents, userEvents, locale, navigation } = this.props;
    const linebreaksPattern = /(\r\n|\n|\r)/gm;
    let content;

    if (isPendingEvents && !userEvents) {
      content = [...Array(15)].map((item, index) => {
        // eslint-disable-next-line react/no-array-index-key
        return <LoadingUserListItem key={index} />;
      });
    } else if (!isPendingEvents && userEvents && userEvents.length === 0) {
      content = (
        <View style={styles.textContainer}>
          <Text style={styles.noneTitle}>
            {translate('auth.events.welcomeMessage', locale)}
          </Text>
        </View>
      );
    } else {
      content = (
        <FlatList
          removeClippedSubviews={false}
          data={userEvents}
          onRefresh={this.getUserEvents}
          refreshing={isPendingEvents}
          keyExtractor={this.keyExtractor}
          renderItem={({ item }) => (
            <View>
              <UserListItem
                user={item.actor}
                title={this.renderDescription(item)}
                titleStyle={{ fontSize: normalize(12) }}
                navigation={navigation}
                onlyImageNavigate
                noBorderBottom={
                  item.type === 'IssueCommentEvent' ||
                  item.type === 'PullRequestReviewCommentEvent'
                }
                icon={this.getIcon(item)}
              />

              {(item.type === 'IssueCommentEvent' ||
                item.type === 'PullRequestReviewCommentEvent') && (
                <View style={styles.subtitleContainer}>
                  <Text numberOfLines={3} style={styles.subtitle}>
                    {emojifyText(
                      item.payload.comment.body.replace(linebreaksPattern, ' ')
                    )}
                  </Text>
                </View>
              )}
            </View>
          )}
          extraData={this.props.locale}
        />
      );
    }

    return <ViewContainer>{content}</ViewContainer>;
  }
}

export const EventsScreen = connect(mapStateToProps, mapDispatchToProps)(
  Events
);
<commit_msg>refactor: migrate events screen to styled-components (#687)<commit_after>/* eslint react/prop-types: 0 */
/* eslint-disable no-shadow */
import React, { Component } from 'react';
import styled from 'styled-components/native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Text, FlatList, View } from 'react-native';
import moment from 'moment/min/moment-with-locales.min';

import { LoadingUserListItem, UserListItem, ViewContainer } from 'components';
import { colors, fonts, normalize } from 'config';
import { emojifyText, translate } from 'utils';
import { getUserEvents } from 'auth';
import { getNotificationsCount } from 'notifications';

const mapStateToProps = state => ({
  user: state.auth.user,
  userEvents: state.auth.events,
  locale: state.auth.locale,
  isPendingEvents: state.auth.isPendingEvents,
  accessToken: state.auth.accessToken,
});

const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      getUserEvents,
      getNotificationsCount,
    },
    dispatch
  );

const DescriptionContainer = styled.Text`
  justify-content: center;
  flex: 1;
  margin-left: 10;
  color: ${colors.primaryDark};
  ${fonts.fontPrimaryLight};
`;

const LinkDescription = styled.Text`
  ${fonts.fontPrimarySemiBold};
`;

const LinkBranchDescription = styled.Text`
  ${fonts.fontCode};
`;

const DeletedLinkBranchDescription = styled.Text`
  color: ${colors.greyDarkest};
  ${fonts.fontCode};
`;

const Datestamp = styled.Text`
  color: ${colors.greyDark};
`;

const SubtitleContainer = styled.View`
  padding-horizontal: 15;
  padding-bottom: 10;
  border-bottom-color: ${colors.greyLight};
  border-bottom-width: 1;
`;

const Subtitle = styled.Text`
  color: ${colors.greyDark};
  font-size: ${normalize(11)};
  margin-top: 1;
  ${fonts.fontPrimarySemiBold};
  margin-left: 39;
`;

const TextContainer = styled.View`
  flex: 1;
  align-items: center;
  justify-content: center;
  margin-horizontal: 15;
`;

const NoneTitle = styled.Text`
  font-size: ${normalize(14)};
  text-align: center;
  ${fonts.fontPrimary};
`;

class Events extends Component {
  componentDidMount() {
    this.getUserEvents();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.user.login && !this.props.user.login) {
      this.getUserEvents(nextProps);
    }
  }

  getUserEvents = ({ user, accessToken } = this.props) => {
    this.props.getUserEvents(user.login);
    this.props.getNotificationsCount(accessToken);
  };

  getAction = userEvent => {
    const { locale } = this.props;
    const eventType = userEvent.type;
    /* eslint-disable prefer-const */
    let { action, ref_type: object } = userEvent.payload;

    switch (eventType) {
      case 'CommitCommentEvent':
        return translate('auth.events.commitCommentEvent', locale);
      case 'CreateEvent':
        return translate('auth.events.createEvent', locale, {
          object: translate(`auth.events.objects.${object}`, locale),
        });
      case 'DeleteEvent':
        return translate('auth.events.deleteEvent', locale, {
          object: translate(`auth.events.objects.${object}`, locale),
        });
      case 'ForkEvent':
        return translate('auth.events.actions.forked', locale);
      case 'GollumEvent':
        action = userEvent.payload.pages[0].action;

        return translate(`auth.events.actions.${action}`, locale);
      case 'IssueCommentEvent': {
        const eventsByActions = {
          created: 'issueCommentEvent',
          edited: 'issueEditedEvent',
          deleted: 'issueRemovedEvent',
        };
        const event = eventsByActions[action];

        if (!event) {
          return null;
        }

        if (action === 'created') {
          action = 'commented';
        }

        const issueData = {
          type: userEvent.payload.issue.pull_request
            ? translate('auth.events.types.pullRequest', locale)
            : translate('auth.events.types.issue', locale),
          action: translate(`auth.events.actions.${action}`, locale),
        };

        return translate(`auth.events.${event}`, locale, issueData);
      }
      case 'IssuesEvent':
        return translate('auth.events.issuesEvent', locale, {
          action: translate(`auth.events.actions.${action}`, locale),
        });
      case 'MemberEvent':
        return translate(`auth.events.actions.${action}`, locale);
      case 'PublicEvent':
        return translate('auth.events.publicEvent.action', locale);
      case 'PullRequestEvent':
        return translate('auth.events.pullRequestEvent', locale, {
          action: translate(`auth.events.actions.${action}`, locale),
        });
      case 'PullRequestReviewEvent':
        return translate('auth.events.pullRequestReviewEvent', locale, {
          payload: translate(`auth.events.actions.${action}`, locale),
        });
      case 'PullRequestReviewCommentEvent': {
        if (action === 'created') {
          return translate(
            'auth.events.pullRequestReviewCommentEvent',
            locale,
            {
              action: translate('auth.events.actions.commented', locale),
            }
          );
        } else if (action === 'edited') {
          return translate('auth.events.pullRequestReviewEditedEvent', locale, {
            action: translate(`auth.events.actions.${action}`, locale),
          });
        } else if (action === 'deleted') {
          return translate(
            'auth.events.pullRequestReviewDeletedEvent',
            locale,
            {
              action: translate(`auth.events.actions.${action}`, locale),
            }
          );
        }

        return null;
      }
      case 'PushEvent':
        return translate('auth.events.actions.pushedTo', locale);
      case 'ReleaseEvent':
        return translate('auth.events.releaseEvent', locale, {
          action: translate(`auth.events.actions.${action}`, locale),
        });
      case 'RepositoryEvent':
        return translate(`auth.events.actions.${action}`, locale);
      case 'WatchEvent':
        return translate('auth.events.actions.starred', locale);
      default:
        return null;
    }
  };

  getItem(userEvent) {
    const eventType = userEvent.type;

    switch (eventType) {
      case 'CreateEvent': {
        if (
          userEvent.payload.ref_type === 'branch' ||
          userEvent.payload.ref_type === 'tag'
        ) {
          return (
            <LinkBranchDescription>
              {userEvent.payload.ref}
            </LinkBranchDescription>
          );
        } else if (userEvent.payload.ref_type === 'repository') {
          return (
            <LinkDescription
              onPress={() => this.navigateToRepository(userEvent)}
            >
              {userEvent.repo.name}
            </LinkDescription>
          );
        }

        return null;
      }
      case 'DeleteEvent':
        return (
          <DeletedLinkBranchDescription>
            {userEvent.payload.ref}
          </DeletedLinkBranchDescription>
        ); // can only be branch or tag
      case 'ForkEvent':
      case 'WatchEvent':
      case 'PublicEvent':
        return (
          <LinkDescription onPress={() => this.navigateToRepository(userEvent)}>
            {userEvent.repo.name}
          </LinkDescription>
        );
      case 'GollumEvent':
        return (
          <Text>
            the{' '}
            <LinkDescription
              onPress={() => this.navigateToRepository(userEvent)}
            >
              {userEvent.repo.name}
            </LinkDescription>{' '}
            wiki
          </Text>
        );
      case 'IssueCommentEvent':
      case 'IssuesEvent':
        return (
          <LinkDescription onPress={() => this.navigateToIssue(userEvent)}>
            {userEvent.payload.issue.title}
          </LinkDescription>
        );
      case 'MemberEvent':
        return (
          <LinkDescription onPress={() => this.navigateToProfile(userEvent)}>
            {userEvent.payload.member.login}
          </LinkDescription>
        );
      case 'PullRequestEvent':
      case 'PullRequestReviewEvent':
      case 'PullRequestReviewCommentEvent':
        return (
          <LinkDescription onPress={() => this.navigateToIssue(userEvent)}>
            {userEvent.payload.pull_request.title}
          </LinkDescription>
        );
      case 'PushEvent':
        return (
          <LinkBranchDescription>
            {userEvent.payload.ref.replace('refs/heads/', '')}
          </LinkBranchDescription>
        );
      case 'ReleaseEvent':
        return `${userEvent.payload.release.id}`;
      case 'RepositoryEvent':
        return (
          <LinkDescription
            onPress={() => {
              if (userEvent.action !== 'deleted') {
                this.navigateToRepository(userEvent);
              }
            }}
          >
            {userEvent.repo.name}
          </LinkDescription>
        );
      default:
        return null;
    }
  }

  getConnector = userEvent => {
    const { locale } = this.props;
    const eventType = userEvent.type;

    switch (eventType) {
      case 'CreateEvent': {
        if (
          userEvent.payload.ref_type === 'branch' ||
          userEvent.payload.ref_type === 'tag'
        ) {
          return translate('auth.events.atConnector', locale);
        }

        return null;
      }
      case 'ForkEvent':
      case 'MemberEvent':
        return translate('auth.events.toConnector', locale);
      case 'DeleteEvent':
      case 'IssueCommentEvent':
      case 'IssuesEvent':
      case 'PushEvent':
      case 'PullRequestEvent':
      case 'PullRequestReviewCommentEvent':
        return translate('auth.events.atConnector', locale);
      case 'PublicEvent':
        return translate('auth.events.publicEvent.connector', locale);
      default:
        return null;
    }
  };

  getSecondItem(userEvent) {
    const eventType = userEvent.type;

    switch (eventType) {
      case 'CreateEvent': {
        if (
          userEvent.payload.ref_type === 'branch' ||
          userEvent.payload.ref_type === 'tag'
        ) {
          return (
            <LinkDescription
              onPress={() => this.navigateToRepository(userEvent)}
            >
              {userEvent.repo.name}
            </LinkDescription>
          );
        }

        return null;
      }
      case 'DeleteEvent':
      case 'IssueCommentEvent':
      case 'IssuesEvent':
      case 'PushEvent':
      case 'PullRequestEvent':
      case 'MemberEvent':
      case 'PullRequestReviewCommentEvent':
        return (
          <LinkDescription onPress={() => this.navigateToRepository(userEvent)}>
            {userEvent.repo.name}
          </LinkDescription>
        );
      case 'ForkEvent':
        return (
          <LinkDescription
            onPress={() => this.navigateToRepository(userEvent, true)}
          >
            {userEvent.payload.forkee.full_name}
          </LinkDescription>
        );
      default:
        return null;
    }
  }

  getIcon = userEvent => {
    const eventType = userEvent.type;

    switch (eventType) {
      case 'CommitCommentEvent':
        return 'comment-discussion';
      case 'CreateEvent':
        return 'git-branch';
      case 'DeleteEvent':
        return 'trashcan';
      case 'ForkEvent':
        return 'repo-forked';
      case 'GollumEvent':
        return 'book';
      case 'IssueCommentEvent':
        return 'comment-discussion';
      case 'IssuesEvent':
        if (userEvent.action === 'reopened') {
          return 'issue-reopened';
        } else if (userEvent.action === 'closed') {
          return 'issue-closed';
        }

        return 'issue-opened';
      case 'MemberEvent':
        return 'person';
      case 'PublicEvent':
        return 'globe';
      case 'PullRequestEvent':
        return 'git-pull-request';
      case 'PullRequestReviewEvent':
        return 'git-pull-request';
      case 'PullRequestReviewCommentEvent':
        return 'comment-discussion';
      case 'PushEvent':
        return 'git-commit';
      case 'ReleaseEvent':
        return 'tag';
      case 'RepositoryEvent':
        return 'repo';
      case 'WatchEvent':
        return 'star';
      default:
        return null;
    }
  };

  formatPullRequestObject = issue => ({
    ...issue,
    url: issue.issue_url,
    pull_request: {
      diff_url: issue.diff_url,
      html_url: issue.html_url,
      patch_url: issue.patch_url,
      url: issue.url,
    },
  });

  navigateToRepository = (userEvent, isForkEvent) => {
    this.props.navigation.navigate('Repository', {
      repository: !isForkEvent
        ? {
            ...userEvent.repo,
            name: userEvent.repo.name.substring(
              userEvent.repo.name.indexOf('/') + 1
            ),
          }
        : userEvent.payload.forkee,
    });
  };

  navigateToIssue = userEvent => {
    this.props.navigation.navigate('Issue', {
      issue:
        userEvent.payload.issue ||
        this.formatPullRequestObject(userEvent.payload.pull_request),
      isPR: !!userEvent.payload.pull_request,
      locale: this.props.locale,
    });
  };

  navigateToProfile = (userEvent, isActor) => {
    this.props.navigation.navigate('Profile', {
      user: !isActor ? userEvent.payload.member : userEvent.actor,
    });
  };

  keyExtractor = item => {
    return item.id;
  };

  renderDescription(userEvent) {
    return (
      <DescriptionContainer>
        <LinkDescription
          onPress={() => this.navigateToProfile(userEvent, true)}
        >
          {userEvent.actor.login}{' '}
        </LinkDescription>
        <Text>{this.getAction(userEvent)} </Text>
        {this.getItem(userEvent)}
        {this.getAction(userEvent) && ' '}
        {this.getConnector(userEvent)}
        {this.getItem(userEvent) && ' '}
        {this.getSecondItem(userEvent)}
        {this.getItem(userEvent) && this.getConnector(userEvent) && ' '}
        <Datestamp>{moment(userEvent.created_at).fromNow()}</Datestamp>
      </DescriptionContainer>
    );
  }

  render() {
    const { isPendingEvents, userEvents, locale, navigation } = this.props;
    const linebreaksPattern = /(\r\n|\n|\r)/gm;
    let content;

    if (isPendingEvents && !userEvents) {
      content = [...Array(15)].map((item, index) => {
        // eslint-disable-next-line react/no-array-index-key
        return <LoadingUserListItem key={index} />;
      });
    } else if (!isPendingEvents && userEvents && userEvents.length === 0) {
      content = (
        <TextContainer>
          <NoneTitle>
            {translate('auth.events.welcomeMessage', locale)}
          </NoneTitle>
        </TextContainer>
      );
    } else {
      content = (
        <FlatList
          removeClippedSubviews={false}
          data={userEvents}
          onRefresh={this.getUserEvents}
          refreshing={isPendingEvents}
          keyExtractor={this.keyExtractor}
          renderItem={({ item }) => (
            <View>
              <UserListItem
                user={item.actor}
                title={this.renderDescription(item)}
                titleStyle={{ fontSize: normalize(12) }}
                navigation={navigation}
                onlyImageNavigate
                noBorderBottom={
                  item.type === 'IssueCommentEvent' ||
                  item.type === 'PullRequestReviewCommentEvent'
                }
                icon={this.getIcon(item)}
              />

              {(item.type === 'IssueCommentEvent' ||
                item.type === 'PullRequestReviewCommentEvent') && (
                <SubtitleContainer>
                  <Subtitle numberOfLines={3}>
                    {emojifyText(
                      item.payload.comment.body.replace(linebreaksPattern, ' ')
                    )}
                  </Subtitle>
                </SubtitleContainer>
              )}
            </View>
          )}
          extraData={this.props.locale}
        />
      );
    }

    return <ViewContainer>{content}</ViewContainer>;
  }
}

export const EventsScreen = connect(mapStateToProps, mapDispatchToProps)(
  Events
);
<|endoftext|>


<commit_before>/* ========================================
 * CORS Planner - jQuery Slot
 *
 * jQuery plugin for Module Slot Interactions
 *
 * Author: Wang Zhuochun
 * Last Edit: 03/Dec/2012 10:14 AM
 * ========================================
 * <License>
 * ======================================== */

define(function(require, exports) {

    "use strict";
    /*jshint jquery:true, laxcomma:true, browser:true, maxerr:50*/

    (function($) {

        var _project = "planner_"
          , _pluginName = "slot"
        // elem pre-cache
          , $grid = $("#tt-grid")
          , $basket = $("#basket-scroll")
        // Plugin constructor
          , Plugin = function(element, options) {
            this.$elem = $(element);
            this.init(options);
          };

        Plugin.prototype = {
            constructor: Plugin

            , init: function(opt) {
                // opt info
                this.code = opt.code;
                this.type = opt.type;
                this.slot = opt.slot;
                this.data = opt.module;
                // css id
                this.id = this.$elem.attr("id");
                // section lecture id
                this.sid = this.id.substr(0, this.id.lastIndexOf("-"));
                // elem ui
                this.updateElem();
                // attach events
                this.attachEvents();
                // draggable
                this.attachDragDrop(opt.droppable);
            }

            , get: function(key) { return this.data.get(key); }

            , updateElem: function() {
                if (this.code.length > 6 && this.$elem.data("span") < 3) {
                    this.$elem.addClass("small");
                }
            }

            , attachEvents: function(item, fun) {
                var self = this;

                this.$elem.on("mouseenter", function() {
                    $grid.find(".slot[id^=" + self.code + "-]").addClass("hover");
                    $basket.find(".module[id=" + self.code + "]").addClass("hover");
                });

                this.$elem.on("mouseleave", function() {
                    $grid.find(".slot[id^=" + self.code + "-]").removeClass("hover");
                    $basket.find(".module[id=" + self.code + "]").removeClass("hover");
                });
            }

            , attachDragDrop: function(droppable) {
                var self = this;
                // default drag/drop opts
                this.dragOpts = {
                    helper: "clone"
                  , opacity: 0.3
                  , cursorAt: {top:20,left:20}
                  , revert: "invalid"
                  , revertDuration: 200
                  , zIndex : 1000
                  , start: $.proxy(self.dragStart, self)
                  , stop: $.proxy(self.dragStop, self)
                };
                this.dropOpts = {
                    activeClass: "highlight"
                  , hoverClass: "hover"
                  , tolerance: "pointer"
                  , over: $.proxy(self.dropOver, self)
                  , out: $.proxy(self.dropOut, self)
                  , drop: $.proxy(self.dropEvent, self)
                };

                if (droppable) {
                    this.$elem.droppable(this.dropOpts);
                } else {
                    this.$elem.draggable(this.dragOpts);
                }
            }

            , dragStart: function() {
                $.publish("grid:module:droppable",
                    [this.slot, this.type, this.data]);
            }

            , dragStop: function() {
                // remove temp drop slot
                $grid.find(".ui-droppable").remove();
                // clear rows
                $.publish("grid:rows:clearEmpty");
            }

            , dropEvent: function(e, ui) {
                // remove all slots of this module + type
                $grid.find(".slot[id^=" + this.code + "-" + this.type + "-]").remove();
                // allocate the new slots
                $.publish("grid:module:allocate", [this.slot, this.type, this.data]);
                // clear rows
                setTimeout(function() {
                    $.publish("grid:rows:clearEmpty");
                }, 10);
            }

            , dropOver: function() {
                $grid.find(".slot[id^=" + this.sid + "-]").addClass("hover");
            }

            , dropOut: function() {
                $grid.find(".slot[id^=" + this.sid + "-]").removeClass("hover");
            }
        };

        /* PLUGIN DEFINITION
         * ======================================== */
        $.fn.slot = function(options) {
            return this.each(function () {
                if (!$.data(this, _project + _pluginName)) {
                    $.data(this, _project + _pluginName, new Plugin(this, options));
                }
            });
        };

    }(jQuery));

});
<commit_msg>fix bug at mouse lose focus on drop slot<commit_after>/* ========================================
 * CORS Planner - jQuery Slot
 *
 * jQuery plugin for Module Slot Interactions
 *
 * Author: Wang Zhuochun
 * Last Edit: 03/Dec/2012 10:14 AM
 * ========================================
 * <License>
 * ======================================== */

define(function(require, exports) {

    "use strict";
    /*jshint jquery:true, laxcomma:true, browser:true, maxerr:50*/

    (function($) {

        var _project = "planner_"
          , _pluginName = "slot"
        // elem pre-cache
          , $grid = $("#tt-grid")
          , $basket = $("#basket-scroll")
        // Plugin constructor
          , Plugin = function(element, options) {
            this.$elem = $(element);
            this.init(options);
          };

        Plugin.prototype = {
            constructor: Plugin

            , init: function(opt) {
                // opt info
                this.code = opt.code;
                this.type = opt.type;
                this.slot = opt.slot;
                this.data = opt.module;
                // css id
                this.id = this.$elem.attr("id");
                // section lecture id
                this.sid = this.id.substr(0, this.id.lastIndexOf("-"));
                // elem ui
                this.updateElem();
                // attach events
                this.attachEvents(opt.droppable);
                // draggable
                this.attachDragDrop(opt.droppable);
            }

            , get: function(key) { return this.data.get(key); }

            , updateElem: function() {
                if (this.code.length > 6 && this.$elem.data("span") < 3) {
                    this.$elem.addClass("small");
                }
            }

            , attachEvents: function(droppable) {
                if (droppable) { return ; }

                var self = this;

                this.$elem.on("mouseenter", function() {
                    $grid.find(".slot[id^=" + self.code + "-]").addClass("hover");
                    $basket.find(".module[id=" + self.code + "]").addClass("hover");
                });

                this.$elem.on("mouseleave", function() {
                    $grid.find(".slot[id^=" + self.code + "-]").removeClass("hover");
                    $basket.find(".module[id=" + self.code + "]").removeClass("hover");
                });
            }

            , attachDragDrop: function(droppable) {
                var self = this;
                // default drag/drop opts
                this.dragOpts = {
                    helper: "clone"
                  , opacity: 0.3
                  , cursorAt: {top:20,left:20}
                  , revert: "invalid"
                  , revertDuration: 200
                  , zIndex : 1000
                  , start: $.proxy(self.dragStart, self)
                  , stop: $.proxy(self.dragStop, self)
                };
                this.dropOpts = {
                    activeClass: "highlight"
                  , hoverClass: "hover"
                  , tolerance: "pointer"
                  , over: $.proxy(self.dropOver, self)
                  , out: $.proxy(self.dropOut, self)
                  , drop: $.proxy(self.dropEvent, self)
                };

                if (droppable) {
                    this.$elem.droppable(this.dropOpts);
                } else {
                    this.$elem.draggable(this.dragOpts);
                }
            }

            , dragStart: function() {
                $.publish("grid:module:droppable",
                    [this.slot, this.type, this.data]);
            }

            , dragStop: function() {
                // remove temp drop slot
                $grid.find(".ui-droppable").remove();
                // clear rows
                $.publish("grid:rows:clearEmpty");
            }

            , dropEvent: function(e, ui) {
                // fix minor bug when mouse is not over the slot after drop
                // the module in basket is still on hover state
                this.$elem.trigger("mouseleave");
                // remove all slots of this module + type
                $grid.find(".slot[id^=" + this.code + "-" + this.type + "-]").remove();
                // allocate the new slots
                $.publish("grid:module:allocate", [this.slot, this.type, this.data]);
                // clear rows
                setTimeout(function() {
                    $.publish("grid:rows:clearEmpty");
                }, 10);
            }

            , dropOver: function() {
                $grid.find(".slot[id^=" + this.sid + "-]").addClass("hover");
            }

            , dropOut: function() {
                $grid.find(".slot[id^=" + this.sid + "-]").removeClass("hover");
            }
        };

        /* PLUGIN DEFINITION
         * ======================================== */
        $.fn.slot = function(options) {
            return this.each(function () {
                if (!$.data(this, _project + _pluginName)) {
                    $.data(this, _project + _pluginName, new Plugin(this, options));
                }
            });
        };

    }(jQuery));

});
<|endoftext|>


<commit_before>function editRelated (collectionId, data, templateData, field, idField) {
  var list = templateData[field];
  if (idField === 'article') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'articles'};
  } else if (idField === 'bulletin') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'bulletins'};
  } else if (idField === 'dataset') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'datasets'};
  } else if (idField === 'document') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'documents'};
  } else if (idField === 'methodology') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'methodologies'};
  } else {
    var dataTemplate = {list: list, idField: idField};
  }
  var html = templates.editorRelated(dataTemplate);
  $('#'+ idField).replaceWith(html);

  initialiseRelated(collectionId, data, templateData, field, idField);
}

function refreshRelated(collectionId, data, templateData, field, idField) {
  var list = templateData[field];
  if (idField === 'article') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'articles'};
  } else if (idField === 'bulletin') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'bulletins'};
  } else if (idField === 'dataset') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'datasets'};
  } else if (idField === 'document') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'documents'};
  } else if (idField === 'methodology') {
    var dataTemplate = {list: list, idField: idField, idPlural: 'methodologies'};
  } else {
    var dataTemplate = {list: list, idField: idField};
  }
  var html = templates.editorRelated(dataTemplate);
  $('#sortable-'+ idField).replaceWith($(html).find('#sortable-'+ idField));
  initialiseRelated(collectionId, data, templateData, field, idField);
}

function initialiseRelated(collectionId, data, templateData, field, idField) {
  // Load
  if (!data[field] || data[field].length === 0) {
    editRelated['lastIndex' + field] = 0;
  } else {
    $(data[field]).each(function (index, value) {
      editRelated['lastIndex' + field] = index + 1;

      // Delete
      $('#' + idField + '-delete_' + index).click(function () {
        var result = confirm("Are you sure you want to delete this link?");
        if (result === true) {
          var position = $(".workspace-edit").scrollTop();
          Florence.globalVars.pagePos = position;
          $(this).parent().remove();
          data[field].splice(index, 1);
          templateData[field].splice(index, 1);
          postContent(collectionId, data.uri, JSON.stringify(data),
            success = function (response) {
              Florence.Editor.isDirty = false;
              refreshPreview(data.uri);
              refreshRelated(collectionId, data, templateData, field, idField)
            },
            error = function (response) {
              if (response.status === 400) {
                alert("Cannot edit this file. It is already part of another collection.");
              }
              else if (response.status === 401) {
                alert("You are not authorised to update content.");
              }
              else {
                handleApiError(response);
              }
            }
          );
        }
      });
    });
  }

  //Add
  $('#add-' + idField).off().one('click', function () {
    var position = $(".workspace-edit").scrollTop();
    Florence.globalVars.pagePos = position;
    var iframeEvent = document.getElementById('iframe').contentWindow;
    iframeEvent.removeEventListener('click', Florence.Handler, true);
    createWorkspace(data.uri, collectionId, '', true);

    $('#sortable-' + idField).append(
      '
' +
      '  <textarea id="' + idField + '-uri_' + editRelated['lastIndex' + field] + '" placeholder="Go to the related data and click Get"></textarea>' +
      '  <button class="btn-page-get" id="' + idField + '-get_' + editRelated['lastIndex' + field] + '">Get</button>' +
      '  <button class="btn-page-cancel" id="' + idField + '-cancel_' + editRelated['lastIndex' + field] + '">Cancel</button>' +
      '
').trigger('create');

    $('#' + idField + '-cancel_' + editRelated['lastIndex' + field]).one('click', function () {
      createWorkspace(data.uri, collectionId, 'edit');
    });

    $('#' + idField + '-get_' + editRelated['lastIndex' + field]).one('click', function () {
      var pastedUrl = $('#' + idField + '-uri_'+editRelated['lastIndex' + field]).val();
      if (pastedUrl) {
        checkPathParsed(pastedUrl);
        var dataUrlData = pastedUrl + "/data";
      } else {
        var dataUrl = getPathNameTrimLast();
        checkPathParsed(dataUrl);
        var dataUrlData = dataUrl + "/data";
      }

      $.ajax({
        url: dataUrlData,
        dataType: 'json',
        crossDomain: true,
        success: function (result) {
          if ((field === 'relatedBulletins' || field === 'statsBulletins') && result.type === 'bulletin') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if (field === 'relatedArticles' && result.type === 'article') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedDocuments') && (result.type === 'article' || result.type === 'bulletin' || result.type === 'compendium_landing_page')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedDatasets' || field === 'datasets') && (result.type === 'dataset' || result.type === 'reference_tables')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'items') && (result.type === 'timeseries')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedData') && (result.type === 'timeseries' || result.type === 'dataset' || result.type === 'reference_tables')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if (field === 'relatedMethodology' && result.type === 'static_methodology') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else {
            alert("This is not a valid document");
            return;
          }

          data[field].push({uri: result.uri});
          saveRelated(collectionId, data.uri, data, field, idField);

        },
        error: function () {
          console.log('No page data returned');
        }
      });
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable();
  }
  sortable();
}
<commit_msg>Refactored to use return value of checkPathParsed function.<commit_after>function editRelated (collectionId, data, templateData, field, idField) {
  var list = templateData[field];
  var dataTemplate = createRelatedTemplate(idField, list);
  var html = templates.editorRelated(dataTemplate);
  $('#'+ idField).replaceWith(html);
  initialiseRelated(collectionId, data, templateData, field, idField);
}

function refreshRelated(collectionId, data, templateData, field, idField) {
  var list = templateData[field];
  var dataTemplate = createRelatedTemplate(idField, list);
  var html = templates.editorRelated(dataTemplate);
  $('#sortable-'+ idField).replaceWith($(html).find('#sortable-'+ idField));
  initialiseRelated(collectionId, data, templateData, field, idField);
}

function createRelatedTemplate(idField, list) {
  var dataTemplate;
  if (idField === 'article') {
    dataTemplate = {list: list, idField: idField, idPlural: 'articles'};
  } else if (idField === 'bulletin') {
    dataTemplate = {list: list, idField: idField, idPlural: 'bulletins'};
  } else if (idField === 'dataset') {
    dataTemplate = {list: list, idField: idField, idPlural: 'datasets'};
  } else if (idField === 'document') {
    dataTemplate = {list: list, idField: idField, idPlural: 'documents'};
  } else if (idField === 'methodology') {
    dataTemplate = {list: list, idField: idField, idPlural: 'methodologies'};
  } else {
    dataTemplate = {list: list, idField: idField};
  }
  return dataTemplate;
}

function initialiseRelated(collectionId, data, templateData, field, idField) {
  // Load
  if (!data[field] || data[field].length === 0) {
    editRelated['lastIndex' + field] = 0;
  } else {
    $(data[field]).each(function (index, value) {
      editRelated['lastIndex' + field] = index + 1;

      // Delete
      $('#' + idField + '-delete_' + index).click(function () {
        var result = confirm("Are you sure you want to delete this link?");
        if (result === true) {
          var position = $(".workspace-edit").scrollTop();
          Florence.globalVars.pagePos = position;
          $(this).parent().remove();
          data[field].splice(index, 1);
          templateData[field].splice(index, 1);
          postContent(collectionId, data.uri, JSON.stringify(data),
            success = function (response) {
              Florence.Editor.isDirty = false;
              refreshPreview(data.uri);
              refreshRelated(collectionId, data, templateData, field, idField)
            },
            error = function (response) {
              if (response.status === 400) {
                alert("Cannot edit this file. It is already part of another collection.");
              }
              else if (response.status === 401) {
                alert("You are not authorised to update content.");
              }
              else {
                handleApiError(response);
              }
            }
          );
        }
      });
    });
  }

  //Add
  $('#add-' + idField).off().one('click', function () {
    var position = $(".workspace-edit").scrollTop();
    Florence.globalVars.pagePos = position;
    var iframeEvent = document.getElementById('iframe').contentWindow;
    iframeEvent.removeEventListener('click', Florence.Handler, true);
    createWorkspace(data.uri, collectionId, '', true);

    $('#sortable-' + idField).append(
      '
' +
      '  <textarea id="' + idField + '-uri_' + editRelated['lastIndex' + field] + '" placeholder="Go to the related data and click Get"></textarea>' +
      '  <button class="btn-page-get" id="' + idField + '-get_' + editRelated['lastIndex' + field] + '">Get</button>' +
      '  <button class="btn-page-cancel" id="' + idField + '-cancel_' + editRelated['lastIndex' + field] + '">Cancel</button>' +
      '
').trigger('create');

    $('#' + idField + '-cancel_' + editRelated['lastIndex' + field]).one('click', function () {
      createWorkspace(data.uri, collectionId, 'edit');
    });

    $('#' + idField + '-get_' + editRelated['lastIndex' + field]).one('click', function () {
      var baseUrl = $('#' + idField + '-uri_'+editRelated['lastIndex' + field]).val();
      if (!baseUrl) {
        baseUrl = getPathNameTrimLast();
      }
      baseUrl = checkPathParsed(baseUrl);
      var dataUrlData = baseUrl + "/data";

      $.ajax({
        url: dataUrlData,
        dataType: 'json',
        crossDomain: true,
        success: function (result) {
          if ((field === 'relatedBulletins' || field === 'statsBulletins') && result.type === 'bulletin') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if (field === 'relatedArticles' && result.type === 'article') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedDocuments') && (result.type === 'article' || result.type === 'bulletin' || result.type === 'compendium_landing_page')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedDatasets' || field === 'datasets') && (result.type === 'dataset' || result.type === 'reference_tables')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'items') && (result.type === 'timeseries')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if ((field === 'relatedData') && (result.type === 'timeseries' || result.type === 'dataset' || result.type === 'reference_tables')) {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else if (field === 'relatedMethodology' && result.type === 'static_methodology') {
            if (!data[field]) {
              data[field] = [];
            }
          }

          else {
            alert("This is not a valid document");
            return;
          }

          data[field].push({uri: baseUrl});
          saveRelated(collectionId, data.uri, data, field, idField);

        },
        error: function () {
          console.log('No page data returned');
        }
      });
    });
  });

  function sortable() {
    $('#sortable-' + idField).sortable();
  }
  sortable();
}
<|endoftext|>


<commit_before>/**
 * Created by ArunaTebel on 12/12/2015.
 */
var v = 1.1;
this.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(v).then(function (cache) {
            return cache.addAll([
                '/app/view1/view1.html',
                '/app/view2/view2.html'
            ]);
        })
    );
});

this.addEventListener('fetch', function (event) {
    console.log("hfhfhf");
    var response;
    event.respondWith(caches.match(event.request).catch(function () {
        return fetch(event.request);
    }).then(function (r) {
        response = r;
        caches.open(v).then(function (cache) {
            cache.put(event.request, response);
        });
        return response.clone();
    }).catch(function () {
        console.log("asdasdasdasdasda");
        return caches.match('/app/view1/fallback.html');
    }));
});

this.addEventListener('activate', function (event) {
    var cacheWhitelist = [v];
    console.log("activ");
    event.waitUntil(
        caches.keys().then(function (keyList) {
            return Promise.all(keyList.map(function (key) {
                if (cacheWhitelist.indexOf(key) === -1) {
                    return caches.delete(keyList[key]);
                }
            }));
        })
    );
});
<commit_msg>Remove old cache<commit_after>/**
 * Created by ArunaTebel on 12/12/2015.
 */
var v = 1.1;
this.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(v).then(function (cache) {
            return cache.addAll([
                '/app/view1/view1.html',
                '/app/view2/view2.html'
            ]);
        })
    );
});

this.addEventListener('fetch', function (event) {
    console.log("hfhfhf");
    var response;
    event.respondWith(caches.match(event.request).catch(function () {
        return fetch(event.request);
    }).then(function (r) {
        response = r;
        caches.open(v).then(function (cache) {
            //cache.put(event.request, response);
        });
        return response.clone();
    }).catch(function () {
        console.log("asdasdasdasdasda");
        return caches.match('/app/view1/fallback.html');
    }));
});

this.addEventListener('activate', function (event) {
    var cacheWhitelist = [v];
    console.log("activ");
    event.waitUntil(
        caches.keys().then(function (keyList) {
            return Promise.all(keyList.map(function (key) {
                if (cacheWhitelist.indexOf(key) === -1) {
                    return caches.delete(keyList[key]);
                }
            }));
        })
    );
});
<|endoftext|>


<commit_before>var _ = require('lodash');
var async = require('async');
var shortid = require('shortid');
var assert = require('assert');

require('dash-assert');

describe('Application', function() {
  var dynamo = require('./dynamo-local');
  var self;

  beforeEach(function() {
    self = this;
    this.appData = {
      appId: shortid.generate(),
      orgId: shortid.generate(),
      ownerId: shortid.generate(),
      name: 'app-name-' + shortid.generate(),
      trafficRules: {
        prod: [
          {version: 'v1', rule: 'random:0.5'},
          {version: 'v2', rule: 'random:0.5'}
        ],
        test: [
          {version: 'v3', rule: '*'}
        ]
      }
    };
  });

  it('create and retrieve application', function(done) {
    var domainName = shortid.generate() + '.com';
    var subDomain = 'www';

    _.extend(this.appData, {
      domainName: domainName,
      subDomain: subDomain
    });

    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, function(err, app) {
          if (err) return cb(err);

          assert.isMatch(app, self.appData);
          cb();
        });
      },
      function(cb) {
        dynamo.getAppByDomainName(domainName, subDomain, function(err, app) {
          if (err) return cb(err);
          debugger;
          assert.isMatch(app, self.appData);
          cb();
        });
      }
    ], done);
  });

  it('create application with existing domainName', function(done) {
    _.extend(this.appData, {
      domainName: shortid.generate() + '.com',
      subDomain: 'www'
    });

    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, cb);
      },
      function(cb) {
        self.appData.appId = shortid.generate();
        self.appData.name = 'app-name-' + shortid.generate();

        dynamo.createApplication(self.appData, function(err) {
          assert.equal(err.code, 'domainNameTaken');
          cb();
        });
      },
      function(cb) {
        self.appData.subDomain = 'www2';

        // Create another app with same domainName but different subDomain
        dynamo.createApplication(self.appData, cb);
      }
    ], done);
  });

  it('get application by name', function(done) {
    self = this;

    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, cb);
      },
      function(cb) {
        dynamo.getApplicationByName(self.appData.name, function(err, app) {
          if (err) return cb(err);

          assert.isMatch(app, self.appData);
          cb();
        });
      }
    ], done);
  });

  it('does not allow duplicate app names', function(done) {
    self = this;
    async.series([
      function(cb) {
        dynamo.models.AppName.create({name: self.appData.name, appId: shortid.generate()}, cb);
      },
      function(cb) {
        dynamo.createApplication(self.appData, function(err) {
          assert.ok(err);
          assert.equal(err.code, 'appNameExists');
          cb();
        });
      }
    ], done);
  });

  it('get appName', function(done) {
    var appName = {name: shortid.generate(), appId: shortid.generate()};
    async.series([
      function(cb) {
        dynamo.models.AppName.create(appName, cb);
      },
      function(cb) {
        dynamo.getAppName(appName.name, function(err, name) {
          assert.deepEqual(name, appName);
          cb();
        });
      }
    ], done);
  });

  it('deletes application', function(done) {
    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, cb);
      },
      function(cb) {
        // Create a version
        dynamo.createVersion({
          appId: self.appData.appId,
          versionId: shortid.generate(),
          name: 'v1',
          userId: self.appData.ownerId,
          status: 'complete',
          manifest: {}
        }, cb);
      },
      function(cb) {
        dynamo.deleteApplication(self.appData.appId, cb);
      },
      function(cb) {
        dynamo.getApplication(self.appData.appId, function(err, app) {
          if (err) return cb(err);
          assert.isNull(app);
          cb();
        });
      }
    ], done);
  });

  it('update application', function(done) {
    var appData = _.extend({}, this.appData, {
      appId: shortid.generate()
    });

    // Update the name and domains
    var updatedData = _.extend({}, appData, {
      name: shortid.generate() + '-new-name',
    });

    // First create an application
    async.series([
      function(cb) {
        dynamo.createApplication(appData, cb);
      },
      function(cb) {
        dynamo.updateApplication(updatedData, cb);
      },
      function(cb) {
        dynamo.getApplication(appData.appId, function(err, app) {
          if (err) return cb(err);

          assert.equal(app.name, updatedData.name);
          cb();
        });
      }
    ], done);
  });

  it('transfer application', function(done) {
    var newOrgId = shortid.generate();

    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, cb);
      },
      function(cb) {
        dynamo.transferApplication(self.appData.appId, newOrgId, cb);
      },
      function(cb) {
        dynamo.getApplication(self.appData.appId, function(err, app) {
          if (err) return cb(err);
          assert.equal(app.orgId, newOrgId);
          cb();
        });
      }
    ], done);
  });

  it('list user applications', function(done) {
    var appIds = _.times(3, function() {
      return shortid.generate();
    });
    var userId = shortid.generate();

    async.series([
      function(cb) {
        async.each(appIds, function(appId, cb1) {
          dynamo.createApplication(_.extend({}, self.appData, {
            appId: appId,
            name: 'app-' + appId,
            ownerId: userId
          }), cb1);
        }, cb);
      },
      function(cb) {
        dynamo.userApplications(userId, function(err, userAppIds) {
          assert.equal(userAppIds.length, 3);
          assert.noDifferences(appIds, userAppIds);
          cb();
        });
      }
    ], done);
  });

  it('updates traffic rules', function(done) {
    var appData = {
      appId: shortid.generate(),
      orgId: shortid.generate(),
      ownerId: shortid.generate(),
      name: 'app-name-' + shortid.generate(),
      trafficRules: {
        test: [
          {version: 'v3', rule: '*'}
        ]
      }
    };

    var updatedRules = [
      {version: 'v1', rule: 'random:0.5'},
      {version: 'v10', rule: 'random:0.5'}
    ];

    async.series([
      function(cb) {
        dynamo.createApplication(appData, cb);
      },
      function(cb) {
        // split traffic 50/50 with v10
        dynamo.updateTrafficRules(appData.appId, 'production', updatedRules, cb);
      },
      function(cb) {
        dynamo.getApplication(appData.appId, function(err, app) {
          if (err) return cb(err);

          // verify that the test environment remained unchanged.
          assert.deepEqual(app.trafficRules.test, [{version: 'v3', rule: '*'}]);
          assert.deepEqual(app.trafficRules.production, updatedRules);
          cb();
        });
      }
    ], done);
  });

  it('deletes traffic rules for env', function(done) {
    var appData = {
      appId: shortid.generate(),
      orgId: shortid.generate(),
      ownerId: shortid.generate(),
      name: 'app-name-' + shortid.generate(),
      trafficRules: {
        prod: [
          {version: 'v1', rule: '*'}
        ],
        test: [
          {version: 'v3', rule: '*'}
        ]
      }
    };

    async.series([
      function(cb) {
        dynamo.createApplication(appData, cb);
      },
      function(cb) {
        // split traffic 50/50 with v10
        dynamo.deleteTrafficRules(appData.appId, 'test', cb);
      },
      function(cb) {
        dynamo.getApplication(appData.appId, function(err, app) {
          if (err) return cb(err);

          // verify that the test environment remained unchanged.
          assert.deepEqual(app.trafficRules.prod, [{version: 'v1', rule: '*'}]);
          assert.isUndefined(app.trafficRules.test);
          cb();
        });
      }
    ], done);
  });

  it('gets apps for domainName', function(done) {
    var domainName = shortid.generate() + '.net';
    var ownerId = shortid.generate();
    var orgId = shortid.generate();

    var appData = _.times(3, function(n) {
      return _.extend({}, appData, {
        appId: shortid.generate(),
        orgId: orgId,
        ownerId: ownerId,
        name: 'app-name-' + shortid.generate(),
        domainName: domainName,
        subDomain: n.toString()
      });
    });

    async.series([
      function(cb) {
        async.each(appData, dynamo.createApplication.bind(dynamo), cb);
      },
      function(cb) {
        dynamo.getAppsByDomain(domainName, function(err, data) {
          if (err) return cb(err);

          assert.noDifferences(['0', '1', '2'], _.map(data, 'subDomain'));
          cb();
        });
      }
    ], done);
  });
});
<commit_msg>Remove leftover debugger statement<commit_after>var _ = require('lodash');
var async = require('async');
var shortid = require('shortid');
var assert = require('assert');

require('dash-assert');

describe('Application', function() {
  var dynamo = require('./dynamo-local');
  var self;

  beforeEach(function() {
    self = this;
    this.appData = {
      appId: shortid.generate(),
      orgId: shortid.generate(),
      ownerId: shortid.generate(),
      name: 'app-name-' + shortid.generate(),
      trafficRules: {
        prod: [
          {version: 'v1', rule: 'random:0.5'},
          {version: 'v2', rule: 'random:0.5'}
        ],
        test: [
          {version: 'v3', rule: '*'}
        ]
      }
    };
  });

  it('create and retrieve application', function(done) {
    var domainName = shortid.generate() + '.com';
    var subDomain = 'www';

    _.extend(this.appData, {
      domainName: domainName,
      subDomain: subDomain
    });

    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, function(err, app) {
          if (err) return cb(err);

          assert.isMatch(app, self.appData);
          cb();
        });
      },
      function(cb) {
        dynamo.getAppByDomainName(domainName, subDomain, function(err, app) {
          if (err) return cb(err);
          assert.isMatch(app, self.appData);
          cb();
        });
      }
    ], done);
  });

  it('create application with existing domainName', function(done) {
    _.extend(this.appData, {
      domainName: shortid.generate() + '.com',
      subDomain: 'www'
    });

    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, cb);
      },
      function(cb) {
        self.appData.appId = shortid.generate();
        self.appData.name = 'app-name-' + shortid.generate();

        dynamo.createApplication(self.appData, function(err) {
          assert.equal(err.code, 'domainNameTaken');
          cb();
        });
      },
      function(cb) {
        self.appData.subDomain = 'www2';

        // Create another app with same domainName but different subDomain
        dynamo.createApplication(self.appData, cb);
      }
    ], done);
  });

  it('get application by name', function(done) {
    self = this;

    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, cb);
      },
      function(cb) {
        dynamo.getApplicationByName(self.appData.name, function(err, app) {
          if (err) return cb(err);

          assert.isMatch(app, self.appData);
          cb();
        });
      }
    ], done);
  });

  it('does not allow duplicate app names', function(done) {
    self = this;
    async.series([
      function(cb) {
        dynamo.models.AppName.create({name: self.appData.name, appId: shortid.generate()}, cb);
      },
      function(cb) {
        dynamo.createApplication(self.appData, function(err) {
          assert.ok(err);
          assert.equal(err.code, 'appNameExists');
          cb();
        });
      }
    ], done);
  });

  it('get appName', function(done) {
    var appName = {name: shortid.generate(), appId: shortid.generate()};
    async.series([
      function(cb) {
        dynamo.models.AppName.create(appName, cb);
      },
      function(cb) {
        dynamo.getAppName(appName.name, function(err, name) {
          assert.deepEqual(name, appName);
          cb();
        });
      }
    ], done);
  });

  it('deletes application', function(done) {
    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, cb);
      },
      function(cb) {
        // Create a version
        dynamo.createVersion({
          appId: self.appData.appId,
          versionId: shortid.generate(),
          name: 'v1',
          userId: self.appData.ownerId,
          status: 'complete',
          manifest: {}
        }, cb);
      },
      function(cb) {
        dynamo.deleteApplication(self.appData.appId, cb);
      },
      function(cb) {
        dynamo.getApplication(self.appData.appId, function(err, app) {
          if (err) return cb(err);
          assert.isNull(app);
          cb();
        });
      }
    ], done);
  });

  it('update application', function(done) {
    var appData = _.extend({}, this.appData, {
      appId: shortid.generate()
    });

    // Update the name and domains
    var updatedData = _.extend({}, appData, {
      name: shortid.generate() + '-new-name',
    });

    // First create an application
    async.series([
      function(cb) {
        dynamo.createApplication(appData, cb);
      },
      function(cb) {
        dynamo.updateApplication(updatedData, cb);
      },
      function(cb) {
        dynamo.getApplication(appData.appId, function(err, app) {
          if (err) return cb(err);

          assert.equal(app.name, updatedData.name);
          cb();
        });
      }
    ], done);
  });

  it('transfer application', function(done) {
    var newOrgId = shortid.generate();

    async.series([
      function(cb) {
        dynamo.createApplication(self.appData, cb);
      },
      function(cb) {
        dynamo.transferApplication(self.appData.appId, newOrgId, cb);
      },
      function(cb) {
        dynamo.getApplication(self.appData.appId, function(err, app) {
          if (err) return cb(err);
          assert.equal(app.orgId, newOrgId);
          cb();
        });
      }
    ], done);
  });

  it('list user applications', function(done) {
    var appIds = _.times(3, function() {
      return shortid.generate();
    });
    var userId = shortid.generate();

    async.series([
      function(cb) {
        async.each(appIds, function(appId, cb1) {
          dynamo.createApplication(_.extend({}, self.appData, {
            appId: appId,
            name: 'app-' + appId,
            ownerId: userId
          }), cb1);
        }, cb);
      },
      function(cb) {
        dynamo.userApplications(userId, function(err, userAppIds) {
          assert.equal(userAppIds.length, 3);
          assert.noDifferences(appIds, userAppIds);
          cb();
        });
      }
    ], done);
  });

  it('updates traffic rules', function(done) {
    var appData = {
      appId: shortid.generate(),
      orgId: shortid.generate(),
      ownerId: shortid.generate(),
      name: 'app-name-' + shortid.generate(),
      trafficRules: {
        test: [
          {version: 'v3', rule: '*'}
        ]
      }
    };

    var updatedRules = [
      {version: 'v1', rule: 'random:0.5'},
      {version: 'v10', rule: 'random:0.5'}
    ];

    async.series([
      function(cb) {
        dynamo.createApplication(appData, cb);
      },
      function(cb) {
        // split traffic 50/50 with v10
        dynamo.updateTrafficRules(appData.appId, 'production', updatedRules, cb);
      },
      function(cb) {
        dynamo.getApplication(appData.appId, function(err, app) {
          if (err) return cb(err);

          // verify that the test environment remained unchanged.
          assert.deepEqual(app.trafficRules.test, [{version: 'v3', rule: '*'}]);
          assert.deepEqual(app.trafficRules.production, updatedRules);
          cb();
        });
      }
    ], done);
  });

  it('deletes traffic rules for env', function(done) {
    var appData = {
      appId: shortid.generate(),
      orgId: shortid.generate(),
      ownerId: shortid.generate(),
      name: 'app-name-' + shortid.generate(),
      trafficRules: {
        prod: [
          {version: 'v1', rule: '*'}
        ],
        test: [
          {version: 'v3', rule: '*'}
        ]
      }
    };

    async.series([
      function(cb) {
        dynamo.createApplication(appData, cb);
      },
      function(cb) {
        // split traffic 50/50 with v10
        dynamo.deleteTrafficRules(appData.appId, 'test', cb);
      },
      function(cb) {
        dynamo.getApplication(appData.appId, function(err, app) {
          if (err) return cb(err);

          // verify that the test environment remained unchanged.
          assert.deepEqual(app.trafficRules.prod, [{version: 'v1', rule: '*'}]);
          assert.isUndefined(app.trafficRules.test);
          cb();
        });
      }
    ], done);
  });

  it('gets apps for domainName', function(done) {
    var domainName = shortid.generate() + '.net';
    var ownerId = shortid.generate();
    var orgId = shortid.generate();

    var appData = _.times(3, function(n) {
      return _.extend({}, appData, {
        appId: shortid.generate(),
        orgId: orgId,
        ownerId: ownerId,
        name: 'app-name-' + shortid.generate(),
        domainName: domainName,
        subDomain: n.toString()
      });
    });

    async.series([
      function(cb) {
        async.each(appData, dynamo.createApplication.bind(dynamo), cb);
      },
      function(cb) {
        dynamo.getAppsByDomain(domainName, function(err, data) {
          if (err) return cb(err);

          assert.noDifferences(['0', '1', '2'], _.map(data, 'subDomain'));
          cb();
        });
      }
    ], done);
  });
});
<|endoftext|>


<commit_before>/*
Module Axis Building Block and Tools Axis.

This module has all functionalities for graphical display of axes.

Module Dependencies: d3, THREE, BBMathematics, BBStatistics.

*/
define( [ 'd3' ], function( d3 ){
  "use strict";

  // Object Constructor BBH1 Building Block Histogram 1D.

  function Axis( name, title ){
    this.name = name;
    this.title = title;

    this.fNdivisions;
    this.fAxisColor;
    this.fLabelColor;
    this.fLabelFont;
    this.fLabelOffset;
    this.fLabelOffset;
    this.fLabelSize;
    this.fTitleOffset;
    this.d3Axis = d3.svg.axis();

  }

  Axis.prototype = {
    constructor: Axis,
    // ****************************************************
    // * Functions coming from ROOT mother class TAxisAtt *
    // ****************************************************

    //
    /*SaveAttributes: function( out, name, subname ){

      return this;
    },

    // Set color of the line axis and tick marks.
    SetAxisColor: function( color ){
      this.d3Axis.style( "stroke", color );

      return this;
    },

    // Set color of labels.
    SetLabelColor: function( color ){

      return this;
    },

    // Set labels' font.
    SetLabelFont: function( font ){

      return this;
    },

    // Set distance between the axis and the labels.
    // In ROOT: The distance is expressed in per cent of the pad width.
    SetLabelOffset: function( offset  ){

      return this;
    },

    // Set size of axis labels.
    // In ROOT: The size is expressed in per cent of the pad width.
    SetLabelSize: function( size  ){

      return this;
    },

    /* Set the number of divisions for this axis.

    if optim = kTRUE (default), the number of divisions will be
                   optimized around the specified value.
    if optim = kFALSE, or n < 0, the axis will be forced to use
                   exactly n divisions.

    n = n1 + 100*n2 + 10000*n3

    Where n1 is the number of primary divisions,
    n2 is the number of second order divisions and
    n3 is the number of third order divisions.

    e.g. 512 means 12 primary and 5 secondary divisions.

    If the number of divisions is "optimized" (see above) n1, n2, n3 are
    maximum values.
    SetNdivisions: function( n, optim  ){

      return this;
    },
    SetNdivisions: function( n1, n2, n3, optim){

      return this;
    },

    // Set tick mark length
    // The length is expressed in per cent of the pad width
    SetTickLength: function( lenght ){

      return this;
    },

    /* Set distance between the axis and the axis title
    Offset is a correction factor with respect to the "standard" value.
    offset = 1  uses the default position that is computed in function
    of the label offset and size.
    offset = 1.2 will add 20 per cent more to the default offset.
    SetTitleOffset: function( offset  ){

      return this;
    },

    // Set size of axis title.
    // The size is expressed in per cent of the pad width.
    SetTitleSize: function( size  ){

      return this;
    },

    // Set color of axis title
    SetTitleColor: function( color ){

      return this;
    },

    // Set the title font.
    SetTitleFont: function( font ){

      return this;
    },

    GetNdivisions: function(){
      return this.fNdivisions;
    },

    GetAxisColor: function(){
      return this.fAxisColor;
    },

    GetLabelColor: function(){
      return this.fLabelColor;
    },

    GetLabelFont: function(){
      return this.fLabelFont;
    },

    GetLabelOffset: function(){
      return this.fLabelOffset;
    },

    GetLabelSize: function(){
      return this.fLabelSize;
    },

    GetTitleOffset: function(){
      return this.fTitleOffset;
    },

    GetTitleSize: function(){
      return this.fTitleSize;
    },

    GetTitleColor: function(){
      return this.fTitleColor;
    },

    GetTitleFont: function(){
      return this.fTitleFont;
    },
*/
  };

  return Axis;

}); // Ends Module Axis

<commit_msg>Removed BBT/Axis.js<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, Mustache, window */

define(function (require, exports, module) {
    "use strict";

    var Dialogs               = require("widgets/Dialogs"),
        Strings               = require("strings"),
        Commands              = require("command/Commands"),
        CommandManager        = require("command/CommandManager"),
        AppInit               = require("utils/AppInit"),
        ExtensionManagerView  = require("extensibility/ExtensionManagerView").ExtensionManagerView,
        ExtensionManagerViewModel  = require("extensibility/ExtensionManagerViewModel").ExtensionManagerViewModel;

    var dialogTemplate    = require("text!htmlContent/extension-manager-dialog.html");

    /**
     * @private
     * Show a dialog that allows the user to browse and manage extensions.
     */
    function _showDialog() {
        var $dlg, view, $search, $searchClear;

        function updateSearch() {
            if (view.model.filterSet.length === 0) {
                $search.attr("disabled", "disabled");
                $searchClear.attr("disabled", "disabled");
            } else {
                $search.removeAttr("disabled");
                $searchClear.removeAttr("disabled");
            }
        }

        // Open the dialog.
        Dialogs.showModalDialogUsingTemplate(
            Mustache.render(dialogTemplate, Strings)
        ).always(function () {
            view.dispose();
        });

        // Create the view.
        $dlg = $(".extension-manager-dialog");
        $search = $(".search", $dlg);
        $searchClear = $(".search-clear", $dlg);
        view = new ExtensionManagerView();
        view.initialize(ExtensionManagerViewModel.SOURCE_INSTALLED)
            .done(function () {
                view.$el.appendTo($(".modal-body", $dlg));

                // Filter the view when the user types in the search field.
                $dlg.on("input", ".search", function (e) {
                    view.filter($(this).val());
                }).on("click", ".search-clear", function (e) {
                    $search.val("");
                    view.filter("");
                });

                // Disable the search field when there are no items int eh view.
                $(view.model).on("change", function () {
                    updateSearch();
                });

                // Handle the install button.
                $(".extension-manager-dialog .install-from-url")
                    .click(function () {
                        CommandManager.execute(Commands.FILE_INSTALL_EXTENSION);
                    });

                updateSearch();
                if (!$search.attr("disabled")) {
                    $dlg.find(".search").focus();
                }
            });
    }

    CommandManager.register(Strings.CMD_EXTENSION_MANAGER, Commands.FILE_EXTENSION_MANAGER, _showDialog);

    AppInit.appReady(function () {
        $("#toolbar-extension-manager").click(_showDialog);
    });
});
<commit_msg>Typo fix<commit_after>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, Mustache, window */

define(function (require, exports, module) {
    "use strict";

    var Dialogs               = require("widgets/Dialogs"),
        Strings               = require("strings"),
        Commands              = require("command/Commands"),
        CommandManager        = require("command/CommandManager"),
        AppInit               = require("utils/AppInit"),
        ExtensionManagerView  = require("extensibility/ExtensionManagerView").ExtensionManagerView,
        ExtensionManagerViewModel  = require("extensibility/ExtensionManagerViewModel").ExtensionManagerViewModel;

    var dialogTemplate    = require("text!htmlContent/extension-manager-dialog.html");

    /**
     * @private
     * Show a dialog that allows the user to browse and manage extensions.
     */
    function _showDialog() {
        var $dlg, view, $search, $searchClear;

        function updateSearch() {
            if (view.model.filterSet.length === 0) {
                $search.attr("disabled", "disabled");
                $searchClear.attr("disabled", "disabled");
            } else {
                $search.removeAttr("disabled");
                $searchClear.removeAttr("disabled");
            }
        }

        // Open the dialog.
        Dialogs.showModalDialogUsingTemplate(
            Mustache.render(dialogTemplate, Strings)
        ).always(function () {
            view.dispose();
        });

        // Create the view.
        $dlg = $(".extension-manager-dialog");
        $search = $(".search", $dlg);
        $searchClear = $(".search-clear", $dlg);
        view = new ExtensionManagerView();
        view.initialize(ExtensionManagerViewModel.SOURCE_INSTALLED)
            .done(function () {
                view.$el.appendTo($(".modal-body", $dlg));

                // Filter the view when the user types in the search field.
                $dlg.on("input", ".search", function (e) {
                    view.filter($(this).val());
                }).on("click", ".search-clear", function (e) {
                    $search.val("");
                    view.filter("");
                });

                // Disable the search field when there are no items in the view.
                $(view.model).on("change", function () {
                    updateSearch();
                });

                // Handle the install button.
                $(".extension-manager-dialog .install-from-url")
                    .click(function () {
                        CommandManager.execute(Commands.FILE_INSTALL_EXTENSION);
                    });

                updateSearch();
                if (!$search.attr("disabled")) {
                    $dlg.find(".search").focus();
                }
            });
    }

    CommandManager.register(Strings.CMD_EXTENSION_MANAGER, Commands.FILE_EXTENSION_MANAGER, _showDialog);

    AppInit.appReady(function () {
        $("#toolbar-extension-manager").click(_showDialog);
    });
});
<|endoftext|>