<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const ImmutableComponent = require('../../../js/components/immutableComponent')
const Dialog = require('../../../js/components/dialog')
const Button = require('../../../js/components/button')
const SwitchControl = require('../../../js/components/switchControl')
const windowActions = require('../../../js/actions/windowActions')
const appActions = require('../../../js/actions/appActions')

class ImportBrowserDataPanel extends ImmutableComponent {
  constructor () {
    super()
    this.onToggleHistory = this.onToggleSetting.bind(this, 'history')
    this.onToggleFavorites = this.onToggleSetting.bind(this, 'favorites')
    this.onToggleMergeFavorites = this.onToggleSetting.bind(this, 'mergeFavorites')
    this.onToggleCookies = this.onToggleSetting.bind(this, 'cookies')
    this.onImport = this.onImport.bind(this)
    this.onChange = this.onChange.bind(this)
  }
  onToggleSetting (setting, e) {
    if (setting === 'favorites') {
      this.props.importBrowserDataSelected =
        this.props.importBrowserDataSelected.set('mergeFavorites', e.target.value)
    }
    windowActions.setImportBrowserDataSelected(this.props.importBrowserDataSelected.set(setting, e.target.value))
  }
  get browserData () {
    let index = this.props.importBrowserDataSelected.get('index')
    if (index === undefined) {
      index = '0'
    }
    return this.props.importBrowserDataDetail.get(index)
  }
  get supportHistory () {
    let browserData = this.browserData
    if (browserData === undefined) {
      return false
    }
    return browserData.get('history')
  }
  get supportFavorites () {
    let browserData = this.browserData
    if (browserData === undefined) {
      return false
    }
    return browserData.get('favorites')
  }
  get supportCookies () {
    let browserData = this.browserData
    if (browserData === undefined) {
      return false
    }
    return browserData.get('cookies')
  }
  onImport () {
    let index = this.props.importBrowserDataSelected.get('index')
    if (index === undefined) {
      this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('index', '0')
    }
    let browserData = this.browserData
    if (browserData !== undefined) {
      let type = browserData.get('type')
      this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('type', type)
    }
    appActions.importBrowserData(this.props.importBrowserDataSelected)
    this.props.onHide()
  }
  onChange (e) {
    windowActions.setImportBrowserDataSelected(
      this.props.importBrowserDataSelected.set('index', e.target.value))
  }
  get selectedBrowser () {
    let index = this.props.importBrowserDataSelected.get('index')
    return index !== undefined ? index : '0'
  }
  render () {
    var browsers = []
    if (this.props.importBrowserDataDetail !== undefined) {
      this.props.importBrowserDataDetail.toJS().forEach((browser) => {
        browsers.push(<option value={browser.index}>{browser.name}</option>)
      })
    }
    return <Dialog onHide={this.props.onHide} className='importBrowserDataPanel' isClickDismiss>

 e.stopPropagation()}>

          <select value={this.selectedBrowser}
            onChange={this.onChange} >
            {browsers}
          </select>
          <SwitchControl rightl10nId='browserHistory' checkedOn={this.props.importBrowserDataSelected.get('history')}
            onClick={this.onToggleHistory} disabled={!this.supportHistory} />
          <SwitchControl rightl10nId='favoritesOrBookmarks' checkedOn={this.props.importBrowserDataSelected.get('favorites')}
            onClick={this.onToggleFavorites} disabled={!this.supportFavorites} />

            <SwitchControl rightl10nId='mergeIntoBookmarksToolbar'
              checkedOn={this.props.importBrowserDataSelected.get('mergeFavorites')}
              onClick={this.onToggleMergeFavorites} disabled={!this.props.importBrowserDataSelected.get('favorites')} />

          <SwitchControl rightl10nId='cookies' checkedOn={this.props.importBrowserDataSelected.get('cookies')}
            onClick={this.onToggleCookies} disabled={!this.supportCookies} />

          <Button l10nId='cancel' className='secondaryAltButton' onClick={this.props.onHide} />
          <Button l10nId='import' className='primaryButton' onClick={this.onImport} />

    </Dialog>
  }
}

module.exports = ImportBrowserDataPanel
<commit_msg>change import dialog switch default from OFF to ON for available data types<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

const React = require('react')
const ImmutableComponent = require('../../../js/components/immutableComponent')
const Dialog = require('../../../js/components/dialog')
const Button = require('../../../js/components/button')
const SwitchControl = require('../../../js/components/switchControl')
const windowActions = require('../../../js/actions/windowActions')
const appActions = require('../../../js/actions/appActions')

class ImportBrowserDataPanel extends ImmutableComponent {
  constructor () {
    super()
    this.onToggleHistory = this.onToggleSetting.bind(this, 'history')
    this.onToggleFavorites = this.onToggleSetting.bind(this, 'favorites')
    this.onToggleMergeFavorites = this.onToggleSetting.bind(this, 'mergeFavorites')
    this.onToggleCookies = this.onToggleSetting.bind(this, 'cookies')
    this.onImport = this.onImport.bind(this)
    this.onChange = this.onChange.bind(this)
  }
  onToggleSetting (setting, e) {
    if (setting === 'favorites') {
      this.props.importBrowserDataSelected =
        this.props.importBrowserDataSelected.set('mergeFavorites', e.target.value)
    }
    windowActions.setImportBrowserDataSelected(this.props.importBrowserDataSelected.set(setting, e.target.value))
  }
  get browserData () {
    let index = this.props.importBrowserDataSelected.get('index')
    if (index === undefined) {
      index = '0'
    }
    return this.props.importBrowserDataDetail.get(index)
  }
  get supportHistory () {
    let browserData = this.browserData
    if (browserData === undefined) {
      return false
    }
    return browserData.get('history')
  }
  get supportFavorites () {
    let browserData = this.browserData
    if (browserData === undefined) {
      return false
    }
    return browserData.get('favorites')
  }
  get supportCookies () {
    let browserData = this.browserData
    if (browserData === undefined) {
      return false
    }
    return browserData.get('cookies')
  }
  onImport () {
    let index = this.props.importBrowserDataSelected.get('index')
    if (index === undefined) {
      this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('index', '0')
    }
    let browserData = this.browserData
    if (browserData !== undefined) {
      let type = browserData.get('type')
      this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('type', type)
    }
    appActions.importBrowserData(this.props.importBrowserDataSelected)
    this.props.onHide()
  }
  onChange (e) {
    this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('index', e.target.value)
    this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('history', false)
    this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('favorites', false)
    this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('mergeFavorites', false)
    this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('cookies', false)
    let importBrowserDataSelected = this.props.importBrowserDataSelected
    if (this.supportHistory) {
      importBrowserDataSelected = importBrowserDataSelected.set('history', true)
    }
    if (this.supportFavorites) {
      importBrowserDataSelected = importBrowserDataSelected.set('favorites', true)
      importBrowserDataSelected = importBrowserDataSelected.set('mergeFavorites', true)
    }
    if (this.supportCookies) {
      importBrowserDataSelected = importBrowserDataSelected.set('cookies', true)
    }
    windowActions.setImportBrowserDataSelected(importBrowserDataSelected)
  }
  get selectedBrowser () {
    let index = this.props.importBrowserDataSelected.get('index')
    if (index === undefined) {
      this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('index', '0')
      if (this.supportHistory) {
        this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('history', true)
      }
      if (this.supportFavorites) {
        this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('favorites', true)
        this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('mergeFavorites', true)
      }
      if (this.supportCookies) {
        this.props.importBrowserDataSelected = this.props.importBrowserDataSelected.set('cookies', true)
      }
    }
    return index !== undefined ? index : '0'
  }
  render () {
    var browsers = []
    if (this.props.importBrowserDataDetail !== undefined) {
      this.props.importBrowserDataDetail.toJS().forEach((browser) => {
        browsers.push(<option value={browser.index}>{browser.name}</option>)
      })
    }
    return <Dialog onHide={this.props.onHide} className='importBrowserDataPanel' isClickDismiss>

 e.stopPropagation()}>

          <select value={this.selectedBrowser}
            onChange={this.onChange} >
            {browsers}
          </select>
          <SwitchControl rightl10nId='browserHistory' checkedOn={this.props.importBrowserDataSelected.get('history')}
            onClick={this.onToggleHistory} disabled={!this.supportHistory} />
          <SwitchControl rightl10nId='favoritesOrBookmarks' checkedOn={this.props.importBrowserDataSelected.get('favorites')}
            onClick={this.onToggleFavorites} disabled={!this.supportFavorites} />

            <SwitchControl rightl10nId='mergeIntoBookmarksToolbar'
              checkedOn={this.props.importBrowserDataSelected.get('mergeFavorites')}
              onClick={this.onToggleMergeFavorites} disabled={!this.props.importBrowserDataSelected.get('favorites')} />

          <SwitchControl rightl10nId='cookies' checkedOn={this.props.importBrowserDataSelected.get('cookies')}
            onClick={this.onToggleCookies} disabled={!this.supportCookies} />

          <Button l10nId='cancel' className='secondaryAltButton' onClick={this.props.onHide} />
          <Button l10nId='import' className='primaryButton' onClick={this.onImport} />

    </Dialog>
  }
}

module.exports = ImportBrowserDataPanel
<|endoftext|>


<commit_before>// @flow

import styles from './EventDetail.css';
import React, { Component, Fragment } from 'react';
import CommentView from 'app/components/Comments/CommentView';
import Icon from 'app/components/Icon';
import JoinEventForm from '../JoinEventForm';
import RegisteredSummary from '../RegisteredSummary';
import {
  AttendanceStatus,
  ModalParentComponent
} from 'app/components/UserAttendance';
import Tag from 'app/components/Tags/Tag';
import { FormatTime, FromToTime } from 'app/components/Time';
import InfoList from 'app/components/InfoList';
import { Flex } from 'app/components/Layout';
import { EVENT_TYPE_TO_STRING, colorForEvent } from '../../utils';
import Admin from '../Admin';
import RegistrationMeta from '../RegistrationMeta';
import DisplayContent from 'app/components/DisplayContent';
import {
  Content,
  ContentHeader,
  ContentSection,
  ContentMain,
  ContentSidebar
} from 'app/components/Content';
import type { ID } from 'app/models';
import { Link } from 'react-router';
import UserGrid from 'app/components/UserGrid';

type InterestedButtonProps = {
  isInterested: boolean
};

