<commit_before>/* eslint-disable react/no-multi-comp */
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
import classNames from 'classnames'
import Avatar from '../assets/Avatar'
import {
  ArrowIcon,
  CheckCircleIcon,
  RepostIcon,
  StarIcon,
  XBoxIcon,
} from '../assets/Icons'
import ContentWarningButton from '../posts/ContentWarningButton'
import RelationshipContainer from '../../containers/RelationshipContainer'
import { RegionItems } from '../regions/RegionRenderables'
import { after, before, css, hover, modifier, select } from '../../styles/jss'
import * as s from '../../styles/jso'

const adminActionsStyle = css(
  s.bgcF2,
  s.colorA,
  s.flex,
  s.fontSize14,
  s.fullWidth,
  s.hv40,
  s.itemsCenter,
  s.justifyCenter,
  s.mb10,
  { marginTop: -10 },
)

const actionButtonStyle = css(
  s.mx5,
  s.transitionColor,
  after(s.inlineBlock, { content: 'attr(data-label)' }),
  select('> .SVGIcon', s.mr5),
  modifier('.approve', hover(s.colorBlack), select('> .CheckCircleIcon', { marginTop: -2 })),
  modifier('.select', hover(s.colorYellow, select('> .StarIcon > g', { fill: '#ffc600' })), select('> .StarIcon', { paddingTop: 2, paddingLeft: 4 })),
  modifier(
    '.unapprove',
    s.colorGreen,
    select('> .CheckCircleIcon', { marginTop: -2 }),
    after({ content: '"Approved"' }),
    hover(
      s.colorBlack,
      after({ content: 'attr(data-label)' }),
      select('> .CheckCircleIcon', s.displayNone),
      select('> .XBoxIcon', s.inlineBlock),
    ),
    select('> .CheckCircleIcon', s.inlineBlock),
    select('> .XBoxIcon', s.displayNone),
  ),
  modifier(
    '.unselect',
    s.colorYellow,
    select('> .StarIcon', { paddingTop: 2, paddingLeft: 4 }),
    after({ content: '"Selected"' }),
    hover(
      s.colorBlack,
      after({ content: 'attr(data-label)' }),
      select('> .StarIcon', s.displayNone),
      select('> .XBoxIcon', s.inlineBlock),
    ),
    select('> .StarIcon', s.inlineBlock, select('> g', { fill: '#ffc600' })),
    select('> .XBoxIcon', s.displayNone),
  ),
)

const getActionIcon = (type) => {
  switch (type) {
    case 'approve':
      return <CheckCircleIcon />
    case 'select':
      return <StarIcon />
    case 'unapprove':
      return [<CheckCircleIcon key="normal" />, <XBoxIcon key="hover" />]
    case 'unselect':
      return [<StarIcon key="normal" />, <XBoxIcon key="hover" />]
    default:
      return null
  }
}

export const PostAdminActions = ({ actions, status }, { onClickAction }) => (
  <div className={`${adminActionsStyle} ${status}`}>
    {actions.entrySeq().map(([type, action]) => (
      <button
        className={`${actionButtonStyle} ${type}`}
        onClick={() => onClickAction(action)}
        data-label={action.get('label')}
        key={type}
      >
        {getActionIcon(type)}
      </button>
    ))}

)
PostAdminActions.propTypes = {
  actions: PropTypes.object.isRequired,
  status: PropTypes.string.isRequired,
}
PostAdminActions.contextTypes = {
  onClickAction: PropTypes.func.isRequired,
}

const PostHeaderTimeAgoLink = ({ to, createdAt }) =>
  (<Link className="PostHeaderTimeAgoLink" to={to}>
    {new Date(createdAt).timeAgoInWords()}
  </Link>)
PostHeaderTimeAgoLink.propTypes = {
  createdAt: PropTypes.string.isRequired,
  to: PropTypes.string.isRequired,
}

export class PostHeader extends PureComponent {
  static propTypes = {
    author: PropTypes.object.isRequired,
    detailPath: PropTypes.string.isRequired,
    isPostDetail: PropTypes.bool.isRequired,
    postCreatedAt: PropTypes.string.isRequired,
    postId: PropTypes.string.isRequired,
  }
  render() {
    const { author, detailPath, isPostDetail, postCreatedAt, postId } = this.props
    return (
      <header className="PostHeader" key={`PostHeader_${postId}`}>

          <Link className="PostHeaderLink" to={`/${author.get('username')}`}>
            <Avatar
              priority={author.get('relationshipPriority')}
              sources={author.get('avatar')}
              userId={`${author.get('id')}`}
              username={author.get('username')}
            />

              {isPostDetail && author.get('name') ?

                  {author.get('name')}
                  @{author.get('username')}

                :
                `@${author.get('username')}`
              }

          </Link>

        <RelationshipContainer className="isInHeader" user={author} />
        <PostHeaderTimeAgoLink to={detailPath} createdAt={postCreatedAt} />

    )
  }
}

export class CategoryHeader extends PureComponent {
  static propTypes = {
    author: PropTypes.object.isRequired,
    categoryName: PropTypes.string.isRequired,
    categoryPath: PropTypes.string.isRequired,
    detailPath: PropTypes.string.isRequired,
    postCreatedAt: PropTypes.string.isRequired,
    postId: PropTypes.string.isRequired,
  }
  render() {
    const { author, categoryName, categoryPath, detailPath, postCreatedAt, postId } = this.props
    return (
      <header className="CategoryHeader" key={`CategoryHeader_${postId}`}>

          <Link className="PostHeaderLink" to={`/${author.get('username')}`}>
            <Avatar
              priority={author.get('relationshipPriority')}
              sources={author.get('avatar')}
              userId={`${author.get('id')}`}
              username={author.get('username')}
            />

              {`@${author.get('username')}`}

          </Link>

        <RelationshipContainer className="isInHeader" user={author} />

          <Link className="PostHeaderLink" to={categoryPath}>
            in
            {categoryName}
          </Link>

        <PostHeaderTimeAgoLink to={detailPath} createdAt={postCreatedAt} />

    )
  }
}

export class RepostHeader extends PureComponent {
  static propTypes = {
    detailPath: PropTypes.string.isRequired,
    inUserDetail: PropTypes.bool.isRequired,
    postCreatedAt: PropTypes.string.isRequired,
    postId: PropTypes.string.isRequired,
    repostAuthor: PropTypes.object.isRequired,
    repostedBy: PropTypes.object.isRequired,
  }
  render() {
    const { detailPath, inUserDetail, postCreatedAt, postId, repostAuthor, repostedBy } = this.props
    return (
      <header className={classNames('RepostHeader', { inUserDetail })} key={`RepostHeader_${postId}`}>

          <Link className="PostHeaderLink" to={`/${repostAuthor.get('username')}`}>
            <Avatar
              priority={repostAuthor.get('relationshipPriority')}
              sources={repostAuthor.get('avatar')}
              userId={`${repostAuthor.get('id')}`}
              username={repostAuthor.get('username')}
            />

              {`@${repostAuthor.get('username')}`}

          </Link>

        <RelationshipContainer className="isInHeader" user={repostAuthor} />

          <Link className="PostHeaderLink" to={`/${repostedBy.get('username')}`}>
            <RepostIcon />

              {` by @${repostedBy.get('username')}`}

          </Link>

        <PostHeaderTimeAgoLink to={detailPath} createdAt={postCreatedAt} />

    )
  }
}

export class PostBody extends PureComponent {
  static propTypes = {
    author: PropTypes.object.isRequired,
    columnWidth: PropTypes.number.isRequired,
    commentOffset: PropTypes.number.isRequired,
    content: PropTypes.object.isRequired,
    contentWarning: PropTypes.string,
    contentWidth: PropTypes.number.isRequired,
    detailPath: PropTypes.string.isRequired,
    innerHeight: PropTypes.number.isRequired,
    isGridMode: PropTypes.bool.isRequired,
    isPostDetail: PropTypes.bool.isRequired,
    isRepost: PropTypes.bool.isRequired,
    postId: PropTypes.string.isRequired,
    repostContent: PropTypes.object,
    summary: PropTypes.object.isRequired,
  }
  static defaultProps = {
    contentWarning: null,
    repostContent: null,
  }
  render() {
    const {
      author,
      columnWidth,
      commentOffset,
      content,
      contentWarning,
      contentWidth,
      detailPath,
      innerHeight,
      isGridMode,
      isPostDetail,
      isRepost,
      postId,
      repostContent,
      summary,
    } = this.props
    const cells = []

    if (contentWarning && !isPostDetail) {
      cells.push(<ContentWarningButton contentWarning={contentWarning} key={`contentWarning_${postId}`} />)
    }

    const regionProps = {
      columnWidth,
      commentOffset,
      contentWidth,
      detailPath,
      innerHeight,
      isGridMode,
      isPostDetail,
    }
    if (isRepost) {
      // this is weird, but the post summary is
      // actually the repost summary on reposts
      if (isGridMode) {
        regionProps.content = summary
        cells.push(<RegionItems {...regionProps} key={`RegionItems_${postId}`} />)
      } else {
        regionProps.content = repostContent
        cells.push(<RegionItems {...regionProps} key={`RegionItems_${postId}`} />)
        if (content && content.size) {
          regionProps.content = content
          cells.push(
            <div className="PostBody RepostedBody" key={`RepostedBody_${postId}`}>
              <Avatar
                priority={author.get('relationshipPriority')}
                sources={author.get('avatar')}
                to={`/${author.get('username')}`}
                userId={`${author.get('id')}`}
                username={author.get('username')}
              />
              <RegionItems {...regionProps} />

,
          )
        }
      }
    } else {
      regionProps.content = isGridMode ? summary : content
      cells.push(<RegionItems {...regionProps} key={`RegionItems_${postId}`} />)
    }
    return (
      <div className="PostBody" key={`PostBody_${postId}`}>
        {cells}

    )
  }
}