const InterestedButton = ({ isInterested }: InterestedButtonProps) => {
  const icon = isInterested ? 'star' : 'star-outline';
  return <Icon className={styles.star} name={icon} />;
};

type Props = {
  eventId: string,
  event: Object,
  loggedIn: boolean,
  currentUser: Object,
  actionGrant: Array<string>,
  comments: Array<Object>,
  error?: Object,
  pools: Array<Object>,
  registrations: Array<Object>,
  currentRegistration: Object,
  currentRegistrationIndex: number,
  hasSimpleWaitingList: boolean,
  waitingRegistrations: Array<Object>,
  register: ({
    eventId: string,
    captchaResponse: string,
    feedback: string,
    userId: number
  }) => Promise<*>,
  follow: (eventId: string, userId: string) => Promise<*>,
  unfollow: (eventId: string, userId: string) => Promise<*>,
  unregister: ({
    eventId: string,
    registrationId: number,
    userId: number
  }) => Promise<*>,
  payment: (eventId: string, token: string) => Promise<*>,
  updateFeedback: (
    eventId: string,
    registrationId: number,
    feedback: string
  ) => Promise<*>,
  deleteEvent: (eventId: ID) => Promise<*>,
  updateUser: Object => void
};

export default class EventDetail extends Component<Props> {
  handleRegistration = ({ captchaResponse, feedback, type }: Object) => {
    const {
      eventId,
      currentRegistration,
      register,
      unregister,
      updateFeedback,
      currentUser: { id: userId }
    } = this.props;
    switch (type) {
      case 'feedback':
        return updateFeedback(eventId, currentRegistration.id, feedback);
      case 'register':
        // Note that we do not return this promise due to custom submitting handling
        register({
          eventId,
          captchaResponse,
          feedback,
          userId
        });
        return;
      case 'unregister':
        unregister({
          eventId,
          registrationId: currentRegistration.id,
          userId
        });
        return;
      default:
        return undefined;
    }
  };

  handleToken = (token: Object) => {
    this.props.payment(this.props.event.id, token.id);
  };

  render() {
    const {
      event,
      loggedIn,
      currentUser,
      updateUser,
      actionGrant,
      comments,
      error,
      pools,
      registrations,
      currentRegistration,
      currentRegistrationIndex,
      hasSimpleWaitingList,
      deleteEvent,
      follow,
      unfollow
    } = this.props;
    if (!event.id) {
      return null;
    }

    if (error) {
      return
{error.message}
;
    }

    const color = colorForEvent(event.eventType);
    const onRegisterClick = event.isUserFollowing
      ? () => unfollow(event.isUserFollowing.id, event.id)
      : () => follow(currentUser.id, event.id);

    const infoItems = [
      event.company && {
        key: 'Arrangerende bedrift',
        value: (
          <Link to={`/companies/${event.company.id}`}>
            {event.company.name}
          </Link>
        )
      },
      event.createdBy && {
        key: 'Forfatter',
        value: (
          <Link to={`/users/${event.createdBy.username}`}>
            {event.createdBy.fullName}
          </Link>
        )
      },
      event.responsibleGroup && {
        key: 'Arrangør',
        value: (

            {event.responsibleGroup.name}{' '}
            {event.responsibleGroup.contactEmail && (
              <a href={`mailto:${event.responsibleGroup.contactEmail}`}>
                {event.responsibleGroup.contactEmail}

            )}

        )
      },
      {
        key: 'Hva',
        value: EVENT_TYPE_TO_STRING(event.eventType)
      },
      {
        key: 'Når',
        value: <FromToTime from={event.startTime} to={event.endTime} />
      },
      { key: 'Finner sted i', value: event.location },
      event.activationTime && {
        key: 'Påmelding åpner',
        value: <FormatTime time={event.activationTime} />
      },
      event.unregistrationDeadline && {
        key: 'Avregistreringsfrist',
        value: <FormatTime time={event.unregistrationDeadline} />
      }
    ];

    const paidItems = [
      { key: 'Pris', value: `${event.priceMember / 100},-` },
      event.paymentDueDate && {
        key: 'Betalingsfrist',
        value: <FormatTime time={event.paymentDueDate} />
      }
    ];

    return (

        <Content banner={event.cover || (event.company && event.company.logo)}>
          <ContentHeader
            borderColor={color}
            onClick={onRegisterClick}
            className={styles.title}
          >
            {loggedIn && (
              <InterestedButton isInterested={event.isUserFollowing} />
            )}
            {event.title}
          </ContentHeader>

          <ContentSection>
            <ContentMain>
              <DisplayContent content={event.text} />
              <Flex className={styles.tagRow}>
                {event.tags.map((tag, i) => (
                  <Tag key={i} tag={tag} />
                ))}
              </Flex>
            </ContentMain>
            <ContentSidebar>
              <InfoList items={infoItems} />
              {event.isPriced && (

                  Dette er et betalt arrangement
                  <InfoList items={paidItems} />

              )}
              <Flex column>

Påmeldte

                {registrations ? (
                  <Fragment>
                    <UserGrid
                      minRows={2}
                      maxRows={2}
                      users={registrations.slice(0, 14).map(reg => reg.user)}
                    />
                    <ModalParentComponent
                      key="modal"
                      pools={pools}
                      registrations={registrations}
                      title="Påmeldte"
                    >
                      <RegisteredSummary registrations={registrations} />
                      <AttendanceStatus />
                    </ModalParentComponent>
                  </Fragment>
                ) : (
                  <AttendanceStatus pools={pools} />
                )}

                {loggedIn && (
                  <RegistrationMeta
                    registration={currentRegistration}
                    isPriced={event.isPriced}
                    registrationIndex={currentRegistrationIndex}
                    hasSimpleWaitingList={hasSimpleWaitingList}
                  />
                )}
                <Admin
                  actionGrant={actionGrant}
                  event={event}
                  deleteEvent={deleteEvent}
                />
              </Flex>
            </ContentSidebar>
          </ContentSection>

          {loggedIn &&
          event.unansweredSurveys &&
          event.unansweredSurveys.length > 0 ? (

                Du kan ikke melde deg på dette arrangementet fordi du har
                ubesvarte spørreundersøkelser.

                Man må svare på alle spørreundersøkelser for tidligere
                arrangementer før man kan melde seg på nye arrangementer. Du kan
                svare på undersøkelsene dine ved å trykke på følgende linker:

                {event.unansweredSurveys.map((surveyId, i) => (

                    <Link to={`/surveys/${surveyId}`}>
                      Undersøkelse {i + 1}
                    </Link>

                ))}

          ) : (

                Bli med på dette arrangementet

              <Link
                to="/pages/arrangementer/26-arrangementsregler"
                style={{ marginTop: 0 }}
              >
                <Flex alignItems="center">
                  <Icon name="document" style={{ marginRight: '4px' }} />
                  Regler for Abakus' arrangementer
                </Flex>
              </Link>

              <JoinEventForm
                event={event}
                registration={currentRegistration}
                currentUser={currentUser}
                updateUser={updateUser}
                onToken={this.handleToken}
                onSubmit={this.handleRegistration}
              />

          )}

          {event.commentTarget && (
            <CommentView
              style={{ marginTop: 20 }}
              user={currentUser}
              commentTarget={event.commentTarget}
              loggedIn={loggedIn}
              comments={comments}
            />
          )}
        </Content>

    );
  }
}
<commit_msg>Add hover effect to favorite-star in events<commit_after>// @flow

import styles from './EventDetail.css';
import React, { Component, Fragment } from 'react';
import CommentView from 'app/components/Comments/CommentView';
import Icon from 'app/components/Icon';
import JoinEventForm from '../JoinEventForm';
import RegisteredSummary from '../RegisteredSummary';
import {
  AttendanceStatus,
  ModalParentComponent
} from 'app/components/UserAttendance';
import Tag from 'app/components/Tags/Tag';
import { FormatTime, FromToTime } from 'app/components/Time';
import InfoList from 'app/components/InfoList';
import { Flex } from 'app/components/Layout';
import Tooltip from 'app/components/Tooltip';
import { EVENT_TYPE_TO_STRING, colorForEvent } from '../../utils';
import Admin from '../Admin';
import RegistrationMeta from '../RegistrationMeta';
import DisplayContent from 'app/components/DisplayContent';
import {
  Content,
  ContentHeader,
  ContentSection,
  ContentMain,
  ContentSidebar
} from 'app/components/Content';
import type { ID } from 'app/models';
import { Link } from 'react-router';
import UserGrid from 'app/components/UserGrid';

type InterestedButtonProps = {
  isInterested: boolean
};

const InterestedButton = ({ isInterested }: InterestedButtonProps) => {
  const icon = isInterested ? 'star' : 'star-outline';
  return (

      <Tooltip
        style={{ lineHeight: '1.3rem' }}
        content={

            Favoritt

        }
      >
        <Icon className={styles.star} name={icon} />
      </Tooltip>

  );
};

type Props = {
  eventId: string,
  event: Object,
  loggedIn: boolean,
  currentUser: Object,
  actionGrant: Array<string>,
  comments: Array<Object>,
  error?: Object,
  pools: Array<Object>,
  registrations: Array<Object>,
  currentRegistration: Object,
  currentRegistrationIndex: number,
  hasSimpleWaitingList: boolean,
  waitingRegistrations: Array<Object>,
  register: ({
    eventId: string,
    captchaResponse: string,
    feedback: string,
    userId: number
  }) => Promise<*>,
  follow: (eventId: string, userId: string) => Promise<*>,
  unfollow: (eventId: string, userId: string) => Promise<*>,
  unregister: ({
    eventId: string,
    registrationId: number,
    userId: number
  }) => Promise<*>,
  payment: (eventId: string, token: string) => Promise<*>,
  updateFeedback: (
    eventId: string,
    registrationId: number,
    feedback: string
  ) => Promise<*>,
  deleteEvent: (eventId: ID) => Promise<*>,
  updateUser: Object => void
};

export default class EventDetail extends Component<Props> {
  handleRegistration = ({ captchaResponse, feedback, type }: Object) => {
    const {
      eventId,
      currentRegistration,
      register,
      unregister,
      updateFeedback,
      currentUser: { id: userId }
    } = this.props;
    switch (type) {
      case 'feedback':
        return updateFeedback(eventId, currentRegistration.id, feedback);
      case 'register':
        // Note that we do not return this promise due to custom submitting handling
        register({
          eventId,
          captchaResponse,
          feedback,
          userId
        });
        return;
      case 'unregister':
        unregister({
          eventId,
          registrationId: currentRegistration.id,
          userId
        });
        return;
      default:
        return undefined;
    }
  };

  handleToken = (token: Object) => {
    this.props.payment(this.props.event.id, token.id);
  };

  render() {
    const {
      event,
      loggedIn,
      currentUser,
      updateUser,
      actionGrant,
      comments,
      error,
      pools,
      registrations,
      currentRegistration,
      currentRegistrationIndex,
      hasSimpleWaitingList,
      deleteEvent,
      follow,
      unfollow
    } = this.props;
    if (!event.id) {
      return null;
    }

    if (error) {
      return
{error.message}
;
    }

    const color = colorForEvent(event.eventType);
    const onRegisterClick = event.isUserFollowing
      ? () => unfollow(event.isUserFollowing.id, event.id)
      : () => follow(currentUser.id, event.id);

    const infoItems = [
      event.company && {
        key: 'Arrangerende bedrift',
        value: (
          <Link to={`/companies/${event.company.id}`}>
            {event.company.name}
          </Link>
        )
      },
      event.createdBy && {
        key: 'Forfatter',
        value: (
          <Link to={`/users/${event.createdBy.username}`}>
            {event.createdBy.fullName}
          </Link>
        )
      },
      event.responsibleGroup && {
        key: 'Arrangør',
        value: (

            {event.responsibleGroup.name}{' '}
            {event.responsibleGroup.contactEmail && (
              <a href={`mailto:${event.responsibleGroup.contactEmail}`}>
                {event.responsibleGroup.contactEmail}

            )}

        )
      },
      {
        key: 'Hva',
        value: EVENT_TYPE_TO_STRING(event.eventType)
      },
      {
        key: 'Når',
        value: <FromToTime from={event.startTime} to={event.endTime} />
      },
      { key: 'Finner sted i', value: event.location },
      event.activationTime && {
        key: 'Påmelding åpner',
        value: <FormatTime time={event.activationTime} />
      },
      event.unregistrationDeadline && {
        key: 'Avregistreringsfrist',
        value: <FormatTime time={event.unregistrationDeadline} />
      }
    ];

    const paidItems = [
      { key: 'Pris', value: `${event.priceMember / 100},-` },
      event.paymentDueDate && {
        key: 'Betalingsfrist',
        value: <FormatTime time={event.paymentDueDate} />
      }
    ];

    return (

        <Content banner={event.cover || (event.company && event.company.logo)}>
          <ContentHeader
            borderColor={color}
            onClick={onRegisterClick}
            className={styles.title}
          >
            {loggedIn && (
              <InterestedButton isInterested={event.isUserFollowing} />
            )}
            {event.title}
          </ContentHeader>

          <ContentSection>
            <ContentMain>
              <DisplayContent content={event.text} />
              <Flex className={styles.tagRow}>
                {event.tags.map((tag, i) => (
                  <Tag key={i} tag={tag} />
                ))}
              </Flex>
            </ContentMain>
            <ContentSidebar>
              <InfoList items={infoItems} />
              {event.isPriced && (

                  Dette er et betalt arrangement
                  <InfoList items={paidItems} />

              )}
              <Flex column>

Påmeldte

                {registrations ? (
                  <Fragment>
                    <UserGrid
                      minRows={2}
                      maxRows={2}
                      users={registrations.slice(0, 14).map(reg => reg.user)}
                    />
                    <ModalParentComponent
                      key="modal"
                      pools={pools}
                      registrations={registrations}
                      title="Påmeldte"
                    >
                      <RegisteredSummary registrations={registrations} />
                      <AttendanceStatus />
                    </ModalParentComponent>
                  </Fragment>
                ) : (
                  <AttendanceStatus pools={pools} />
                )}

                {loggedIn && (
                  <RegistrationMeta
                    registration={currentRegistration}
                    isPriced={event.isPriced}
                    registrationIndex={currentRegistrationIndex}
                    hasSimpleWaitingList={hasSimpleWaitingList}
                  />
                )}
                <Admin
                  actionGrant={actionGrant}
                  event={event}
                  deleteEvent={deleteEvent}
                />
              </Flex>
            </ContentSidebar>
          </ContentSection>

          {loggedIn &&
          event.unansweredSurveys &&
          event.unansweredSurveys.length > 0 ? (

                Du kan ikke melde deg på dette arrangementet fordi du har
                ubesvarte spørreundersøkelser.

                Man må svare på alle spørreundersøkelser for tidligere
                arrangementer før man kan melde seg på nye arrangementer. Du kan
                svare på undersøkelsene dine ved å trykke på følgende linker:

                {event.unansweredSurveys.map((surveyId, i) => (

                    <Link to={`/surveys/${surveyId}`}>
                      Undersøkelse {i + 1}
                    </Link>

                ))}

          ) : (

                Bli med på dette arrangementet

              <Link
                to="/pages/arrangementer/26-arrangementsregler"
                style={{ marginTop: 0 }}
              >
                <Flex alignItems="center">
                  <Icon name="document" style={{ marginRight: '4px' }} />
                  Regler for Abakus' arrangementer
                </Flex>
              </Link>

              <JoinEventForm
                event={event}
                registration={currentRegistration}
                currentUser={currentUser}
                updateUser={updateUser}
                onToken={this.handleToken}
                onSubmit={this.handleRegistration}
              />

          )}

          {event.commentTarget && (
            <CommentView
              style={{ marginTop: 20 }}
              user={currentUser}
              commentTarget={event.commentTarget}
              loggedIn={loggedIn}
              comments={comments}
            />
          )}
        </Content>

    );
  }
}
<|endoftext|>


<commit_before>var config = require("../../shared/config");
var observableArrayModule = require("data/observable-array");

function GroceryListViewModel(items) {
	var viewModel = new observableArrayModule.ObservableArray(items);
	var history = new observableArrayModule.ObservableArray([]);

	viewModel.load = function() {
		return fetch(config.apiUrl + "Groceries", {
			headers: {
				"Authorization": "Bearer " + config.token
			}
		})
		.then(handleErrors)
		.then(function(response) {
			return response.json();
		}).then(function(data) {
			data.Result.forEach(function(grocery) {
				var destination = grocery.Deleted ? history : viewModel;
				destination.push({
					name: grocery.Name,
					id: grocery.Id,
					deleted: grocery.Deleted,
					done: grocery.Done
				});
			});
		});
	};

	viewModel.empty = function() {
		while (viewModel.length) {
			viewModel.pop();
		}
		while (history.length) {
			history.pop();
		}
	};

	viewModel.history = function() {
		return history;
	};

	viewModel.add = function(grocery) {
		return fetch(config.apiUrl + "Groceries", {
			method: "POST",
			body: JSON.stringify({
				Name: grocery
			}),
			headers: {
				"Authorization": "Bearer " + config.token,
				"Content-Type": "application/json"
			}
		})
		.then(handleErrors)
		.then(function(response) {
			return response.json();
		})
		.then(function(data) {
			viewModel.push({ name: grocery, id: data.Result.Id });
		});
	};

	function toggleDelete(index, deleteFlag) {
		var source = deleteFlag ? viewModel : history;
		var destination = deleteFlag ? history : viewModel;
		var item = source.getItem(index);

		return fetch(config.apiUrl + "Groceries/" + item.id, {
			method: "PUT",
			body: JSON.stringify({
				Deleted: deleteFlag
			}),
			headers: {
				"Authorization": "Bearer " + config.token,
				"Content-Type": "application/json"
			}
		})
		.then(handleErrors)
		.then(function() {
			source.splice(index, 1);
			destination.push(item);
		});
	}

	viewModel.restore = function(index) {
		return toggleDelete(index, false);
	};
	viewModel.delete = function(index) {
		return toggleDelete(index, true);
	};

	viewModel.toggleDone = function(index) {
		var item = viewModel.getItem(index);
		item.done = !item.done;

		return fetch(config.apiUrl + "Groceries/" + item.id, {
			method: "PUT",
			body: JSON.stringify({
				Done: item.done
			}),
			headers: {
				"Authorization": "Bearer " + config.token,
				"Content-Type": "application/json"
			}
		})
		.then(handleErrors)
		.then(function() {
			viewModel.setItem(index, item);
		});
	};

	return viewModel;
}

function handleErrors(response) {
	if (!response.ok) {
		console.log(JSON.stringify(response));
		throw Error(response.statusText);
	}
	return response;
}

module.exports = GroceryListViewModel;<commit_msg>Make the ListView update actually work<commit_after>var config = require("../../shared/config");
var observableArrayModule = require("data/observable-array");

function GroceryListViewModel(items) {
	var viewModel = new observableArrayModule.ObservableArray(items);
	var history = new observableArrayModule.ObservableArray([]);

	viewModel.load = function() {
		return fetch(config.apiUrl + "Groceries", {
			headers: {
				"Authorization": "Bearer " + config.token
			}
		})
		.then(handleErrors)
		.then(function(response) {
			return response.json();
		}).then(function(data) {
			data.Result.forEach(function(grocery) {
				var destination = grocery.Deleted ? history : viewModel;
				destination.push({
					name: grocery.Name,
					id: grocery.Id,
					deleted: grocery.Deleted,
					done: grocery.Done
				});
			});
		});
	};

	viewModel.empty = function() {
		while (viewModel.length) {
			viewModel.pop();
		}
		while (history.length) {
			history.pop();
		}
	};

	viewModel.history = function() {
		return history;
	};

	viewModel.add = function(grocery) {
		return fetch(config.apiUrl + "Groceries", {
			method: "POST",
			body: JSON.stringify({
				Name: grocery
			}),
			headers: {
				"Authorization": "Bearer " + config.token,
				"Content-Type": "application/json"
			}
		})
		.then(handleErrors)
		.then(function(response) {
			return response.json();
		})
		.then(function(data) {
			viewModel.push({ name: grocery, id: data.Result.Id });
		});
	};

	function toggleDelete(index, deleteFlag) {
		var source = deleteFlag ? viewModel : history;
		var destination = deleteFlag ? history : viewModel;
		var item = source.getItem(index);

		return fetch(config.apiUrl + "Groceries/" + item.id, {
			method: "PUT",
			body: JSON.stringify({
				Deleted: deleteFlag
			}),
			headers: {
				"Authorization": "Bearer " + config.token,
				"Content-Type": "application/json"
			}
		})
		.then(handleErrors)
		.then(function() {
			source.splice(index, 1);
			destination.push(item);
		});
	}

	viewModel.restore = function(index) {
		return toggleDelete(index, false);
	};
	viewModel.delete = function(index) {
		return toggleDelete(index, true);
	};

	viewModel.toggleDone = function(index) {
		var item = viewModel.getItem(index);
		item.done = !item.done;

		return fetch(config.apiUrl + "Groceries/" + item.id, {
			method: "PUT",
			body: JSON.stringify({
				Done: item.done
			}),
			headers: {
				"Authorization": "Bearer " + config.token,
				"Content-Type": "application/json"
			}
		})
		.then(handleErrors)
		.then(function() {
			viewModel.setItem(index, {
				name: item.name,
				id: item.id,
				deleted: item.deleted,
				done: item.done
			});
		});
	};

	return viewModel;
}