const launchCommentEditorStyle = css(
  s.mt30,
  s.relative,
)

const launchCommentEditorAvatarStyle = css(
  { top: 10 },
)

const launchCommentEditorButtonStyle = css(
  s.absolute,
  s.bgcBlack,
  s.colorWhite,
  s.sansRegular,
  s.ml20,
  s.fontSize14,
  {
    borderRadius: 5,
    height: 50,
    width: 'calc(100% - 50px)',
    maxWidth: '640px',
    paddingLeft: 8,
    textAlign: 'left',
  },
  before(
    s.absolute,
    {
      top: 15,
      left: -20,
      width: 0,
      height: 0,
      content: '""',
      borderColor: 'transparent',
      borderStyle: 'solid',
      borderWidth: 10,
      borderRightColor: '#000',
    },
  ),
)

export const LaunchCommentEditorButton = ({ avatar, post }, { onLaunchNativeEditor }) =>
  (

    <Avatar className={`${launchCommentEditorAvatarStyle}`} sources={avatar} />
    <button
      className={launchCommentEditorButtonStyle}
      onClick={() => onLaunchNativeEditor(post, true, null)}
    >
      Comment...
    </button>

)
LaunchCommentEditorButton.propTypes = {
  avatar: PropTypes.object,
  post: PropTypes.object,
}
LaunchCommentEditorButton.defaultProps = {
  avatar: null,
  post: null,
}
LaunchCommentEditorButton.contextTypes = {
  onLaunchNativeEditor: PropTypes.func.isRequired,
}

const relatedPostButtonStyle = css(
  s.absolute,
  { top: 0, right: 0 },
  s.fontSize18,
  s.colorA,
  s.transitionColor,
  hover(s.colorBlack),
  select('& > .ArrowIcon', s.rotate90, { marginLeft: 15 }),
)

export const RelatedPostsButton = (props, { onClickScrollToRelatedPosts }) =>
  (<button
    className={relatedPostButtonStyle}
    onClick={onClickScrollToRelatedPosts}
  >
    Related Posts
    <ArrowIcon />
  </button>)
RelatedPostsButton.contextTypes = {
  onClickScrollToRelatedPosts: PropTypes.func.isRequired,
}

<commit_msg>Cleanup and refactor the css a bit<commit_after>/* eslint-disable react/no-multi-comp */
import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
import classNames from 'classnames'
import Avatar from '../assets/Avatar'
import {
  ArrowIcon,
  CheckCircleIcon,
  RepostIcon,
  StarIcon,
  XBoxIcon,
} from '../assets/Icons'
import ContentWarningButton from '../posts/ContentWarningButton'
import RelationshipContainer from '../../containers/RelationshipContainer'
import { RegionItems } from '../regions/RegionRenderables'
import { after, before, css, hover, modifier, select } from '../../styles/jss'
import * as s from '../../styles/jso'

const adminActionsStyle = css(
  s.bgcF2,
  s.colorA,
  s.flex,
  s.fontSize14,
  s.fullWidth,
  s.hv40,
  s.itemsCenter,
  s.justifyCenter,
  s.mb10,
  { marginTop: -10 },
)

const actionButtonStyle = css(
  s.mx5,
  s.transitionColor,
  after(s.inlineBlock, { content: 'attr(data-label)' }),
  hover(
    s.colorBlack,
    after({ content: 'attr(data-label)' }),
    select('> .XBoxIcon', s.inlineBlock),
  ),
  select('> .SVGIcon', s.mr5),
  select('> .SVGIcon.CheckCircleIcon', { marginTop: -2, marginRight: 7 }),
  select('> .StarIcon', { paddingTop: 2, paddingLeft: 2 }),
  select('> .XBoxIcon', s.displayNone),
  modifier(
    '.select',
    hover(
      s.colorYellow,
      select('> .StarIcon > g', { fill: '#ffc600' }),
    ),
  ),
  modifier(
    '.unapprove',
    s.colorGreen,
    after({ content: '"Approved"' }),
    hover(
      select('> .CheckCircleIcon', s.displayNone),
    ),
    select('> .CheckCircleIcon', s.inlineBlock),
  ),
  modifier(
    '.unselect',
    s.colorYellow,
    after({ content: '"Selected"' }),
    hover(
      select('> .StarIcon', s.displayNone),
    ),
    select('> .StarIcon', s.inlineBlock, select('> g', { fill: '#ffc600' })),
  ),
)

const getActionIcon = (type) => {
  switch (type) {
    case 'approve':
      return <CheckCircleIcon />
    case 'select':
      return <StarIcon />
    case 'unapprove':
      return [<CheckCircleIcon key="normal" />, <XBoxIcon key="hover" />]
    case 'unselect':
      return [<StarIcon key="normal" />, <XBoxIcon key="hover" />]
    default:
      return null
  }
}

export const PostAdminActions = ({ actions, status }, { onClickAction }) => (
  <div className={`${adminActionsStyle} ${status}`}>
    {actions.entrySeq().map(([type, action]) => (
      <button
        className={`${actionButtonStyle} ${type}`}
        onClick={() => onClickAction(action)}
        data-label={action.get('label')}
        key={type}
      >
        {getActionIcon(type)}
      </button>
    ))}

)
PostAdminActions.propTypes = {
  actions: PropTypes.object.isRequired,
  status: PropTypes.string.isRequired,
}
PostAdminActions.contextTypes = {
  onClickAction: PropTypes.func.isRequired,
}

const PostHeaderTimeAgoLink = ({ to, createdAt }) =>
  (<Link className="PostHeaderTimeAgoLink" to={to}>
    {new Date(createdAt).timeAgoInWords()}
  </Link>)
PostHeaderTimeAgoLink.propTypes = {
  createdAt: PropTypes.string.isRequired,
  to: PropTypes.string.isRequired,
}

export class PostHeader extends PureComponent {
  static propTypes = {
    author: PropTypes.object.isRequired,
    detailPath: PropTypes.string.isRequired,
    isPostDetail: PropTypes.bool.isRequired,
    postCreatedAt: PropTypes.string.isRequired,
    postId: PropTypes.string.isRequired,
  }
  render() {
    const { author, detailPath, isPostDetail, postCreatedAt, postId } = this.props
    return (
      <header className="PostHeader" key={`PostHeader_${postId}`}>

          <Link className="PostHeaderLink" to={`/${author.get('username')}`}>
            <Avatar
              priority={author.get('relationshipPriority')}
              sources={author.get('avatar')}
              userId={`${author.get('id')}`}
              username={author.get('username')}
            />

              {isPostDetail && author.get('name') ?

                  {author.get('name')}
                  @{author.get('username')}

                :
                `@${author.get('username')}`
              }

          </Link>

        <RelationshipContainer className="isInHeader" user={author} />
        <PostHeaderTimeAgoLink to={detailPath} createdAt={postCreatedAt} />

    )
  }
}

export class CategoryHeader extends PureComponent {
  static propTypes = {
    author: PropTypes.object.isRequired,
    categoryName: PropTypes.string.isRequired,
    categoryPath: PropTypes.string.isRequired,
    detailPath: PropTypes.string.isRequired,
    postCreatedAt: PropTypes.string.isRequired,
    postId: PropTypes.string.isRequired,
  }
  render() {
    const { author, categoryName, categoryPath, detailPath, postCreatedAt, postId } = this.props
    return (
      <header className="CategoryHeader" key={`CategoryHeader_${postId}`}>

          <Link className="PostHeaderLink" to={`/${author.get('username')}`}>
            <Avatar
              priority={author.get('relationshipPriority')}
              sources={author.get('avatar')}
              userId={`${author.get('id')}`}
              username={author.get('username')}
            />

              {`@${author.get('username')}`}

          </Link>

        <RelationshipContainer className="isInHeader" user={author} />

          <Link className="PostHeaderLink" to={categoryPath}>
            in
            {categoryName}
          </Link>

        <PostHeaderTimeAgoLink to={detailPath} createdAt={postCreatedAt} />

    )
  }
}

export class RepostHeader extends PureComponent {
  static propTypes = {
    detailPath: PropTypes.string.isRequired,
    inUserDetail: PropTypes.bool.isRequired,
    postCreatedAt: PropTypes.string.isRequired,
    postId: PropTypes.string.isRequired,
    repostAuthor: PropTypes.object.isRequired,
    repostedBy: PropTypes.object.isRequired,
  }
  render() {
    const { detailPath, inUserDetail, postCreatedAt, postId, repostAuthor, repostedBy } = this.props
    return (
      <header className={classNames('RepostHeader', { inUserDetail })} key={`RepostHeader_${postId}`}>

          <Link className="PostHeaderLink" to={`/${repostAuthor.get('username')}`}>
            <Avatar
              priority={repostAuthor.get('relationshipPriority')}
              sources={repostAuthor.get('avatar')}
              userId={`${repostAuthor.get('id')}`}
              username={repostAuthor.get('username')}
            />

              {`@${repostAuthor.get('username')}`}

          </Link>

        <RelationshipContainer className="isInHeader" user={repostAuthor} />

          <Link className="PostHeaderLink" to={`/${repostedBy.get('username')}`}>
            <RepostIcon />

              {` by @${repostedBy.get('username')}`}

          </Link>

        <PostHeaderTimeAgoLink to={detailPath} createdAt={postCreatedAt} />

    )
  }
}

export class PostBody extends PureComponent {
  static propTypes = {
    author: PropTypes.object.isRequired,
    columnWidth: PropTypes.number.isRequired,
    commentOffset: PropTypes.number.isRequired,
    content: PropTypes.object.isRequired,
    contentWarning: PropTypes.string,
    contentWidth: PropTypes.number.isRequired,
    detailPath: PropTypes.string.isRequired,
    innerHeight: PropTypes.number.isRequired,
    isGridMode: PropTypes.bool.isRequired,
    isPostDetail: PropTypes.bool.isRequired,
    isRepost: PropTypes.bool.isRequired,
    postId: PropTypes.string.isRequired,
    repostContent: PropTypes.object,
    summary: PropTypes.object.isRequired,
  }
  static defaultProps = {
    contentWarning: null,
    repostContent: null,
  }
  render() {
    const {
      author,
      columnWidth,
      commentOffset,
      content,
      contentWarning,
      contentWidth,
      detailPath,
      innerHeight,
      isGridMode,
      isPostDetail,
      isRepost,
      postId,
      repostContent,
      summary,
    } = this.props
    const cells = []

    if (contentWarning && !isPostDetail) {
      cells.push(<ContentWarningButton contentWarning={contentWarning} key={`contentWarning_${postId}`} />)
    }

    const regionProps = {
      columnWidth,
      commentOffset,
      contentWidth,
      detailPath,
      innerHeight,
      isGridMode,
      isPostDetail,
    }
    if (isRepost) {
      // this is weird, but the post summary is
      // actually the repost summary on reposts
      if (isGridMode) {
        regionProps.content = summary
        cells.push(<RegionItems {...regionProps} key={`RegionItems_${postId}`} />)
      } else {
        regionProps.content = repostContent
        cells.push(<RegionItems {...regionProps} key={`RegionItems_${postId}`} />)
        if (content && content.size) {
          regionProps.content = content
          cells.push(
            <div className="PostBody RepostedBody" key={`RepostedBody_${postId}`}>
              <Avatar
                priority={author.get('relationshipPriority')}
                sources={author.get('avatar')}
                to={`/${author.get('username')}`}
                userId={`${author.get('id')}`}
                username={author.get('username')}
              />
              <RegionItems {...regionProps} />

,
          )
        }
      }
    } else {
      regionProps.content = isGridMode ? summary : content
      cells.push(<RegionItems {...regionProps} key={`RegionItems_${postId}`} />)
    }
    return (
      <div className="PostBody" key={`PostBody_${postId}`}>
        {cells}

    )
  }
}

const launchCommentEditorStyle = css(
  s.mt30,
  s.relative,
)

const launchCommentEditorAvatarStyle = css(
  { top: 10 },
)

const launchCommentEditorButtonStyle = css(
  s.absolute,
  s.bgcBlack,
  s.colorWhite,
  s.sansRegular,
  s.ml20,
  s.fontSize14,
  {
    borderRadius: 5,
    height: 50,
    width: 'calc(100% - 50px)',
    maxWidth: '640px',
    paddingLeft: 8,
    textAlign: 'left',
  },
  before(
    s.absolute,
    {
      top: 15,
      left: -20,
      width: 0,
      height: 0,
      content: '""',
      borderColor: 'transparent',
      borderStyle: 'solid',
      borderWidth: 10,
      borderRightColor: '#000',
    },
  ),
)

export const LaunchCommentEditorButton = ({ avatar, post }, { onLaunchNativeEditor }) =>
  (

    <Avatar className={`${launchCommentEditorAvatarStyle}`} sources={avatar} />
    <button
      className={launchCommentEditorButtonStyle}
      onClick={() => onLaunchNativeEditor(post, true, null)}
    >
      Comment...
    </button>

)
LaunchCommentEditorButton.propTypes = {
  avatar: PropTypes.object,
  post: PropTypes.object,
}
LaunchCommentEditorButton.defaultProps = {
  avatar: null,
  post: null,
}
LaunchCommentEditorButton.contextTypes = {
  onLaunchNativeEditor: PropTypes.func.isRequired,
}

const relatedPostButtonStyle = css(
  s.absolute,
  { top: 0, right: 0 },
  s.fontSize18,
  s.colorA,
  s.transitionColor,
  hover(s.colorBlack),
  select('& > .ArrowIcon', s.rotate90, { marginLeft: 15 }),
)

export const RelatedPostsButton = (props, { onClickScrollToRelatedPosts }) =>
  (<button
    className={relatedPostButtonStyle}
    onClick={onClickScrollToRelatedPosts}
  >
    Related Posts
    <ArrowIcon />
  </button>)
RelatedPostsButton.contextTypes = {
  onClickScrollToRelatedPosts: PropTypes.func.isRequired,
}

<|endoftext|>


<commit_before>var gulp = require('gulp');
var path = require('path');

var jquery = {
    bowerComponent: 'jquery',
    distFiles: ['dist/jquery.js']
};

var jqueryui = {
    bowerComponent: 'jquery-ui',
    distFiles: ['jquery-ui.js']
};

var underscore = {
    bowerComponent: 'underscore',
    distFiles: ['underscore.js']
}

var handlebars = {
    bowerComponent: 'handlebars',
    distFiles: ['handlebars.js']
};

var backbone = {
    bowerComponent: 'backbone#1.1.2',
    distFiles: ['backbone.js']
}

var aceEditor = {
    id: 'ace-builds',
    bowerComponent: 'git@github.com:ajaxorg/ace-builds.git',
    distFiles: [
        './src/ace.js',
        './src/worker-json.js',
        './src/mode-json.js',
        './src/theme-chrome.js'
    ]
};

var leaflet = {
    bowerComponent: 'leaflet',
    distFiles: [
        'dist/leaflet-src.js',
        'dist/leaflet.css',
        'dist/images/layers.png',
        'dist/images/layers-2x.png',
        'dist/images/marker-icon.png',
        'dist/images/marker-icon-2x.png',
        'dist/images/marker-shadow.png'
    ]
};

var leafletActiveArea = {
    id: 'Leaflet-active-area',
    bowerComponent: 'Mappy/Leaflet-active-area',
    distFiles: ['./src/leaflet.activearea.js']
};

var markercluster = {
    id: 'leaflet.markercluster',
    srcDir: './external/leaflet.markercluster',
    distFiles: ['dist/MarkerCluster.css', 'dist/MarkerCluster.Default.css', 'dist/leaflet.markercluster.js'],
    build: true,
    watch: true
};

var heatmap = {
    id: 'leaflet.heat',
    bowerComponent: 'leaflet/leaflet.heat',
    distFiles: ['dist/leaflet-heat.js']
};

var leafletGeomixer = {
    id: 'Leaflet-GeoMixer',
    srcDir: './external/Leaflet-GeoMixer',
    distFiles: ['./dist/leaflet-geomixer-src.js'],
    build: true,
    watch: false
};

var tileLayerMercator = {
    id: 'Leaflet.TileLayer.Mercator',
    srcDir: './external/Leaflet.TileLayer.Mercator',
    distFiles: ['./src/TileLayer.Mercator.js'],
    build: false,
    watch: false
};

var gmxBaseLayersManager = {
    id: 'Leaflet.gmxBaseLayersManager',
    srcDir: './external/Leaflet.gmxBaseLayersManager',
    distFiles: [
        './src/gmxBaseLayersManager.js',
        './src/initBaseLayerManager.js'
    ],
    build: false,
    watch: false
};

var gmxControls = {
    id: 'gmxControls',
    srcDir: './external/gmxControls',
    distFiles: [
        './dist/gmxControls-src.js',
        './dist/css/gmxControls.css',
        './dist/css/img/band.png',
        './dist/css/img/coords.png',
        './dist/css/img/gmxSprite.png',
        './dist/css/img/logo_footer.png',
        './dist/css/img/logo_footer_color.png'
    ],
    build: true,
    watch: false
};

var iconLayersControl = {
    id: 'Leaflet-IconLayers',
    srcDir: './external/Leaflet-IconLayers',
    distDir: './src',
    build: false
};

var gmxIconLayers = {
    id: 'GmxIconLayers',
    srcDir: './external/GMXCommonComponents/GmxIconLayers',
    build: false
};

var componentsManager = {
    id: 'ComponentsManager',
    srcDir: './external/GMXCommonComponents/ComponentsManager',
    distDir: './build',
    build: true
};

var utils = {
    id: 'Utils',
    srcDir: './external/GMXCommonComponents/Utils',
    build: false
};

var winnieCore = {
    id: 'core',
    srcDir: './core',
    build: false
};

var commonStyles = {
    id: 'CommonStyles',
    srcDir: './external/GMXCommonComponents/CommonStyles',
    distDir: './build',
    build: true
};

var translations = {
    id: 'translations',
    url: 'http://maps.kosmosnimki.ru/api/translations.js'
};

var dropdownMenuWidget = {
    id: 'DropdownMenuWidget',
    srcDir: './external/GMXCommonComponents/DropdownMenuWidget',
    distDir: './build',
    build: true
};

var popover = {
    id: 'Popover',
    srcDir: './external/GMXCommonComponents/Popover',
    distDir: './build',
    build: true
};

var authManager = {
    id: 'AuthManager',
    srcDir: './external/GMXCommonComponents/AuthManager',
    distDir: './build',
    build: true
};

var thorax = {
    id: 'Thorax',
    srcDir: './external/GMXCommonComponents/Thorax',
    distFiles: [
        './thorax.js'
    ],
    build: false,
    watch: false
}

var layersTree = {
    id: 'LayersTree',
    srcDir: './external/GMXCommonComponents/LayersTree',
    distDir: './build',
    build: true
};

var layersDebugger = './external/GMXCommonComponents/LayersDebugger';

var gmxWidget = {
    id: 'GmxWidget',
    srcDir: './external/GMXCommonComponents/GmxWidget',
    build: false
};

var animationHelpers = {
    id: 'animationHelpers',
    srcDir: './external/GMXCommonComponents/animationHelpers',
    build: false
};