function handleErrors(response) {
	if (!response.ok) {
		console.log(JSON.stringify(response));
		throw Error(response.statusText);
	}
	return response;
}

module.exports = GroceryListViewModel;<|endoftext|>


<commit_before>const assert = require('assert')
const addParameters = require('../gulpfile').addParameters
const cheerio = require('cheerio')

describe('addParameters adds all parameters in information.json to all links if there are none present', function () {
  it('accepts a string and an object and a cheerio instance', function () {
    let basicString = 'string'
    let linksObject = {}
    assert.doesNotThrow(function () {
      addParameters(basicString, linksObject, cheerio)
    }, Error, 'File is empty')
  })
  it('returns the same element if the links object is empty', function () {
    let basicString = '<a href="https://www.google.com"'
    assert.equal(addParameters(basicString, {}, cheerio), basicString)
    assert.equal(addParameters('', {}, cheerio), '')
  })
  it('appends the parameters to the all links in the string', function () {
    let basicString = 'Google Github'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium'
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerio), 'Google Github')
  })
  it('appends only the elements that are not empty', function () {
    let basicString = 'Google Github'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: ''
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerio), 'Google Github')
  })
  it('appends only strings or numbers, ignores other types of key values', function () {
    let basicString = 'Google Github'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: 5,
        content: function () {
          console.log('Faulty function')
        }
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerio),
      'Google Github')
  })
  it('adds only the valid utm keys, rejects the ones that do not match', function () {
    let basicString = 'Google Github'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: 5,
        content: function () {
          console.log('Faulty function')
        },
        fake: 'fake'
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerio),
      'Google Github')
  })
  it('adds only the valid utm keys, rejects the ones that do not match', function () {
    let basicString = 'Google'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: 'name',
        term: 'term',
        content: 'content'
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerio),
      'Google')
  })

  it('if there are existing parameters it does not add anything', function () {
    let basicString = 'Google Google'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: 'name',
        term: 'term',
        content: 'content'
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerio),
      'Google Google')
  })
})
<commit_msg>test the functionality of empty utm objects => no url parameters<commit_after>const assert = require('assert')
const addParameters = require('../gulpfile').addParameters
const cheerioTest = require('cheerio')

describe('addParameters adds all utm parameters in an links object to all links if there are none present', function () {
  it('accepts a string, an object and a cheerio instance', function () {
    let basicString = 'string'
    let linksObject = {}
    assert.doesNotThrow(function () {
      addParameters(basicString, linksObject, cheerioTest)
    }, Error, 'File is empty')
  })
  it('returns the same element if the links object is empty', function () {
    let basicString = '<a href="https://www.google.com"'
    assert.equal(addParameters(basicString, {}, cheerioTest), basicString)
    assert.equal(addParameters('', {}, cheerioTest), '')
  })
  it('appends the parameters to the all links in the string', function () {
    let basicString = 'Google Github'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium'
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerioTest), 'Google Github')
  })
  it('appends only the elements that are not empty', function () {
    let basicString = 'Google Github'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: ''
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerioTest), 'Google Github')
  })
  it('appends only strings or numbers, ignores other types of key values', function () {
    let basicString = 'Google Github'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: 5,
        content: function () {
          console.log('Faulty function')
        }
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerioTest),
      'Google Github')
  })
  it('adds only the valid utm keys, rejects the ones that do not match', function () {
    let basicString = 'Google Github'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: 5,
        content: function () {
          console.log('Faulty function')
        },
        fake: 'fake'
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerioTest),
      'Google Github')
  })
  it('adds only the valid utm keys, rejects the ones that do not match', function () {
    let basicString = 'Google'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: 'name',
        term: 'term',
        content: 'content'
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerioTest),
      'Google')
  })

  it('if there are existing parameters it does not add anything', function () {
    let basicString = 'Google Google'
    let linksObject = {
      utm: {
        source: 'source',
        medium: 'medium',
        name: 'name',
        term: 'term',
        content: 'content'
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerioTest),
      'Google Google')
  })
  it('if all utm parameters are empty, add nothing', function () {
    let basicString = 'Google Google'
    let linksObject = {
      utm: {
        source: '',
        medium: '',
        name: '',
        term: '',
        content: ''
      }
    }
    assert.equal(addParameters(basicString, linksObject, cheerioTest),
      'Google Google')
  })
})
<|endoftext|>


<commit_before>var assert = require('assert');

function validateRemainingLength(value) {
    var maxMessageLength = 268435455;
    if (value > maxMessageLength) {
        return Error('max message length exceeded');
    }
    return undefined;
}

function existy(value) {
    return value !== null && value !== undefined;
}

function dispatch() {
    var funcs = arguments;

    return function(target) {
        for (var funcIndex in funcs) {
            var func = funcs[funcIndex];
            var ret = func.apply(null, [target]);
            if (existy(ret)) {
                return ret;
            }
        }
        return undefined;
    }
}

function encodeRemainingLength(value) {

    var dispatcher = dispatch(validateRemainingLength, encode);

    return dispatcher(value);

    function encode(value) {
        var buffer = new Buffer(0);
        do {
            var digit = value % 128;
            value = parseInt(value / 128);
            if (value > 0) {
                digit = digit | 0xFF;
            }
            var next = new Buffer(1);
            next.writeUInt8(digit, 0);
            buffer = Buffer.concat([buffer, next])
        }
        while (value > 0);
        return buffer;
    }
}

function decodeRemainingLength(buffer) {
    var multiplier = 1;
    var value = 0;
    var index = 0;
    var digit;
    do {
        if (index === buffer.length)
            throw Error('malformed remaining length')
        digit = buffer.readUInt8(index++);
        value += (digit & 127) * multiplier;
        multiplier *= 128;
    }
    while ((digit & 128) !== 0);
    return value;
}

function remainingLengthByteCount(value) {
    var dispatcher = dispatch(validateRemainingLength, count);
    return dispatcher(value);

    function count(value){
        return Math.ceil(Math.log(value) / Math.log(128));
    }
}

describe('MQTT Special Functions', function() {

    describe('Encoding remaining length', function() {

        function expectEncoding(value, expectedValues) {
            var result = encodeRemainingLength(value);
            assert.equal(result.length, expectedValues.length);
            for (var i = 0; i < expectedValues.length; i++) {
                assert.equal(result.readUInt8(i), expectedValues[i]);
            }
        }

        it('encoding 127 returns a 1 byte Buffer', function() {
            expectEncoding(127, [0x7F]);
        });

        it('encoding 128 x 127 returns a 2 byte Buffer', function() {
            expectEncoding(128 * 127, [0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 127 returns a 3 byte Buffer', function() {
            expectEncoding(128 * 128 * 127, [0xFF, 0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 128 x 127 returns a 4 byte Buffer', function() {
            expectEncoding(128 * 128 * 128 * 127, [0xFF, 0xFF, 0xFF, 0x7F]);
        });

        it('encoding a number greater than 128x128x128x127 throws an error', function() {
            var error = encodeRemainingLength(128 * 128 * 128 * 128);
            assert.equal(error.message,'max message length exceeded');
        });
    });

    describe('Decoding remaining length', function() {

        var oneByteUpperLimit = 128 - 1;
        var twoByteUpperLimit = 128 * 128 - 1;
        var threeByteUpperLimit = 128 * 128 * 128 - 1;
        var fourByteUpperLimit = 128 * 128 * 128 * 128 - 1;

        function expectDecoding(value, expectedValue) {
            var buffer = new Buffer(value.length);
            for (var i = 0; i < value.length; i++) {
                buffer.writeUInt8(value[i], i);
            }
            var result = decodeRemainingLength(buffer);
            assert.equal(result, expectedValue);
        }

        it('decodes 0x7F as one byte upper limit', function() {
            expectDecoding([0x7F], oneByteUpperLimit);
        });

        it('decodes 0xFF 0x7F as two byte upper limit', function() {
            expectDecoding([0xFF, 0x7F], twoByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0x7F as three byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0x7F], threeByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0xFF 0x7F as four byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0xFF, 0x7F], fourByteUpperLimit);
        });

        it('decoding a buffer greater than the four byte upper limit throws an error', function() {
            assert.throws(function() {
                decodeRemainingLength(new Buffer([0xFF, 0xFF, 0xFF, 0xFF]))
            }, /malformed remaining length/);
        });

        it('remainingLengthByteCount returns 1', function() {
            assert.equal(1, remainingLengthByteCount(oneByteUpperLimit));
        });

        it('remainLengthByteCount returns 2', function() {
            assert.equal(2, remainingLengthByteCount(twoByteUpperLimit));
        });

        it('remainingLengthByteCount returns 2', function() {
            assert.equal(3, remainingLengthByteCount(threeByteUpperLimit));
        });

        it('remainingLengthByteCount returns 4', function() {
            assert.equal(4, remainingLengthByteCount(fourByteUpperLimit));
        });

        it('remainingLengthByteCount returns error when number is greater than fourByteUpperLimit', function() {
            assert.ok(remainingLengthByteCount(fourByteUpperLimit + 1) instanceof Error);
        });
    });

});
<commit_msg>returning an error from decode instead of throwing<commit_after>var assert = require('assert');

function validateRemainingLength(value) {
    var maxMessageLength = 268435455;
    if (value > maxMessageLength) {
        return Error('max message length exceeded');
    }
    return undefined;
}

function existy(value) {
    return value !== null && value !== undefined;
}

function dispatch() {
    var funcs = arguments;

    return function(target) {
        for (var funcIndex in funcs) {
            var func = funcs[funcIndex];
            var ret = func.apply(null, [target]);
            if (existy(ret)) {
                return ret;
            }
        }
        return undefined;
    }
}

function encodeRemainingLength(value) {

    var dispatcher = dispatch(validateRemainingLength, encode);

    return dispatcher(value);

    function encode(value) {
        var buffer = new Buffer(0);
        do {
            var digit = value % 128;
            value = parseInt(value / 128);
            if (value > 0) {
                digit = digit | 0xFF;
            }
            var next = new Buffer(1);
            next.writeUInt8(digit, 0);
            buffer = Buffer.concat([buffer, next])
        }
        while (value > 0);
        return buffer;
    }
}

function decodeRemainingLength(buffer) {
    var multiplier = 1;
    var value = 0;
    var index = 0;
    var digit;
    do {
        if (index === buffer.length)
            return Error('malformed remaining length')
        digit = buffer.readUInt8(index++);
        value += (digit & 127) * multiplier;
        multiplier *= 128;
    }
    while ((digit & 128) !== 0);
    return value;
}

function remainingLengthByteCount(value) {
    var dispatcher = dispatch(validateRemainingLength, count);
    return dispatcher(value);

    function count(value) {
        return Math.ceil(Math.log(value) / Math.log(128));
    }
}

describe('MQTT Special Functions', function() {

    describe('Encoding remaining length', function() {

        function expectEncoding(value, expectedValues) {
            var result = encodeRemainingLength(value);
            assert.equal(result.length, expectedValues.length);
            for (var i = 0; i < expectedValues.length; i++) {
                assert.equal(result.readUInt8(i), expectedValues[i]);
            }
        }

        it('encoding 127 returns a 1 byte Buffer', function() {
            expectEncoding(127, [0x7F]);
        });

        it('encoding 128 x 127 returns a 2 byte Buffer', function() {
            expectEncoding(128 * 127, [0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 127 returns a 3 byte Buffer', function() {
            expectEncoding(128 * 128 * 127, [0xFF, 0xFF, 0x7F]);
        });

        it('encoding 128 x 128 x 128 x 127 returns a 4 byte Buffer', function() {
            expectEncoding(128 * 128 * 128 * 127, [0xFF, 0xFF, 0xFF, 0x7F]);
        });

        it('encoding a number greater than 128x128x128x127 throws an error', function() {
            var error = encodeRemainingLength(128 * 128 * 128 * 128);
            assert.equal(error.message, 'max message length exceeded');
        });
    });

    describe('Decoding remaining length', function() {

        var oneByteUpperLimit = 128 - 1;
        var twoByteUpperLimit = 128 * 128 - 1;
        var threeByteUpperLimit = 128 * 128 * 128 - 1;
        var fourByteUpperLimit = 128 * 128 * 128 * 128 - 1;

        function expectDecoding(value, expectedValue) {
            var buffer = new Buffer(value.length);
            for (var i = 0; i < value.length; i++) {
                buffer.writeUInt8(value[i], i);
            }
            var result = decodeRemainingLength(buffer);
            assert.equal(result, expectedValue);
        }

        it('decodes 0x7F as one byte upper limit', function() {
            expectDecoding([0x7F], oneByteUpperLimit);
        });

        it('decodes 0xFF 0x7F as two byte upper limit', function() {
            expectDecoding([0xFF, 0x7F], twoByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0x7F as three byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0x7F], threeByteUpperLimit);
        });

        it('decodes 0xFF 0xFF 0xFF 0x7F as four byte upper limit', function() {
            expectDecoding([0xFF, 0xFF, 0xFF, 0x7F], fourByteUpperLimit);
        });

        it('decoding a buffer greater than the four byte upper limit throws an error', function() {
            var error = decodeRemainingLength(new Buffer([0xFF, 0xFF, 0xFF, 0xFF]))
            assert.equal(error.message, 'malformed remaining length');
        });

        it('remainingLengthByteCount returns 1', function() {
            assert.equal(1, remainingLengthByteCount(oneByteUpperLimit));
        });

        it('remainLengthByteCount returns 2', function() {
            assert.equal(2, remainingLengthByteCount(twoByteUpperLimit));
        });

        it('remainingLengthByteCount returns 2', function() {
            assert.equal(3, remainingLengthByteCount(threeByteUpperLimit));
        });

        it('remainingLengthByteCount returns 4', function() {
            assert.equal(4, remainingLengthByteCount(fourByteUpperLimit));
        });

        it('remainingLengthByteCount returns error when number is greater than fourByteUpperLimit', function() {
            assert.ok(remainingLengthByteCount(fourByteUpperLimit + 1) instanceof Error);
        });
    });

});
<|endoftext|>


<commit_before>
module.exports = {
  "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "es6": true
        }
    },
    "rules": {
        'quotes': ["warn", 'single'],
        "semi": 2,
        "indent": ["warn", 2,
          {
            "SwitchCase": 1,
            "MemberExpression": 1,
            "ObjectExpression": 1
          }],
        "no-loop-func": "error",
        "no-dupe-keys": "error",
        "no-empty": "error",
        "block-scoped-var": "error",
        "dot-notation": "error",
        "no-redeclare": "error",
        "no-self-assign": "error",
        "no-useless-escape": "error",
        "comma-spacing": ["warn", { "before": false, "after": true }],
        "key-spacing": ["error",
          {
            "beforeColon": false,
            "afterColon": true
          }],
        "keyword-spacing": ["error", { "before": true }],
        "no-debugger": process.env.NODE_ENV === 'production' ? 'error' : 'off',
        "no-console": [process.env.NODE_ENV === 'production' ? 'error' : 'off',
            { allow: ["warn", "error"]
        }],
    }
}
<commit_msg>eslint rules<commit_after>
module.exports = {
  "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "es6": true
        }
    },
    "rules": {
        'quotes': ["warn", 'single'],
        "semi": 2,
        "indent": ["warn", 2,
          {
            "SwitchCase": 1,
            "MemberExpression": 1,
            "ObjectExpression": 1
          }],
        "no-loop-func": "error",
        "no-dupe-keys": "error",
        "no-empty": "error",
        "block-scoped-var": "error",
        "dot-notation": "error",
        "no-redeclare": "error",
        "no-self-assign": "error",
        // "no-useless-escape": "error",
        "comma-spacing": ["warn", { "before": false, "after": true }],
        "key-spacing": ["error",
          {
            "beforeColon": false,
            "afterColon": true
          }],
        "keyword-spacing": ["error", { "before": true }],
        "no-debugger": process.env.NODE_ENV === 'production' ? 'error' : 'off',
        "no-console": [process.env.NODE_ENV === 'production' ? 'error' : 'off',
            { allow: ["warn", "error"]
        }],
    }
}
<|endoftext|>


<commit_before>/*eslint-env mocha */
/*global chai */

import Wrapper from "../wrapper";
import Transfer from "../transfer";
import spanan from "../spanan";

var expect = chai.expect;

describe("Wrapper", function () {
  var target, _subject;

  beforeEach(function () {
    target = {
      postMessage: function () {}
    };
  });

  afterEach(function () {
    _subject = undefined;
  });

  function subject(otherTarget) {
    _subject = _subject || new Wrapper(otherTarget || target);
    return _subject;
  }

  describe("#constructor", function () {
    it("sets `target` as property", function () {
      expect(subject().target).to.eql(target);
    });

    it("sets contentWindow as a target if provided with iframe", function () {
      var iframe = spanan.createIframe();
      expect(subject(iframe).target).to.eql(iframe.contentWindow);

      // cleanup
      document.body.removeChild(iframe);
    });

    it("has default timeout - 1000ms", function () {
      expect(subject()).to.have.property("timeout", 1000);
    });

    it("accepts timeout from options", function () {
      var wrapper = new Wrapper({}, { timeout: 400 });
      expect(wrapper).to.have.property("timeout", 400);
    });
  });

  describe("#ready", function () {
    var iframeURL = "./fixtures/basic.html",
        iframe;

    afterEach(function () {
      if ( iframe ) {
        document.body.removeChild(iframe);
      }
    });

    it("returns promise", function () {
      expect(subject().ready()).to.be.instanceof(Promise);
    });

    it("does not resolve if iframe is not loaded", function () {
      iframe = spanan.createIframe(iframeURL);
      expect(subject(iframe).ready()).to.not.be.fullfilled;
    });

    it("does resolve when iframe is loaded", function (done) {
      iframe = spanan.createIframe(iframeURL);
      var wrapper = subject(iframe);

      setTimeout(function () {
        expect(wrapper.ready()).to.be.fullfilled;
        done();
      }, 200);
    });
  });

  describe("#send", function () {

    it("calls postMessage with Transfer", function (done) {
      var fnName = "test",
          fnArgs = [1,2,3];

      target.postMessage = function (msg) {
        var serializedCall = new Transfer(fnName, fnArgs);
        expect(msg).to.eql(serializedCall.toString());
        done();
      };

      subject().send(fnName, fnArgs);
    });

    it("returns promise", function () {
      expect(subject().send("test")).to.be.instanceof(Promise);
    });

    it("promise get rejected after timeout", function () {
      var wrapper = new Wrapper(target, { timeout: 0 });
      return expect(wrapper.send("test")).to.eventually.be.rejected;
    });

    context("target ready", function () {
      it("calls 'postMessage' on target", function (done) {
        target.postMessage = function () {
          done();
        };
        subject().send("test");
      });

      it("calls postMessage with wildcard as targetOrigin", function (done) {
        target.postMessage = function (msg, targetOrigin) {
          if ( targetOrigin === "*" ) {
            done();
          }
        };
        subject().send("test");
      });

      it("subscribe callback on its callback list", function (done) {
        subject().send("test");
        setTimeout(function () {
          expect(Object.keys(subject()._callbacks)).to.have.length(1);
          done();
        }, 240);
      });
    });

    context("target not ready", function () {
      it("does not call 'postMessage' on target", function () {
        var called = false;

        target.postMessage = function () {
          called = true;
        };

        subject().send("test");

        expect(called).to.eql(false);
      });
    });
  });
});
<commit_msg>Wrapper: testing callback<commit_after>/*eslint-env mocha */
/*global chai */

import Wrapper from "../wrapper";
import Transfer from "../transfer";
import spanan from "../spanan";

var expect = chai.expect;