var sidebar = {
    id: 'IconSidebarControl',
    srcDir: './external/GMXCommonComponents/IconSidebarControl'
};

var storytellingControl = {
    id: 'StorytellingControl',
    srcDir: './external/GMXCommonComponents/StorytellingControl',
    build: false
};

var storytellingAccordeonControl =  {
    id: 'storytellingAccordeonControl',
    srcDir: './external/GMXCommonComponents/StorytellingAccordeonControl',
    build: false
};

var layersTreeWidget = {
    id: 'LayersTreeWidget',
    srcDir: './external/GMXCommonComponents/LayersTreeWidget',
    distDir: './build',
    build: true
};

var dateInterval = {
    id: 'DateInterval',
    srcDir: './external/GMXCommonComponents/DateInterval',
    build: false
};

var calendarWidget = {
    id: 'CalendarWidget',
    srcDir: './external/GMXCommonComponents/CalendarWidget',
    distDir: './build',
    build: true
};

var switchingCollectionWidget = {
    id: 'SwitchingCollectionWidget',
    srcDir: './external/GMXCommonComponents/SwitchingCollectionWidget',
    build: false
};

var bookmarksWidget = {
    id: 'BookmarksWidget',
    srcDir: './external/GMXCommonComponents/BookmarksWidget',
    distDir: './build',
    build: true
};

var stateManager = {
    id: 'StateManager',
    srcDir: './external/GMXCommonComponents/StateManager',
    build: false
};

var alertWidget = {
    id: 'AlertWidget',
    srcDir: './external/GMXCommonComponents/AlertWidget',
    distDir: './build',
    build: true
};

var shareIconControl = {
    id: 'ShareIconControl',
    srcDir: './external/GMXCommonComponents/ShareIconControl',
    distDir: 'build',
    build: true
};

var coreComponents = [
    jquery,
    jqueryui,
    handlebars,
    underscore,
    backbone,
    thorax,
    leaflet,
    leafletActiveArea,
    markercluster,
    heatmap,
    leafletGeomixer,
    tileLayerMercator,
    gmxBaseLayersManager,
    gmxControls,
    layersTree,
    layersDebugger,
    commonStyles,
    popover,
    translations,
    iconLayersControl,
    gmxIconLayers,
    componentsManager,
    utils,
    gmxWidget,
    animationHelpers,
    switchingCollectionWidget,
    sidebar,
    layersTreeWidget,
    dateInterval,
    calendarWidget,
    bookmarksWidget,
    storytellingControl,
    storytellingAccordeonControl,
    stateManager,
    winnieCore
];

var virtualLayers = [{
    id: 'GmxVirtualTileLayer',
    srcDir: './external/GMXCommonComponents/GmxVirtualTileLayer',
    build: false
}, {
    id: 'leaflet-GIBS',
    srcDir: './external/leaflet-GIBS',
    distFiles: [
        './src/GeoMixerGIBSLayer.js',
        './src/GIBSLayer.js',
        './src/GIBSMetadata.js'
    ],
    build: false
}, {
    id: 'GMXPluginGFW',
    srcDir: './external/GMXPluginGFW',
    distFiles: [
        './src/L.GFWLayer.js',
        './src/L.GFWSlider.js',
        './src/L.GFWSlider.css',
        './src/GmxGFWLayer.js'
    ],
    build: false
}, {
    id: 'L.ImageOverlay.Pane',
    srcDir: './external/L.ImageOverlay.Pane',
    distDir: './src',
    build: false
}, {
    id: 'GMXPluginCadatsre',
    srcDir: './external/GMXPluginCadatsre',
    distFiles: [
        './GmxCadastreLayer.js',
        './L.Cadastre/src/L.Cadastre.js',
        './L.Cadastre/src/L.Cadastre.css',
        './L.Cadastre/src/L.Cadastre.Info.js'
    ],
    build: false
}];

require('./external/GMXBuilder')(gulp, {
    tempDir: './temp',
    distDir: './dist',
    watchExtensions: ['.js', '.css', '.html', '.less', '.svg'],
    distributionExtensions: ['.js', '.css', '.jpg', '.png', '.eot', '.ttf', '.woff', '.svg']
}, [{
    id: 'core',
    components: coreComponents
}, {
    id: 'viewer',
    htmlfile: 'html/viewer.html',
    components: [].concat(coreComponents, virtualLayers, [{
        id: 'viewer',
        srcDir: './viewer'
    }])
}, {
    id: 'index',
    htmlfile: 'html/index.html',
    components: [].concat(coreComponents, virtualLayers, [
        aceEditor,
        dropdownMenuWidget,
        alertWidget,
        shareIconControl,
        authManager, {
            id: 'editor',
            srcDir: './editor',
            distDir: './build',
            build: true
        }
    ])
}]);
<commit_msg>core: fix. include ScrollView<commit_after>var gulp = require('gulp');
var path = require('path');

var jquery = {
    bowerComponent: 'jquery',
    distFiles: ['dist/jquery.js']
};

var jqueryui = {
    bowerComponent: 'jquery-ui',
    distFiles: ['jquery-ui.js']
};

var underscore = {
    bowerComponent: 'underscore',
    distFiles: ['underscore.js']
}

var handlebars = {
    bowerComponent: 'handlebars',
    distFiles: ['handlebars.js']
};

var backbone = {
    bowerComponent: 'backbone#1.1.2',
    distFiles: ['backbone.js']
}

var aceEditor = {
    id: 'ace-builds',
    bowerComponent: 'git@github.com:ajaxorg/ace-builds.git',
    distFiles: [
        './src/ace.js',
        './src/worker-json.js',
        './src/mode-json.js',
        './src/theme-chrome.js'
    ]
};

var leaflet = {
    bowerComponent: 'leaflet',
    distFiles: [
        'dist/leaflet-src.js',
        'dist/leaflet.css',
        'dist/images/layers.png',
        'dist/images/layers-2x.png',
        'dist/images/marker-icon.png',
        'dist/images/marker-icon-2x.png',
        'dist/images/marker-shadow.png'
    ]
};

var leafletActiveArea = {
    id: 'Leaflet-active-area',
    bowerComponent: 'Mappy/Leaflet-active-area',
    distFiles: ['./src/leaflet.activearea.js']
};

var markercluster = {
    id: 'leaflet.markercluster',
    srcDir: './external/leaflet.markercluster',
    distFiles: ['dist/MarkerCluster.css', 'dist/MarkerCluster.Default.css', 'dist/leaflet.markercluster.js'],
    build: true,
    watch: true
};

var heatmap = {
    id: 'leaflet.heat',
    bowerComponent: 'leaflet/leaflet.heat',
    distFiles: ['dist/leaflet-heat.js']
};

var leafletGeomixer = {
    id: 'Leaflet-GeoMixer',
    srcDir: './external/Leaflet-GeoMixer',
    distFiles: ['./dist/leaflet-geomixer-src.js'],
    build: true,
    watch: false
};

var tileLayerMercator = {
    id: 'Leaflet.TileLayer.Mercator',
    srcDir: './external/Leaflet.TileLayer.Mercator',
    distFiles: ['./src/TileLayer.Mercator.js'],
    build: false,
    watch: false
};

var gmxBaseLayersManager = {
    id: 'Leaflet.gmxBaseLayersManager',
    srcDir: './external/Leaflet.gmxBaseLayersManager',
    distFiles: [
        './src/gmxBaseLayersManager.js',
        './src/initBaseLayerManager.js'
    ],
    build: false,
    watch: false
};

var gmxControls = {
    id: 'gmxControls',
    srcDir: './external/gmxControls',
    distFiles: [
        './dist/gmxControls-src.js',
        './dist/css/gmxControls.css',
        './dist/css/img/band.png',
        './dist/css/img/coords.png',
        './dist/css/img/gmxSprite.png',
        './dist/css/img/logo_footer.png',
        './dist/css/img/logo_footer_color.png'
    ],
    build: true,
    watch: false
};

var iconLayersControl = {
    id: 'Leaflet-IconLayers',
    srcDir: './external/Leaflet-IconLayers',
    distDir: './src',
    build: false
};

var gmxIconLayers = {
    id: 'GmxIconLayers',
    srcDir: './external/GMXCommonComponents/GmxIconLayers',
    build: false
};

var componentsManager = {
    id: 'ComponentsManager',
    srcDir: './external/GMXCommonComponents/ComponentsManager',
    distDir: './build',
    build: true
};

var utils = {
    id: 'Utils',
    srcDir: './external/GMXCommonComponents/Utils',
    build: false
};

var winnieCore = {
    id: 'core',
    srcDir: './core',
    build: false
};

var commonStyles = {
    id: 'CommonStyles',
    srcDir: './external/GMXCommonComponents/CommonStyles',
    distDir: './build',
    build: true
};

var translations = {
    id: 'translations',
    url: 'http://maps.kosmosnimki.ru/api/translations.js'
};

var dropdownMenuWidget = {
    id: 'DropdownMenuWidget',
    srcDir: './external/GMXCommonComponents/DropdownMenuWidget',
    distDir: './build',
    build: true
};

var popover = {
    id: 'Popover',
    srcDir: './external/GMXCommonComponents/Popover',
    distDir: './build',
    build: true
};

var authManager = {
    id: 'AuthManager',
    srcDir: './external/GMXCommonComponents/AuthManager',
    distDir: './build',
    build: true
};

var thorax = {
    id: 'Thorax',
    srcDir: './external/GMXCommonComponents/Thorax',
    distFiles: [
        './thorax.js'
    ],
    build: false,
    watch: false
}

var layersTree = {
    id: 'LayersTree',
    srcDir: './external/GMXCommonComponents/LayersTree',
    distDir: './build',
    build: true
};

var layersDebugger = './external/GMXCommonComponents/LayersDebugger';