describe("Wrapper", function () {
  var target, _subject;

  beforeEach(function () {
    target = {
      postMessage: function () {}
    };
  });

  afterEach(function () {
    _subject = undefined;
  });

  function subject(otherTarget) {
    _subject = _subject || new Wrapper(otherTarget || target);
    return _subject;
  }

  describe("#constructor", function () {
    it("sets `target` as property", function () {
      expect(subject().target).to.eql(target);
    });

    it("sets contentWindow as a target if provided with iframe", function () {
      var iframe = spanan.createIframe();
      expect(subject(iframe).target).to.eql(iframe.contentWindow);

      // cleanup
      document.body.removeChild(iframe);
    });

    it("has default timeout - 1000ms", function () {
      expect(subject()).to.have.property("timeout", 1000);
    });

    it("accepts timeout from options", function () {
      var wrapper = new Wrapper({}, { timeout: 400 });
      expect(wrapper).to.have.property("timeout", 400);
    });
  });

  describe("#ready", function () {
    var iframeURL = "./fixtures/basic.html",
        iframe;

    afterEach(function () {
      if ( iframe ) {
        document.body.removeChild(iframe);
      }
    });

    it("returns promise", function () {
      expect(subject().ready()).to.be.instanceof(Promise);
    });

    it("does not resolve if iframe is not loaded", function () {
      iframe = spanan.createIframe(iframeURL);
      expect(subject(iframe).ready()).to.not.be.fullfilled;
    });

    it("does resolve when iframe is loaded", function (done) {
      iframe = spanan.createIframe(iframeURL);
      var wrapper = subject(iframe);

      setTimeout(function () {
        expect(wrapper.ready()).to.be.fullfilled;
        done();
      }, 200);
    });
  });

  describe("#send", function () {

    it("calls postMessage with Transfer", function (done) {
      var fnName = "test",
          fnArgs = [1,2,3];

      target.postMessage = function (msg) {
        var serializedCall = new Transfer(fnName, fnArgs);
        expect(msg).to.eql(serializedCall.toString());
        done();
      };

      subject().send(fnName, fnArgs);
    });

    it("returns promise", function () {
      expect(subject().send("test")).to.be.instanceof(Promise);
    });

    it("promise get rejected after timeout", function () {
      var wrapper = new Wrapper(target, { timeout: 0 });
      return expect(wrapper.send("test")).to.eventually.be.rejected;
    });

    context("target ready", function () {
      beforeEach(function () {
        return subject().ready();
      });

      it("calls 'postMessage' on target", function (done) {
        target.postMessage = function () {
          done();
        };
        subject().send("test");
      });

      it("calls postMessage with wildcard as targetOrigin", function (done) {
        target.postMessage = function (msg, targetOrigin) {
          if ( targetOrigin === "*" ) {
            done();
          }
        };
        subject().send("test");
      });

      it("subscribe callback on its callback list", function (done) {
        subject().send("test");
        setTimeout(function () {
          expect(Object.keys(subject()._callbacks)).to.have.length(1);
          done();
        }, 240);
      });

      it("promise get resolved after callback being called", function (done) {
        var promise = subject().send("test");

        promise.then(done);

        setTimeout(function () {
          subject()._callbacks[promise.transferId]();
        }, 10);
      });
    });

    context("target not ready", function () {
      it("does not call 'postMessage' on target", function () {
        var called = false;

        target.postMessage = function () {
          called = true;
        };

        subject().send("test");

        expect(called).to.eql(false);
      });
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var TAG_NAME = 'icon-checkbox';
var template = require('./template.html');

var ko = require('knockout');

ko.components.register(TAG_NAME, {
    template: template
});
<commit_msg>Correctly set label and value from params.<commit_after>'use strict';

var TAG_NAME = 'icon-checkbox';
var template = require('./template.html');

var ko = require('knockout');

function ViewModel(params) {

    this.value = params.value;
    this.label = params.label;

    this.iconClass = ko.pureComputed(function() {
        return 'icon';
    }, this);

}

ko.components.register(TAG_NAME, {
    template: template,
    viewModel: ViewModel
});
<|endoftext|>


<commit_before>var url = require('url');
var net = require('net');
var http = require('http');
var util = require('../lib/util');

function request(req, res, port, weinre) {
  var options = url.parse(util.getFullUrl(req));
  if (options.protocol == 'https:') {
    options.protocol = 'http:';
    req.headers['x-whistle-https'] = 'true';
  }
  options.host = '127.0.0.1';
  options.method = req.method;
  options.hostname = null;
  options.protocol = null;
  if (port) {
    options.port = port;
  }
  req.headers['x-forwarded-for'] = req.clientIp;
  options.headers = req.headers;
  req.pipe(http.request(options, function(_res) {
    if (weinre && options.pathname == '/target/target-script-min.js') {
      _res.headers['access-control-allow-origin'] = '*';
    }
    if (util.getStatusCode(_res.statusCode)) {
      res.writeHead(_res.statusCode, _res.headers);
      res.src(_res);
      _res.trailers && res.addTrailers(_res.trailers);
    } else {
      util.sendStatusCodeError(res, _res);
    }
  }));
}

module.exports = function(req, res, next) {
  var config = this.config;
  var host = (req.headers.host || '').split(':');
  var port = host[1] || 80;
  host = host[0];
  if (net.isIP(host) && util.isLocalAddress(host)) {
    if (port == config.port || port == config.uiport) {
      host = config.localUIHost;
    } else if (port == config.weinreport) {
      host = config.WEINRE_HOST;
    }
  }

  var pluginMgr = this.pluginMgr;
  var pluginHomePage;
  if (host == config.localUIHost) {
    request(req, res, config.uiport);
  } else if (host == config.WEINRE_HOST) {
    request(req, res, config.weinreport, true);
  } else if (pluginHomePage = pluginMgr.getPluginByHomePage(util.getFullUrl(req))) {
    pluginMgr.loadPlugin(pluginHomePage, function(err, ports) {
      if (err || !ports.uiPort) {
        res.response(util.wrapResponse({
          statusCode: err ? 503 : 501,
          headers: {
            'content-type': 'text/plain; charset=utf-8'
          },
          body: err || 'Not implemented'
        }));
        return;
      }
      request(req, res, ports.uiPort);
    });
  } else {
    next();
  }
};

<commit_msg>feat: Supports use `http://ip:port/whistle.name/xxx` to access plugin<commit_after>var url = require('url');
var net = require('net');
var http = require('http');
var util = require('../lib/util');

function request(req, res, port, weinre) {
  var options = url.parse(util.getFullUrl(req));
  if (options.protocol == 'https:') {
    options.protocol = 'http:';
    req.headers['x-whistle-https'] = 'true';
  }
  options.host = '127.0.0.1';
  options.method = req.method;
  options.hostname = null;
  options.protocol = null;
  if (port) {
    options.port = port;
  }
  req.headers['x-forwarded-for'] = req.clientIp;
  options.headers = req.headers;
  req.pipe(http.request(options, function(_res) {
    if (weinre && options.pathname == '/target/target-script-min.js') {
      _res.headers['access-control-allow-origin'] = '*';
    }
    if (util.getStatusCode(_res.statusCode)) {
      res.writeHead(_res.statusCode, _res.headers);
      res.src(_res);
      _res.trailers && res.addTrailers(_res.trailers);
    } else {
      util.sendStatusCodeError(res, _res);
    }
  }));
}

module.exports = function(req, res, next) {
  var config = this.config;
  var host = (req.headers.host || '').split(':');
  var port = host[1] || 80;
  host = host[0];
  if (net.isIP(host) && util.isLocalAddress(host)) {
    if (port == config.port || port == config.uiport) {
      host = config.localUIHost;
    } else if (port == config.weinreport) {
      host = config.WEINRE_HOST;
    }
  }

  var pluginMgr = this.pluginMgr;
  var fullUrl = util.getFullUrl(req);
  var pluginHomePage;
  if (host == config.localUIHost) {
    var path = url.parse(fullUrl).path;
    if (/\/whistle\.([^\/\?]+)(.*)$/.test(path)) {
      path = RegExp.$2;
      pluginHomePage = pluginMgr.getPluginByName(RegExp.$1);
      if (pluginHomePage) {
        req.url = path;
        host = '';
      }
    }
  }

  if (host == config.localUIHost) {
    request(req, res, config.uiport);
  } else if (host == config.WEINRE_HOST) {
    request(req, res, config.weinreport, true);
  } else if (pluginHomePage || (pluginHomePage = pluginMgr.getPluginByHomePage(fullUrl))) {
    pluginMgr.loadPlugin(pluginHomePage, function(err, ports) {
      if (err || !ports.uiPort) {
        res.response(util.wrapResponse({
          statusCode: err ? 503 : 501,
          headers: {
            'content-type': 'text/plain; charset=utf-8'
          },
          body: err || 'Not implemented'
        }));
        return;
      }
      request(req, res, ports.uiPort);
    });
  } else {
    next();
  }
};

<|endoftext|>


<commit_before>/*
 *	MySQL Mode for CodeMirror 2 by MySQL-Tools
 *	@author James Thorne (partydroid)
 *	@link 	http://github.com/partydroid/MySQL-Tools
 * 	@link 	http://mysqltools.org
 *	@version 02/Jan/2012
*/
CodeMirror.defineMode("mysql", function(config) {
  var indentUnit = config.indentUnit;
  var curPunc;

  function wordRegexp(words) {
    return new RegExp("^(?:" + words.join("|") + ")$", "i");
  }
  var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
                        "isblank", "isliteral", "union", "a"]);
  var keywords = wordRegexp([
  ('ACCESSIBLE'),('ALTER'),('AS'),('BEFORE'),('BINARY'),('BY'),('CASE'),('CHARACTER'),('COLUMN'),('CONTINUE'),('CROSS'),('CURRENT_TIMESTAMP'),('DATABASE'),('DAY_MICROSECOND'),('DEC'),('DEFAULT'),
	('DESC'),('DISTINCT'),('DOUBLE'),('EACH'),('ENCLOSED'),('EXIT'),('FETCH'),('FLOAT8'),('FOREIGN'),('GRANT'),('HIGH_PRIORITY'),('HOUR_SECOND'),('IN'),('INNER'),('INSERT'),('INT2'),('INT8'),
	('INTO'),('JOIN'),('KILL'),('LEFT'),('LINEAR'),('LOCALTIME'),('LONG'),('LOOP'),('MATCH'),('MEDIUMTEXT'),('MINUTE_SECOND'),('NATURAL'),('NULL'),('OPTIMIZE'),('OR'),('OUTER'),('PRIMARY'),
	('RANGE'),('READ_WRITE'),('REGEXP'),('REPEAT'),('RESTRICT'),('RIGHT'),('SCHEMAS'),('SENSITIVE'),('SHOW'),('SPECIFIC'),('SQLSTATE'),('SQL_CALC_FOUND_ROWS'),('STARTING'),('TERMINATED'),
	('TINYINT'),('TRAILING'),('UNDO'),('UNLOCK'),('USAGE'),('UTC_DATE'),('VALUES'),('VARCHARACTER'),('WHERE'),('WRITE'),('ZEROFILL'),('ALL'),('AND'),('ASENSITIVE'),('BIGINT'),('BOTH'),('CASCADE'),
	('CHAR'),('COLLATE'),('CONSTRAINT'),('CREATE'),('CURRENT_TIME'),('CURSOR'),('DAY_HOUR'),('DAY_SECOND'),('DECLARE'),('DELETE'),('DETERMINISTIC'),('DIV'),('DUAL'),('ELSEIF'),('EXISTS'),('FALSE'),
	('FLOAT4'),('FORCE'),('FULLTEXT'),('HAVING'),('HOUR_MINUTE'),('IGNORE'),('INFILE'),('INSENSITIVE'),('INT1'),('INT4'),('INTERVAL'),('ITERATE'),('KEYS'),('LEAVE'),('LIMIT'),('LOAD'),('LOCK'),
	('LONGTEXT'),('MASTER_SSL_VERIFY_SERVER_CERT'),('MEDIUMINT'),('MINUTE_MICROSECOND'),('MODIFIES'),('NO_WRITE_TO_BINLOG'),('ON'),('OPTIONALLY'),('OUT'),('PRECISION'),('PURGE'),('READS'),
	('REFERENCES'),('RENAME'),('REQUIRE'),('REVOKE'),('SCHEMA'),('SELECT'),('SET'),('SPATIAL'),('SQLEXCEPTION'),('SQL_BIG_RESULT'),('SSL'),('TABLE'),('TINYBLOB'),('TO'),('TRUE'),('UNIQUE'),
	('UPDATE'),('USING'),('UTC_TIMESTAMP'),('VARCHAR'),('WHEN'),('WITH'),('YEAR_MONTH'),('ADD'),('ANALYZE'),('ASC'),('BETWEEN'),('BLOB'),('CALL'),('CHANGE'),('CHECK'),('CONDITION'),('CONVERT'),
	('CURRENT_DATE'),('CURRENT_USER'),('DATABASES'),('DAY_MINUTE'),('DECIMAL'),('DELAYED'),('DESCRIBE'),('DISTINCTROW'),('DROP'),('ELSE'),('ESCAPED'),('EXPLAIN'),('FLOAT'),('FOR'),('FROM'),
	('GROUP'),('HOUR_MICROSECOND'),('IF'),('INDEX'),('INOUT'),('INT'),('INT3'),('INTEGER'),('IS'),('KEY'),('LEADING'),('LIKE'),('LINES'),('LOCALTIMESTAMP'),('LONGBLOB'),('LOW_PRIORITY'),
	('MEDIUMBLOB'),('MIDDLEINT'),('MOD'),('NOT'),('NUMERIC'),('OPTION'),('ORDER'),('OUTFILE'),('PROCEDURE'),('READ'),('REAL'),('RELEASE'),('REPLACE'),('RETURN'),('RLIKE'),('SECOND_MICROSECOND'),
	('SEPARATOR'),('SMALLINT'),('SQL'),('SQLWARNING'),('SQL_SMALL_RESULT'),('STRAIGHT_JOIN'),('THEN'),('TINYTEXT'),('TRIGGER'),('UNION'),('UNSIGNED'),('USE'),('UTC_TIME'),('VARBINARY'),('VARYING'),
	('WHILE'),('XOR'),('FULL'),('COLUMNS'),('MIN'),('MAX'),('STDEV'),('COUNT')
  ]);
  var operatorChars = /[*+\-<>=&|]/;

  function tokenBase(stream, state) {
    var ch = stream.next();
    curPunc = null;
    if (ch == "$" || ch == "?") {
      stream.match(/^[\w\d]*/);
      return "variable-2";
    }
    else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) {
      stream.match(/^[^\s\u00a0>]*>?/);
      return "atom";
    }
    else if (ch == "\"" || ch == "'") {
      state.tokenize = tokenLiteral(ch);
      return state.tokenize(stream, state);
    }
    else if (ch == "`") {
      state.tokenize = tokenOpLiteral(ch);
      return state.tokenize(stream, state);
    }
    else if (/[{}\(\),\.;\[\]]/.test(ch)) {
      curPunc = ch;
      return null;
    }
    else if (ch == "-") {
      var ch2 = stream.next();
      if (ch2=="-") {
      	stream.skipToEnd();
      	return "comment";
      }
    }
    else if (operatorChars.test(ch)) {
      stream.eatWhile(operatorChars);
      return null;
    }
    else if (ch == ":") {
      stream.eatWhile(/[\w\d\._\-]/);
      return "atom";
    }
    else {
      stream.eatWhile(/[_\w\d]/);
      if (stream.eat(":")) {
        stream.eatWhile(/[\w\d_\-]/);
        return "atom";
      }
      var word = stream.current(), type;
      if (ops.test(word))
        return null;
      else if (keywords.test(word))
        return "keyword";
      else
        return "variable";
    }
  }

  function tokenLiteral(quote) {
    return function(stream, state) {
      var escaped = false, ch;
      while ((ch = stream.next()) != null) {
        if (ch == quote && !escaped) {
          state.tokenize = tokenBase;
          break;
        }
        escaped = !escaped && ch == "\\";
      }
      return "string";
    };
  }

  function tokenOpLiteral(quote) {
    return function(stream, state) {
      var escaped = false, ch;
      while ((ch = stream.next()) != null) {
        if (ch == quote && !escaped) {
          state.tokenize = tokenBase;
          break;
        }
        escaped = !escaped && ch == "\\";
      }
      return "variable-2";
    };
  }

  function pushContext(state, type, col) {
    state.context = {prev: state.context, indent: state.indent, col: col, type: type};
  }
  function popContext(state) {
    state.indent = state.context.indent;
    state.context = state.context.prev;
  }

  return {
    startState: function(base) {
      return {tokenize: tokenBase,
              context: null,
              indent: 0,
              col: 0};
    },

    token: function(stream, state) {
      if (stream.sol()) {
        if (state.context && state.context.align == null) state.context.align = false;
        state.indent = stream.indentation();
      }
      if (stream.eatSpace()) return null;
      var style = state.tokenize(stream, state);

      if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") {
        state.context.align = true;
      }

      if (curPunc == "(") pushContext(state, ")", stream.column());
      else if (curPunc == "[") pushContext(state, "]", stream.column());
      else if (curPunc == "{") pushContext(state, "}", stream.column());
      else if (/[\]\}\)]/.test(curPunc)) {
        while (state.context && state.context.type == "pattern") popContext(state);
        if (state.context && curPunc == state.context.type) popContext(state);
      }
      else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state);
      else if (/atom|string|variable/.test(style) && state.context) {
        if (/[\}\]]/.test(state.context.type))
          pushContext(state, "pattern", stream.column());
        else if (state.context.type == "pattern" && !state.context.align) {
          state.context.align = true;
          state.context.col = stream.column();
        }
      }

      return style;
    },

    indent: function(state, textAfter) {
      var firstChar = textAfter && textAfter.charAt(0);
      var context = state.context;
      if (/[\]\}]/.test(firstChar))
        while (context && context.type == "pattern") context = context.prev;

      var closing = context && firstChar == context.type;
      if (!context)
        return 0;
      else if (context.type == "pattern")
        return context.col;
      else if (context.align)
        return context.col + (closing ? 0 : 1);
      else
        return context.indent + (closing ? 0 : indentUnit);
    }
  };
});

CodeMirror.defineMIME("text/x-mysql", "mysql");
<commit_msg>[mysql mode] Support /* */ comments<commit_after>/*
 *	MySQL Mode for CodeMirror 2 by MySQL-Tools
 *	@author James Thorne (partydroid)
 *	@link 	http://github.com/partydroid/MySQL-Tools
 * 	@link 	http://mysqltools.org
 *	@version 02/Jan/2012
*/
CodeMirror.defineMode("mysql", function(config) {
  var indentUnit = config.indentUnit;
  var curPunc;

  function wordRegexp(words) {
    return new RegExp("^(?:" + words.join("|") + ")$", "i");
  }
  var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri",
                        "isblank", "isliteral", "union", "a"]);
  var keywords = wordRegexp([
  ('ACCESSIBLE'),('ALTER'),('AS'),('BEFORE'),('BINARY'),('BY'),('CASE'),('CHARACTER'),('COLUMN'),('CONTINUE'),('CROSS'),('CURRENT_TIMESTAMP'),('DATABASE'),('DAY_MICROSECOND'),('DEC'),('DEFAULT'),
	('DESC'),('DISTINCT'),('DOUBLE'),('EACH'),('ENCLOSED'),('EXIT'),('FETCH'),('FLOAT8'),('FOREIGN'),('GRANT'),('HIGH_PRIORITY'),('HOUR_SECOND'),('IN'),('INNER'),('INSERT'),('INT2'),('INT8'),
	('INTO'),('JOIN'),('KILL'),('LEFT'),('LINEAR'),('LOCALTIME'),('LONG'),('LOOP'),('MATCH'),('MEDIUMTEXT'),('MINUTE_SECOND'),('NATURAL'),('NULL'),('OPTIMIZE'),('OR'),('OUTER'),('PRIMARY'),
	('RANGE'),('READ_WRITE'),('REGEXP'),('REPEAT'),('RESTRICT'),('RIGHT'),('SCHEMAS'),('SENSITIVE'),('SHOW'),('SPECIFIC'),('SQLSTATE'),('SQL_CALC_FOUND_ROWS'),('STARTING'),('TERMINATED'),
	('TINYINT'),('TRAILING'),('UNDO'),('UNLOCK'),('USAGE'),('UTC_DATE'),('VALUES'),('VARCHARACTER'),('WHERE'),('WRITE'),('ZEROFILL'),('ALL'),('AND'),('ASENSITIVE'),('BIGINT'),('BOTH'),('CASCADE'),
	('CHAR'),('COLLATE'),('CONSTRAINT'),('CREATE'),('CURRENT_TIME'),('CURSOR'),('DAY_HOUR'),('DAY_SECOND'),('DECLARE'),('DELETE'),('DETERMINISTIC'),('DIV'),('DUAL'),('ELSEIF'),('EXISTS'),('FALSE'),
	('FLOAT4'),('FORCE'),('FULLTEXT'),('HAVING'),('HOUR_MINUTE'),('IGNORE'),('INFILE'),('INSENSITIVE'),('INT1'),('INT4'),('INTERVAL'),('ITERATE'),('KEYS'),('LEAVE'),('LIMIT'),('LOAD'),('LOCK'),
	('LONGTEXT'),('MASTER_SSL_VERIFY_SERVER_CERT'),('MEDIUMINT'),('MINUTE_MICROSECOND'),('MODIFIES'),('NO_WRITE_TO_BINLOG'),('ON'),('OPTIONALLY'),('OUT'),('PRECISION'),('PURGE'),('READS'),
	('REFERENCES'),('RENAME'),('REQUIRE'),('REVOKE'),('SCHEMA'),('SELECT'),('SET'),('SPATIAL'),('SQLEXCEPTION'),('SQL_BIG_RESULT'),('SSL'),('TABLE'),('TINYBLOB'),('TO'),('TRUE'),('UNIQUE'),
	('UPDATE'),('USING'),('UTC_TIMESTAMP'),('VARCHAR'),('WHEN'),('WITH'),('YEAR_MONTH'),('ADD'),('ANALYZE'),('ASC'),('BETWEEN'),('BLOB'),('CALL'),('CHANGE'),('CHECK'),('CONDITION'),('CONVERT'),
	('CURRENT_DATE'),('CURRENT_USER'),('DATABASES'),('DAY_MINUTE'),('DECIMAL'),('DELAYED'),('DESCRIBE'),('DISTINCTROW'),('DROP'),('ELSE'),('ESCAPED'),('EXPLAIN'),('FLOAT'),('FOR'),('FROM'),
	('GROUP'),('HOUR_MICROSECOND'),('IF'),('INDEX'),('INOUT'),('INT'),('INT3'),('INTEGER'),('IS'),('KEY'),('LEADING'),('LIKE'),('LINES'),('LOCALTIMESTAMP'),('LONGBLOB'),('LOW_PRIORITY'),
	('MEDIUMBLOB'),('MIDDLEINT'),('MOD'),('NOT'),('NUMERIC'),('OPTION'),('ORDER'),('OUTFILE'),('PROCEDURE'),('READ'),('REAL'),('RELEASE'),('REPLACE'),('RETURN'),('RLIKE'),('SECOND_MICROSECOND'),
	('SEPARATOR'),('SMALLINT'),('SQL'),('SQLWARNING'),('SQL_SMALL_RESULT'),('STRAIGHT_JOIN'),('THEN'),('TINYTEXT'),('TRIGGER'),('UNION'),('UNSIGNED'),('USE'),('UTC_TIME'),('VARBINARY'),('VARYING'),
	('WHILE'),('XOR'),('FULL'),('COLUMNS'),('MIN'),('MAX'),('STDEV'),('COUNT')
  ]);
  var operatorChars = /[*+\-<>=&|]/;

  function tokenBase(stream, state) {
    var ch = stream.next();
    curPunc = null;
    if (ch == "$" || ch == "?") {
      stream.match(/^[\w\d]*/);
      return "variable-2";
    }
    else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) {
      stream.match(/^[^\s\u00a0>]*>?/);
      return "atom";
    }
    else if (ch == "\"" || ch == "'") {
      state.tokenize = tokenLiteral(ch);
      return state.tokenize(stream, state);
    }
    else if (ch == "`") {
      state.tokenize = tokenOpLiteral(ch);
      return state.tokenize(stream, state);
    }
    else if (/[{}\(\),\.;\[\]]/.test(ch)) {
      curPunc = ch;
      return null;
    }
    else if (ch == "-" && stream.eat("-")) {
      stream.skipToEnd();
      return "comment";
    }
    else if (ch == "/" && stream.eat("*")) {
      state.tokenize = tokenComment;
      return state.tokenize(stream, state);
    }
    else if (operatorChars.test(ch)) {
      stream.eatWhile(operatorChars);
      return null;
    }
    else if (ch == ":") {
      stream.eatWhile(/[\w\d\._\-]/);
      return "atom";
    }
    else {
      stream.eatWhile(/[_\w\d]/);
      if (stream.eat(":")) {
        stream.eatWhile(/[\w\d_\-]/);
        return "atom";
      }
      var word = stream.current(), type;
      if (ops.test(word))
        return null;
      else if (keywords.test(word))
        return "keyword";
      else
        return "variable";
    }
  }

  function tokenLiteral(quote) {
    return function(stream, state) {
      var escaped = false, ch;
      while ((ch = stream.next()) != null) {
        if (ch == quote && !escaped) {
          state.tokenize = tokenBase;
          break;
        }
        escaped = !escaped && ch == "\\";
      }
      return "string";
    };
  }

  function tokenOpLiteral(quote) {
    return function(stream, state) {
      var escaped = false, ch;
      while ((ch = stream.next()) != null) {
        if (ch == quote && !escaped) {
          state.tokenize = tokenBase;
          break;
        }
        escaped = !escaped && ch == "\\";
      }
      return "variable-2";
    };
  }

  function tokenComment(stream, state) {
    for (;;) {
      if (stream.skipTo("*")) {
        stream.next();
        if (stream.eat("/")) {
          state.tokenize = tokenBase;
          break;
        }
      } else {
        stream.skipToEnd();
        break;
      }
    }
    return "comment";
  }

  function pushContext(state, type, col) {
    state.context = {prev: state.context, indent: state.indent, col: col, type: type};
  }
  function popContext(state) {
    state.indent = state.context.indent;
    state.context = state.context.prev;
  }

  return {
    startState: function(base) {
      return {tokenize: tokenBase,
              context: null,
              indent: 0,
              col: 0};
    },

    token: function(stream, state) {
      if (stream.sol()) {
        if (state.context && state.context.align == null) state.context.align = false;
        state.indent = stream.indentation();
      }
      if (stream.eatSpace()) return null;
      var style = state.tokenize(stream, state);

      if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") {
        state.context.align = true;
      }

      if (curPunc == "(") pushContext(state, ")", stream.column());
      else if (curPunc == "[") pushContext(state, "]", stream.column());
      else if (curPunc == "{") pushContext(state, "}", stream.column());
      else if (/[\]\}\)]/.test(curPunc)) {
        while (state.context && state.context.type == "pattern") popContext(state);
        if (state.context && curPunc == state.context.type) popContext(state);
      }
      else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state);
      else if (/atom|string|variable/.test(style) && state.context) {
        if (/[\}\]]/.test(state.context.type))
          pushContext(state, "pattern", stream.column());
        else if (state.context.type == "pattern" && !state.context.align) {
          state.context.align = true;
          state.context.col = stream.column();
        }
      }

      return style;
    },

    indent: function(state, textAfter) {
      var firstChar = textAfter && textAfter.charAt(0);
      var context = state.context;
      if (/[\]\}]/.test(firstChar))
        while (context && context.type == "pattern") context = context.prev;

      var closing = context && firstChar == context.type;
      if (!context)
        return 0;
      else if (context.type == "pattern")
        return context.col;
      else if (context.align)
        return context.col + (closing ? 0 : 1);
      else
        return context.indent + (closing ? 0 : indentUnit);
    }
  };
});