var gmxWidget = {
    id: 'GmxWidget',
    srcDir: './external/GMXCommonComponents/GmxWidget',
    build: false
};

var animationHelpers = {
    id: 'animationHelpers',
    srcDir: './external/GMXCommonComponents/animationHelpers',
    build: false
};

var sidebar = {
    id: 'IconSidebarControl',
    srcDir: './external/GMXCommonComponents/IconSidebarControl'
};

var scrollView = {
    id: 'ScrollView',
    srcDir: 'external/GMXCommonComponents/ScrollView',
    distDir: 'build',
    build: true
};

var storytellingControl = {
    id: 'StorytellingControl',
    srcDir: './external/GMXCommonComponents/StorytellingControl',
    build: false
};

var storytellingAccordeonControl =  {
    id: 'storytellingAccordeonControl',
    srcDir: './external/GMXCommonComponents/StorytellingAccordeonControl',
    build: false
};

var layersTreeWidget = {
    id: 'LayersTreeWidget',
    srcDir: './external/GMXCommonComponents/LayersTreeWidget',
    distDir: './build',
    build: true
};

var dateInterval = {
    id: 'DateInterval',
    srcDir: './external/GMXCommonComponents/DateInterval',
    build: false
};

var calendarWidget = {
    id: 'CalendarWidget',
    srcDir: './external/GMXCommonComponents/CalendarWidget',
    distDir: './build',
    build: true
};

var switchingCollectionWidget = {
    id: 'SwitchingCollectionWidget',
    srcDir: './external/GMXCommonComponents/SwitchingCollectionWidget',
    build: false
};

var bookmarksWidget = {
    id: 'BookmarksWidget',
    srcDir: './external/GMXCommonComponents/BookmarksWidget',
    distDir: './build',
    build: true
};

var stateManager = {
    id: 'StateManager',
    srcDir: './external/GMXCommonComponents/StateManager',
    build: false
};

var alertWidget = {
    id: 'AlertWidget',
    srcDir: './external/GMXCommonComponents/AlertWidget',
    distDir: './build',
    build: true
};

var shareIconControl = {
    id: 'ShareIconControl',
    srcDir: './external/GMXCommonComponents/ShareIconControl',
    distDir: 'build',
    build: true
};

var coreComponents = [
    jquery,
    jqueryui,
    handlebars,
    underscore,
    backbone,
    thorax,
    leaflet,
    leafletActiveArea,
    markercluster,
    heatmap,
    leafletGeomixer,
    tileLayerMercator,
    gmxBaseLayersManager,
    gmxControls,
    layersTree,
    layersDebugger,
    commonStyles,
    popover,
    translations,
    iconLayersControl,
    gmxIconLayers,
    componentsManager,
    utils,
    gmxWidget,
    animationHelpers,
    switchingCollectionWidget,
    sidebar,
    scrollView,
    layersTreeWidget,
    dateInterval,
    calendarWidget,
    bookmarksWidget,
    storytellingControl,
    storytellingAccordeonControl,
    stateManager,
    winnieCore
];

var virtualLayers = [{
    id: 'GmxVirtualTileLayer',
    srcDir: './external/GMXCommonComponents/GmxVirtualTileLayer',
    build: false
}, {
    id: 'leaflet-GIBS',
    srcDir: './external/leaflet-GIBS',
    distFiles: [
        './src/GeoMixerGIBSLayer.js',
        './src/GIBSLayer.js',
        './src/GIBSMetadata.js'
    ],
    build: false
}, {
    id: 'GMXPluginGFW',
    srcDir: './external/GMXPluginGFW',
    distFiles: [
        './src/L.GFWLayer.js',
        './src/L.GFWSlider.js',
        './src/L.GFWSlider.css',
        './src/GmxGFWLayer.js'
    ],
    build: false
}, {
    id: 'L.ImageOverlay.Pane',
    srcDir: './external/L.ImageOverlay.Pane',
    distDir: './src',
    build: false
}, {
    id: 'GMXPluginCadatsre',
    srcDir: './external/GMXPluginCadatsre',
    distFiles: [
        './GmxCadastreLayer.js',
        './L.Cadastre/src/L.Cadastre.js',
        './L.Cadastre/src/L.Cadastre.css',
        './L.Cadastre/src/L.Cadastre.Info.js'
    ],
    build: false
}];

require('./external/GMXBuilder')(gulp, {
    tempDir: './temp',
    distDir: './dist',
    watchExtensions: ['.js', '.css', '.html', '.less', '.svg'],
    distributionExtensions: ['.js', '.css', '.jpg', '.png', '.eot', '.ttf', '.woff', '.svg']
}, [{
    id: 'core',
    components: coreComponents
}, {
    id: 'viewer',
    htmlfile: 'html/viewer.html',
    components: [].concat(coreComponents, virtualLayers, [{
        id: 'viewer',
        srcDir: './viewer'
    }])
}, {
    id: 'index',
    htmlfile: 'html/index.html',
    components: [].concat(coreComponents, virtualLayers, [
        aceEditor,
        dropdownMenuWidget,
        alertWidget,
        shareIconControl,
        authManager, {
            id: 'editor',
            srcDir: './editor',
            distDir: './build',
            build: true
        }
    ])
}]);
<|endoftext|>


<commit_before>// Generic forms user page (Part A)

'use strict';

var generateSections      = require('./components/generate-form-sections')
, incompleteFormNav       = require('./components/incomplete-form-nav')
, _                       = require('mano').i18n.bind('Registration')
, errorMsg                = require('./_business-process-error-info').errorMsg;

exports._parent = require('./business-process-base');

exports['step-guide'] = { class: { 'step-form': true } };

exports.step = function () {
	exports._formsHeading();

	insert(errorMsg(this));

	div({ class: ['disabler-range', _if(not(eq(this.businessProcess._guideProgress, 1)),
				'disabler-active')], id: 'forms-disabler-range' },
		generateSections(this.businessProcess.dataForms.applicable, { viewContext: this }),
		div({ class: 'disabler' }));

	insert(_if(eq(this.businessProcess.dataForms._progress, 1),
		div({ class: 'user-next-step-button' },
			a({ href: '/documents/' }, _("Continue to next step"))),
		section({ class: 'section-warning' },
			incompleteFormNav(this.businessProcess.dataForms.applicable))));

};

exports._formsHeading = Function.prototype;
<commit_msg>Issue #773. Show incomplete forms list after user started to fill them.<commit_after>// Generic forms user page (Part A)

'use strict';

var generateSections      = require('./components/generate-form-sections')
, incompleteFormNav       = require('./components/incomplete-form-nav')
, _                       = require('mano').i18n.bind('Registration')
, errorMsg                = require('./_business-process-error-info').errorMsg;

exports._parent = require('./business-process-base');

exports['step-guide'] = { class: { 'step-form': true } };

exports.step = function () {
	exports._formsHeading();

	insert(errorMsg(this));

	div({ class: ['disabler-range', _if(not(eq(this.businessProcess._guideProgress, 1)),
				'disabler-active')], id: 'forms-disabler-range' },
		generateSections(this.businessProcess.dataForms.applicable, { viewContext: this }),
		div({ class: 'disabler' }));

	insert(_if(eq(this.businessProcess.dataForms._progress, 1),
		div({ class: 'user-next-step-button' },
			a({ href: '/documents/' }, _("Continue to next step"))),
		_if(gt(this.businessProcess.dataForms._progress, 0), section({ class: 'section-warning' },
			incompleteFormNav(this.businessProcess.dataForms.applicable)))
		));

};

exports._formsHeading = Function.prototype;
<|endoftext|>


<commit_before>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');
var MatrixClientPeg = require("matrix-react-sdk/lib/MatrixClientPeg");

module.exports = React.createClass({
    displayName: 'RightPanel',

    Phase : {
        MemberList: 'MemberList',
        FileList: 'FileList',
        MemberInfo: 'MemberInfo',
    },

    componentWillMount: function() {
        this.dispatcherRef = dis.register(this.onAction);
        var cli = MatrixClientPeg.get();
        cli.on("RoomState.members", this.onRoomStateMember);
    },

    componentWillUnmount: function() {
        dis.unregister(this.dispatcherRef);
        if (MatrixClientPeg.get()) {
            MatrixClientPeg.get().removeListener("RoomState.members", this.onRoomStateMember);
        }
    },

    getInitialState: function() {
        return {
            phase : this.Phase.MemberList
        }
    },

    onMemberListButtonClick: function() {
        if (this.props.collapsed) {
            this.setState({ phase: this.Phase.MemberList });
            dis.dispatch({
                action: 'show_right_panel',
            });
        }
        else {
            dis.dispatch({
                action: 'hide_right_panel',
            });
        }
    },

    onRoomStateMember: function(ev, state, member) {
        // redraw the badge on the membership list
        if (this.state.phase == this.Phase.MemberList && member.roomId === this.props.roomId) {
            this.forceUpdate();
        }
        else if (this.state.phase === this.Phase.MemberInfo && member.roomId === this.props.roomId &&
                member.userId === this.state.member.userId) {
            // refresh the member info (e.g. new power level)
            this.forceUpdate();
        }
    },

    onAction: function(payload) {
        if (payload.action === "view_user") {
            if (payload.member) {
                this.setState({
                    phase: this.Phase.MemberInfo,
                    member: payload.member,
                });
            }
            else {
                this.setState({
                    phase: this.Phase.MemberList
                });
            }
        }
        if (payload.action === "view_room") {
            if (this.state.phase === this.Phase.MemberInfo) {
                this.setState({
                    phase: this.Phase.MemberList
                });
            }
        }
    },

    render: function() {
        var MemberList = sdk.getComponent('rooms.MemberList');
        var buttonGroup;
        var panel;

        var filesHighlight;
        var membersHighlight;
        if (!this.props.collapsed) {
            if (this.state.phase == this.Phase.MemberList || this.state.phase === this.Phase.MemberInfo) {
                membersHighlight =

;
            }
            else if (this.state.phase == this.Phase.FileList) {
                filesHighlight =

;
            }
        }

        var membersBadge;
        if ((this.state.phase == this.Phase.MemberList || this.state.phase === this.Phase.MemberInfo) && this.props.roomId) {
            var cli = MatrixClientPeg.get();
            var room = cli.getRoom(this.props.roomId);
            if (room) {
                membersBadge =
{ room.getJoinedMembers().length }
;
            }
        }

        if (this.props.roomId) {
            buttonGroup =

                            <object type="image/svg+xml" data="img/members.svg" width="17" height="22" title="Members"/>
                            { membersBadge }
                            { membersHighlight }

                            <object type="image/svg+xml" data="img/files.svg" width="17" height="22" title="Files"/>
                            { filesHighlight }

;

            if (!this.props.collapsed) {
                if(this.state.phase == this.Phase.MemberList) {
                    panel = <MemberList roomId={this.props.roomId} key={this.props.roomId} />
                }
                else if(this.state.phase == this.Phase.MemberInfo) {
                    var MemberInfo = sdk.getComponent('rooms.MemberInfo');
                    panel = <MemberInfo roomId={this.props.roomId} member={this.state.member} key={this.props.roomId} />
                }
            }

        }

        var classes = "mx_RightPanel";
        if (this.props.collapsed) {
            classes += " collapsed";
        }

        return (

                    { buttonGroup }

                { panel }

        );
    }
});