CodeMirror.defineMIME("text/x-mysql", "mysql");
<|endoftext|>


<commit_before>import Component from '../../view/components/component';
import {VALIDATION_NAME} from '../definition';

const ruleBindings = {
	length_between: '<? lengthBetween',
	length_equal: '<? lengthEqual',
	min_length: '<? minLength',
	max_length: '<? maxLength',
	one_of: '<? oneOf',
	positive_integer: '@? positiveInteger',
	required: '@?'
};
const bindings = {
	for: '@',
	key: '@'
};
Object.assign(bindings, ruleBindings);

class Rule extends Component {
	constructor() {
		super(...arguments);
	}

	onInit() {
		const predefinedRules = Object.keys(ruleBindings);
		const gridModel = this.validation.model;
		const validation = gridModel.validation;
		const rules = Array.from(validation().rules);
		const rule = {
			for: this.for,
			key: this.key
		};
		for (let name of predefinedRules) {
			if (this.hasOwnProperty(name)) {
				rule[name] = this[name];
			}
		}

		rules.push(rule);
		validation({rules});
	}
}

Rule.$inject = [];

export default {
	controller: Rule,
	require: {
		validation: `^^${VALIDATION_NAME}`
	},
	controllerAs: '$rule',
	bindings: bindings
};
<commit_msg>add new rule bindings<commit_after>import Component from '../../view/components/component';
import {VALIDATION_NAME} from '../definition';

const ruleBindings = {

	// Common Rules
	required: '@?',
	not_empty_list: '@? notEmptyList',
	any_object: '@? anyObject',

	// String Rules
	eq: '<? equal',
	string: '@?',
	length_between: '<? lengthBetween',
	length_equal: '<? lengthEqual',
	min_length: '<? minLength',
	max_length: '<? maxLength',
	one_of: '<? oneOf',
	like: '<? pattern',

	// Numeric Rules
	integer: '@?',
	positive_integer: '@? positiveInteger',
	decimal: '@?',
	positive_decimal: '@? positiveDecimal',
	max_number: '<? maxNumber',
	min_number: '<? minNumber',
	number_between: '<? numberBetween',

	// Special Rules
	email: '@?',
	url: '@?',
	iso_date: '@? isoDate',
	equal_to_field: '@? equalToField'
};
const bindings = {
	for: '@',
	key: '@'
};
Object.assign(bindings, ruleBindings);

class Rule extends Component {
	constructor() {
		super(...arguments);
	}

	onInit() {
		const predefinedRules = Object.keys(ruleBindings);
		const gridModel = this.validation.model;
		const validation = gridModel.validation;
		const rules = Array.from(validation().rules);
		const rule = {
			for: this.for,
			key: this.key
		};
		for (let name of predefinedRules) {
			if (this.hasOwnProperty(name)) {
				rule[name] = this[name];
			}
		}

		rules.push(rule);
		validation({rules});
	}
}

Rule.$inject = [];

export default {
	controller: Rule,
	require: {
		validation: `^^${VALIDATION_NAME}`
	},
	controllerAs: '$rule',
	bindings: bindings
};
<|endoftext|>