<commit_msg>move title attributes to the div<commit_after>/*
Copyright 2015 OpenMarket Ltd

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

'use strict';

var React = require('react');
var sdk = require('matrix-react-sdk')
var dis = require('matrix-react-sdk/lib/dispatcher');
var MatrixClientPeg = require("matrix-react-sdk/lib/MatrixClientPeg");

module.exports = React.createClass({
    displayName: 'RightPanel',

    Phase : {
        MemberList: 'MemberList',
        FileList: 'FileList',
        MemberInfo: 'MemberInfo',
    },

    componentWillMount: function() {
        this.dispatcherRef = dis.register(this.onAction);
        var cli = MatrixClientPeg.get();
        cli.on("RoomState.members", this.onRoomStateMember);
    },

    componentWillUnmount: function() {
        dis.unregister(this.dispatcherRef);
        if (MatrixClientPeg.get()) {
            MatrixClientPeg.get().removeListener("RoomState.members", this.onRoomStateMember);
        }
    },

    getInitialState: function() {
        return {
            phase : this.Phase.MemberList
        }
    },

    onMemberListButtonClick: function() {
        if (this.props.collapsed) {
            this.setState({ phase: this.Phase.MemberList });
            dis.dispatch({
                action: 'show_right_panel',
            });
        }
        else {
            dis.dispatch({
                action: 'hide_right_panel',
            });
        }
    },

    onRoomStateMember: function(ev, state, member) {
        // redraw the badge on the membership list
        if (this.state.phase == this.Phase.MemberList && member.roomId === this.props.roomId) {
            this.forceUpdate();
        }
        else if (this.state.phase === this.Phase.MemberInfo && member.roomId === this.props.roomId &&
                member.userId === this.state.member.userId) {
            // refresh the member info (e.g. new power level)
            this.forceUpdate();
        }
    },

    onAction: function(payload) {
        if (payload.action === "view_user") {
            if (payload.member) {
                this.setState({
                    phase: this.Phase.MemberInfo,
                    member: payload.member,
                });
            }
            else {
                this.setState({
                    phase: this.Phase.MemberList
                });
            }
        }
        if (payload.action === "view_room") {
            if (this.state.phase === this.Phase.MemberInfo) {
                this.setState({
                    phase: this.Phase.MemberList
                });
            }
        }
    },

    render: function() {
        var MemberList = sdk.getComponent('rooms.MemberList');
        var buttonGroup;
        var panel;

        var filesHighlight;
        var membersHighlight;
        if (!this.props.collapsed) {
            if (this.state.phase == this.Phase.MemberList || this.state.phase === this.Phase.MemberInfo) {
                membersHighlight =

;
            }
            else if (this.state.phase == this.Phase.FileList) {
                filesHighlight =

;
            }
        }

        var membersBadge;
        if ((this.state.phase == this.Phase.MemberList || this.state.phase === this.Phase.MemberInfo) && this.props.roomId) {
            var cli = MatrixClientPeg.get();
            var room = cli.getRoom(this.props.roomId);
            if (room) {
                membersBadge =
{ room.getJoinedMembers().length }
;
            }
        }

        if (this.props.roomId) {
            buttonGroup =

                            <object type="image/svg+xml" data="img/members.svg" width="17" height="22"/>
                            { membersBadge }
                            { membersHighlight }

                            <object type="image/svg+xml" data="img/files.svg" width="17" height="22"/>
                            { filesHighlight }

;

            if (!this.props.collapsed) {
                if(this.state.phase == this.Phase.MemberList) {
                    panel = <MemberList roomId={this.props.roomId} key={this.props.roomId} />
                }
                else if(this.state.phase == this.Phase.MemberInfo) {
                    var MemberInfo = sdk.getComponent('rooms.MemberInfo');
                    panel = <MemberInfo roomId={this.props.roomId} member={this.state.member} key={this.props.roomId} />
                }
            }

        }

        var classes = "mx_RightPanel";
        if (this.props.collapsed) {
            classes += " collapsed";
        }

        return (

                    { buttonGroup }

                { panel }

        );
    }
});

<|endoftext|>


<commit_before>import React from 'react';
import LinearGradient from 'react-native-linear-gradient';
import styled from 'styled-components/native';
import { colors, fonts } from 'config';
import { InlineLabel } from 'components';
import { FlatList, View } from 'react-native';

type Props = {
  title: string,
  topics: Array,
};

const styles = {
  contentContainerStyle: {
    paddingLeft: 13,
    paddingRight: 13,
  },
  scrollGradient: {
    position: 'absolute',
    width: 15,
    height: 30,
  },
};

const TopicsListContainer = styled.View`
  margin-top: 30;
`;

const TopicsListLabel = styled.Text`
  color: ${colors.black};
  ${{ ...fonts.fontPrimaryBold }};
  margin-bottom: 10;
  padding-left: 15;
`;

export const TopicsList = ({ title, topics }: Props) => (
  <TopicsListContainer>
    <TopicsListLabel>{title}</TopicsListLabel>
    <View>
      {topics.length > 0 && (
        <FlatList
          contentContainerStyle={styles.contentContainerStyle}
          data={topics}
          showsHorizontalScrollIndicator={false}
          renderItem={({ item }) => (
            <InlineLabel
              label={{ name: item, color: colors.topicLightBlue.slice(1) }}
            />
          )}
          keyExtractor={item => item}
          horizontal
        />
      )}
      <LinearGradient
        style={[styles.scrollGradient, { left: 0 }]}
        colors={['white', 'rgba(255, 255, 255, 0)']}
        start={{ x: 0, y: 0.5 }}
        end={{ x: 1, y: 0.5 }}
      />

      <LinearGradient
        style={[styles.scrollGradient, { right: 0 }]}
        colors={['rgba(255, 255, 255, 0)', 'white']}
        start={{ x: 0, y: 0.5 }}
        end={{ x: 1, y: 0.5 }}
      />
    </View>
  </TopicsListContainer>
);
<commit_msg>fix(*): Same import entry for styled-components<commit_after>import React from 'react';
import LinearGradient from 'react-native-linear-gradient';
import styled from 'styled-components';
import { colors, fonts } from 'config';
import { InlineLabel } from 'components';
import { FlatList, View } from 'react-native';

type Props = {
  title: string,
  topics: Array,
};

const styles = {
  contentContainerStyle: {
    paddingLeft: 13,
    paddingRight: 13,
  },
  scrollGradient: {
    position: 'absolute',
    width: 15,
    height: 30,
  },
};

const TopicsListContainer = styled.View`
  margin-top: 30;
`;

const TopicsListLabel = styled.Text`
  color: ${colors.black};
  ${{ ...fonts.fontPrimaryBold }};
  margin-bottom: 10;
  padding-left: 15;
`;

export const TopicsList = ({ title, topics }: Props) => (
  <TopicsListContainer>
    <TopicsListLabel>{title}</TopicsListLabel>
    <View>
      {topics.length > 0 && (
        <FlatList
          contentContainerStyle={styles.contentContainerStyle}
          data={topics}
          showsHorizontalScrollIndicator={false}
          renderItem={({ item }) => (
            <InlineLabel
              label={{ name: item, color: colors.topicLightBlue.slice(1) }}
            />
          )}
          keyExtractor={item => item}
          horizontal
        />
      )}
      <LinearGradient
        style={[styles.scrollGradient, { left: 0 }]}
        colors={['white', 'rgba(255, 255, 255, 0)']}
        start={{ x: 0, y: 0.5 }}
        end={{ x: 1, y: 0.5 }}
      />

      <LinearGradient
        style={[styles.scrollGradient, { right: 0 }]}
        colors={['rgba(255, 255, 255, 0)', 'white']}
        start={{ x: 0, y: 0.5 }}
        end={{ x: 1, y: 0.5 }}
      />
    </View>
  </TopicsListContainer>
);
<|endoftext|>


<commit_before>///* jshint camelcase:false */
//var gulp = require('gulp');
//var browserSync = require('browser-sync');
//var del = require('del');
//var glob = require('glob');

var gulp = require('gulp-param')(require('gulp'), process.argv),
  mocha = require("gulp-mocha"),
  istanbul = require('gulp-istanbul'),
  bench = require('gulp-bench'),
  uglify = require('gulp-uglify'),
  rimraf = require('gulp-rimraf'),
  bump = require('gulp-bump'),
  replace = require('gulp-replace'),
  rename = require('gulp-rename'),
  browserify = require('gulp-browserify'),
  SRC = 'index.js',
  DEST = 'dist',
  SRC_COMPILED = 'safeaccessors.js',
  MIN_FILE = 'safeaccessors.min.js',
  VERSION_FILES = ['./package.json', './component.json', './bower.json'];
VERSION_FILES_JS = [SRC, 'package.js'];

gulp.task('test', ['browserify'], function(cov) {
  var reporters = ['html'];

  if (cov) {
    reporters.push('text');
  } else {
    reporters.push('text-summary');
  }

  return gulp.src(['safeGet.js', 'safeCall.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire())
    .on('finish', function () {
      return gulp.src(['test/specs/*.js'])
        .pipe(
          mocha({
            globals: '*',
            reporter: 'dot'
          })
        )
        .pipe(istanbul.writeReports({
          reporters: reporters
        }));
    });
});

gulp.task('bench', ['browserify'], function(func) {
  func = func || '*';
  return gulp.src('bench/'+ func + '.js')
    .pipe(bench());
});

gulp.task('browserify', function() {
  return gulp.src(['index.js'])
    .pipe(browserify())
    .pipe(rename('safeaccessors.js'))
    .pipe(gulp.dest(DEST));
});

gulp.task('clean', function() {
  return gulp.src(DEST)
    .pipe(rimraf());
});

gulp.task('bump-in-js', function(semver) {
  return gulp.src(VERSION_FILES_JS)
    .pipe(replace(/(version?\s?=?\:?\s\')([\d\.]*)\'/gi, '$1' + semver + "'"))
    .pipe(gulp.dest('./'));
});

// usage: gulp bump -s <% Version %>
// usage: gulp bump --semver <% Version %>
gulp.task('bump', ['bump-in-js'], function(semver) {
  if (typeof semver !== 'string' || semver.length <= 0) {
    console.error('pass a new version `gulp bump --semver 2.4.1`');
    process.exit(1);
  }

  return gulp.src(VERSION_FILES)
    .pipe(bump({
      version: semver
    }))
    .pipe(gulp.dest('./'));
});

gulp.task('build', ['test', 'clean'], function() {
  gulp.src(DEST + '/' + SRC_COMPILED)
    .pipe(uglify())
    .pipe(rename(MIN_FILE))
    .pipe(gulp.dest(DEST));
});
<commit_msg>Updated tests to include isVoid<commit_after>///* jshint camelcase:false */
//var gulp = require('gulp');
//var browserSync = require('browser-sync');
//var del = require('del');
//var glob = require('glob');

var gulp = require('gulp-param')(require('gulp'), process.argv),
  mocha = require("gulp-mocha"),
  istanbul = require('gulp-istanbul'),
  bench = require('gulp-bench'),
  uglify = require('gulp-uglify'),
  rimraf = require('gulp-rimraf'),
  bump = require('gulp-bump'),
  replace = require('gulp-replace'),
  rename = require('gulp-rename'),
  browserify = require('gulp-browserify'),
  SRC = 'index.js',
  DEST = 'dist',
  SRC_COMPILED = 'safeaccessors.js',
  MIN_FILE = 'safeaccessors.min.js',
  VERSION_FILES = ['./package.json', './component.json', './bower.json'];
VERSION_FILES_JS = [SRC, 'package.js'];

gulp.task('test', ['browserify'], function(cov) {
  var reporters = ['html'];

  if (cov) {
    reporters.push('text');
  } else {
    reporters.push('text-summary');
  }

  return gulp.src(['isVoid.js', 'safeGet.js', 'safeCall.js'])
    .pipe(istanbul())
    .pipe(istanbul.hookRequire())
    .on('finish', function () {
      return gulp.src(['test/specs/*.js'])
        .pipe(
          mocha({
            globals: '*',
            reporter: 'dot'
          })
        )
        .pipe(istanbul.writeReports({
          reporters: reporters
        }));
    });
});

gulp.task('bench', ['browserify'], function(func) {
  func = func || '*';
  return gulp.src('bench/'+ func + '.js')
    .pipe(bench());
});

gulp.task('browserify', function() {
  return gulp.src(['index.js'])
    .pipe(browserify())
    .pipe(rename('safeaccessors.js'))
    .pipe(gulp.dest(DEST));
});

gulp.task('clean', function() {
  return gulp.src(DEST)
    .pipe(rimraf());
});

gulp.task('bump-in-js', function(semver) {
  return gulp.src(VERSION_FILES_JS)
    .pipe(replace(/(version?\s?=?\:?\s\')([\d\.]*)\'/gi, '$1' + semver + "'"))
    .pipe(gulp.dest('./'));
});

// usage: gulp bump -s <% Version %>
// usage: gulp bump --semver <% Version %>
gulp.task('bump', ['bump-in-js'], function(semver) {
  if (typeof semver !== 'string' || semver.length <= 0) {
    console.error('pass a new version `gulp bump --semver 2.4.1`');
    process.exit(1);
  }

  return gulp.src(VERSION_FILES)
    .pipe(bump({
      version: semver
    }))
    .pipe(gulp.dest('./'));
});

gulp.task('build', ['test', 'clean'], function() {
  gulp.src(DEST + '/' + SRC_COMPILED)
    .pipe(uglify())
    .pipe(rename(MIN_FILE))
    .pipe(gulp.dest(DEST));
});
<|endoftext|>


<commit_before>var CounterForm = {};

$(function(){
    CounterForm.initTypeClick();
    CounterForm.initWeekdayClick();
    CounterForm.initDatePicker();
    CounterForm.initBtnClick();
});

CounterForm.initTypeClick = function() {
    $('#add-counter-modal li.type-select-item').click(function(){
        var selectId = $(this).attr('id');

        if(selectId == 'type-select-item-daily') {
            CounterForm.setType('daily');
        }
        else if(selectId == 'type-select-item-weekly') {
            CounterForm.setType('weekly');
        }
    });
}

CounterForm.initWeekdayClick = function() {
    $('#add-counter-modal #weekly-day-select li').click(function() {
        CounterForm.toggleWeekday($(this).text());
    });
}

CounterForm.resetForAdd = function() {
    this.setMode('add');
    this.setTitle('New Counter')
    this.setLabel('');
    this.setSummary('');
    this.setType('daily');
    this.setEvery('1');
    this.setWeekdays(['mon']);
    this.setPublic(true);
    $('#new-counter-more').collapse('hide');
}

CounterForm.initBtnClick = function() {
    $('#add-counter-modal .modal-footer button').click(function() {
        console.log(counterAddUrl);
        console.log($('#counter-form').serialize());
        var mode = CounterForm.getMode();

        if(mode == 'add') {
            $.ajax({
                type: 'POST',
                url: counterAddUrl,
                data: $('#counter-form').serialize(),
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log('Counter add ' + textStatus + ' ' + errorThrown);
                },
                success: function(data, textStatus, jqXHR) {
                    $('#add-counter-modal').modal('hide');
                    console.log(data);
                    location.reload();
                }
            });
        }
        else if(mode == 'update') {
            console.log($('#counter-form').serialize());
            $.ajax({
                type: 'POST',
                url: counterUpdateUrl,
                data: $('#counter-form').serialize(),
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log('Counter update error ' + textStatus + ' ' + errorThrown);
                },
                success: function(data, textStatus, jqXHR) {
                    $('#add-counter-modal').modal('hide');
                    console.log('counter update success');
                    //location.reload();
                }
            });
        }
    });
}

CounterForm.setCounterId = function(counterId) {
    $('#add-counter-modal input#counter-counterid').val(counterId);
}

CounterForm.setLabel = function(text) {
    $('#add-counter-modal input#counter-label').val(text);
}

CounterForm.setSummary = function(text) {
    $('#add-counter-modal textarea#counter-summary').val(text);
}

/**
 * Type is 'daily' or 'weekly'.
 */
CounterForm.setType = function(type) {
    $('#add-counter-modal li.type-select-item').removeClass('active');

    if(type.toLowerCase() == 'daily') {
        $('#add-counter-modal input#counter-type').val('daily');
        $('#add-counter-modal #type-select-item-daily').addClass('active');
        $('#add-counter-modal #every-label').text('day');
        $('#add-counter-modal #weekly-day-select').css('display', 'none');
    }
    else {
        $('#add-counter-modal input#counter-type').val('weekly');
        $('#add-counter-modal #type-select-item-weekly').addClass('active');
        $('#add-counter-modal #every-label').text('week');
        $('#add-counter-modal #weekly-day-select').css('display', '');
    }
}

/**
 * Gets the type that is current selected.
 * @return 'daily' or 'weekly'
 */
CounterForm.getType = function() {
    if($('#add-counter-modal li#type-select-item-daily').hasClass('active'))
        return 'daily';
    if($('#add-counter-modal li#type-select-item-weekly').hasClass('active'))
        return 'weekly';
}

/**
 * Sets the value of the 'every' input field.
 * $param period is an integer. For example when type is 'daily' and period is 2, this mean 2 days.
 *        this also apply to weeks. If this parameter is not numeric, no effect.
 */
CounterForm.setEvery = function(period) {
    if(!$.isNumeric(period) ||
        period < 1 ||
        (this.getType() == 'daily' && period > 7)
    )
        return;
    $('#add-counter-modal input#counter-every').val(Math.floor(period));
}

/**
 * Sets which days are selected on the form.
 * @param weekdays array containing;
 *     'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'
 */
CounterForm.setWeekdays = function(weekdays) {
    $('#add-counter-modal #weekly-day-select input').val(0);
    $('#add-counter-modal #weekly-day-select li').removeClass('active');

    for(i = 0; i < weekdays.length; i++) {
        this.addWeekday(weekdays[i]);
    }
}

/**
 * Adds a weekday to selections.
 * @param day is a string which should be one of: 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'
 */
CounterForm.addWeekday = function(day) {
    var num   = this.weekdayNum(day);
    var input = '#add-counter-modal #weekly-day-select input:eq(' + (num - 1) + ')';
    var li    = '#add-counter-modal #weekly-day-select li:nth-child(' + num + ')';
    $(input).val(1);
    $(li).addClass('active');
}

CounterForm.toggleWeekday = function(day) {
    var num   = this.weekdayNum(day);
    var input = '#add-counter-modal #weekly-day-select input:eq(' + (num - 1) + ')';
    var li    = '#add-counter-modal #weekly-day-select li:nth-child(' + num + ')';
    $(input).val($(input).val() == 0 ? 1 : 0);
    $(li).toggleClass('active');
}

/**
 * Return integer representation of a weekday where mon = 1, tue = 2, ..., sun = 7.
 * If name is not valid, undefined is returned.
 */
CounterForm.weekdayNum = function(name) {
    switch(name.toLowerCase()) {
        case 'mon': return 1;
        case 'tue': return 2;
        case 'wed': return 3;
        case 'thu': return 4;
        case 'fri': return 5;
        case 'sat': return 6;
        case 'sun': return 7;
    }
}

CounterForm.setPublic = function(public) {
    $('#add-counter-modal input#counter-public').prop('checked', public);
}

/**
 * mode should be 'add' or 'update'
 */
CounterForm.setMode = function(mode) {
    $('#add-counter-modal').attr('mode', mode.toLowerCase());
}

/**
 * Returns either 'add' or 'update'
 */
CounterForm.getMode = function() {
    return $('#add-counter-modal').attr('mode');
}

CounterForm.setTitle = function(title) {
    $('#add-counter-modal .modal-title').html('' + title + '');
}

var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dateInputSel = '#counter-startdate';

CounterForm.initDatePicker = function() {
    $(dateInputSel).datepicker({dateFormat: 'MM d, yy'});
    var now = new Date();
    $(dateInputSel).val(monthNames[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear());
}

CounterForm.setStartDate = function(dateStr) {
    var date = new Date(dateStr);
    $(dateInputSel).datepicker('setDate', date);
}

CounterForm.setTimeZone = function(name) {
    $('#add-counter-modal select#counter-timezone option').prop('selected', false);
    $('#add-counter-modal select#counter-timezone option[value="' + name + '"]').prop('selected', true);
}

/**
 * Shows the counter form modal.
 */
CounterForm.show = function(name) {
    $('#add-counter-modal').modal('show');
}<commit_msg>MonthNames array is already defined in cal.js<commit_after>var CounterForm = {};

$(function(){
    CounterForm.initTypeClick();
    CounterForm.initWeekdayClick();
    CounterForm.initDatePicker();
    CounterForm.initBtnClick();
});

CounterForm.initTypeClick = function() {
    $('#add-counter-modal li.type-select-item').click(function(){
        var selectId = $(this).attr('id');

        if(selectId == 'type-select-item-daily') {
            CounterForm.setType('daily');
        }
        else if(selectId == 'type-select-item-weekly') {
            CounterForm.setType('weekly');
        }
    });
}

CounterForm.initWeekdayClick = function() {
    $('#add-counter-modal #weekly-day-select li').click(function() {
        CounterForm.toggleWeekday($(this).text());
    });
}

CounterForm.resetForAdd = function() {
    this.setMode('add');
    this.setTitle('New Counter')
    this.setLabel('');
    this.setSummary('');
    this.setType('daily');
    this.setEvery('1');
    this.setWeekdays(['mon']);
    this.setPublic(true);
    $('#new-counter-more').collapse('hide');
}

CounterForm.initBtnClick = function() {
    $('#add-counter-modal .modal-footer button').click(function() {
        console.log(counterAddUrl);
        console.log($('#counter-form').serialize());
        var mode = CounterForm.getMode();

        if(mode == 'add') {
            $.ajax({
                type: 'POST',
                url: counterAddUrl,
                data: $('#counter-form').serialize(),
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log('Counter add ' + textStatus + ' ' + errorThrown);
                },
                success: function(data, textStatus, jqXHR) {
                    $('#add-counter-modal').modal('hide');
                    console.log(data);
                    location.reload();
                }
            });
        }
        else if(mode == 'update') {
            console.log($('#counter-form').serialize());
            $.ajax({
                type: 'POST',
                url: counterUpdateUrl,
                data: $('#counter-form').serialize(),
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log('Counter update error ' + textStatus + ' ' + errorThrown);
                },
                success: function(data, textStatus, jqXHR) {
                    $('#add-counter-modal').modal('hide');
                    console.log('counter update success');
                    //location.reload();
                }
            });
        }
    });
}

CounterForm.setCounterId = function(counterId) {
    $('#add-counter-modal input#counter-counterid').val(counterId);
}

CounterForm.setLabel = function(text) {
    $('#add-counter-modal input#counter-label').val(text);
}

CounterForm.setSummary = function(text) {
    $('#add-counter-modal textarea#counter-summary').val(text);
}

/**
 * Type is 'daily' or 'weekly'.
 */
CounterForm.setType = function(type) {
    $('#add-counter-modal li.type-select-item').removeClass('active');

    if(type.toLowerCase() == 'daily') {
        $('#add-counter-modal input#counter-type').val('daily');
        $('#add-counter-modal #type-select-item-daily').addClass('active');
        $('#add-counter-modal #every-label').text('day');
        $('#add-counter-modal #weekly-day-select').css('display', 'none');
    }
    else {
        $('#add-counter-modal input#counter-type').val('weekly');
        $('#add-counter-modal #type-select-item-weekly').addClass('active');
        $('#add-counter-modal #every-label').text('week');
        $('#add-counter-modal #weekly-day-select').css('display', '');
    }
}

/**
 * Gets the type that is current selected.
 * @return 'daily' or 'weekly'
 */
CounterForm.getType = function() {
    if($('#add-counter-modal li#type-select-item-daily').hasClass('active'))
        return 'daily';
    if($('#add-counter-modal li#type-select-item-weekly').hasClass('active'))
        return 'weekly';
}

/**
 * Sets the value of the 'every' input field.
 * $param period is an integer. For example when type is 'daily' and period is 2, this mean 2 days.
 *        this also apply to weeks. If this parameter is not numeric, no effect.
 */
CounterForm.setEvery = function(period) {
    if(!$.isNumeric(period) ||
        period < 1 ||
        (this.getType() == 'daily' && period > 7)
    )
        return;
    $('#add-counter-modal input#counter-every').val(Math.floor(period));
}

/**
 * Sets which days are selected on the form.
 * @param weekdays array containing;
 *     'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'
 */
CounterForm.setWeekdays = function(weekdays) {
    $('#add-counter-modal #weekly-day-select input').val(0);
    $('#add-counter-modal #weekly-day-select li').removeClass('active');

    for(i = 0; i < weekdays.length; i++) {
        this.addWeekday(weekdays[i]);
    }
}

/**
 * Adds a weekday to selections.
 * @param day is a string which should be one of: 'mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'
 */
CounterForm.addWeekday = function(day) {
    var num   = this.weekdayNum(day);
    var input = '#add-counter-modal #weekly-day-select input:eq(' + (num - 1) + ')';
    var li    = '#add-counter-modal #weekly-day-select li:nth-child(' + num + ')';
    $(input).val(1);
    $(li).addClass('active');
}

CounterForm.toggleWeekday = function(day) {
    var num   = this.weekdayNum(day);
    var input = '#add-counter-modal #weekly-day-select input:eq(' + (num - 1) + ')';
    var li    = '#add-counter-modal #weekly-day-select li:nth-child(' + num + ')';
    $(input).val($(input).val() == 0 ? 1 : 0);
    $(li).toggleClass('active');
}

/**
 * Return integer representation of a weekday where mon = 1, tue = 2, ..., sun = 7.
 * If name is not valid, undefined is returned.
 */
CounterForm.weekdayNum = function(name) {
    switch(name.toLowerCase()) {
        case 'mon': return 1;
        case 'tue': return 2;
        case 'wed': return 3;
        case 'thu': return 4;
        case 'fri': return 5;
        case 'sat': return 6;
        case 'sun': return 7;
    }
}

CounterForm.setPublic = function(public) {
    $('#add-counter-modal input#counter-public').prop('checked', public);
}

/**
 * mode should be 'add' or 'update'
 */
CounterForm.setMode = function(mode) {
    $('#add-counter-modal').attr('mode', mode.toLowerCase());
}

/**
 * Returns either 'add' or 'update'
 */
CounterForm.getMode = function() {
    return $('#add-counter-modal').attr('mode');
}

CounterForm.setTitle = function(title) {
    $('#add-counter-modal .modal-title').html('' + title + '');
}

//var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dateInputSel = '#counter-startdate';

CounterForm.initDatePicker = function() {
    $(dateInputSel).datepicker({dateFormat: 'MM d, yy'});
    var now = new Date();
    $(dateInputSel).val(monthNames[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear());
}

CounterForm.setStartDate = function(dateStr) {
    var date = new Date(dateStr);
    $(dateInputSel).datepicker('setDate', date);
}

CounterForm.setTimeZone = function(name) {
    $('#add-counter-modal select#counter-timezone option').prop('selected', false);
    $('#add-counter-modal select#counter-timezone option[value="' + name + '"]').prop('selected', true);
}

/**
 * Shows the counter form modal.
 */
CounterForm.show = function(name) {
    $('#add-counter-modal').modal('show');
}<|endoftext|>