<commit_before>'use strict';

/* global Connector, MetadataFilter */

var scrobbleMusicOnly = false;
chrome.storage.local.get('Connectors', function(data) {
	if (data && data.Connectors && data.Connectors.YouTube) {
		var options = data.Connectors.YouTube;
		if (options.scrobbleMusicOnly === true) {
			scrobbleMusicOnly = true;
		}

		console.log('connector options: ' + JSON.stringify(options));
	}
});

Connector.videoSelector = '#player-api .html5-main-video';

Connector.artistTrackSelector = '#eow-title';

Connector.escapeBadTimeValues = function (time) {
	if (typeof time !== 'number') {
		return null;
	}
	if (isNaN(time) || !isFinite(time)) {
		return null;
	}
	return time;
};

/**
 * Because player can be still present in the page, we need to detect that it's invisible
 * and don't return current time. Otherwise resulting state may not be considered empty.
 */
Connector.getCurrentTime = function() {
	if (isPlayerOffscreen()) {
		return null;
	}
	const currentTime = $(this.videoSelector).prop('currentTime');
	return this.escapeBadTimeValues(currentTime);
};

/**
 * Because player can be still present in the page, we need to detect that it's invisible
 * and don't return duration. Otherwise resulting state may not be considered empty.
 */
Connector.getDuration = function() {
	if (isPlayerOffscreen()) {
		return null;
	}
	const duration = $(this.videoSelector).prop('duration');
	return this.escapeBadTimeValues(duration);
};

Connector.getUniqueID = function() {
	var url = window.location.href;
	var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
	var match = url.match(regExp);
	if (match && match[7].length === 11){
		return match[7];
	}
};

Connector.isPlaying = function() {
	return $('#player-api .html5-video-player').hasClass('playing-mode');
};

Connector.isStateChangeAllowed = function() {
	var videoCategory = $('meta[itemprop=\"genre\"]').attr('content');
	return !scrobbleMusicOnly || (scrobbleMusicOnly && videoCategory === 'Music');
};

Connector.getArtistTrack = function () {
	var text =$(Connector.artistTrackSelector).text();

	// Remove [genre] from the beginning of the title
	text = text.replace(/^\[[^\]]+\]\s*-*\s*/i, '');

	let {artist, track} = Connector.splitArtistTrack(text);
	if (artist === null && track === null) {
		// Look for Artist "Track"
		let artistTrack = text.match(/(.+?)\s"(.+?)"/);
		if (artistTrack) {
			artist = artistTrack[1];
			track = artistTrack[2];
		}
	}
	return {artist, track};
};

Connector.filter = MetadataFilter.getYoutubeFilter();

/**
 * YouTube doesn't really unload the player. It simply moves it outside viewport.
 * That has to be checked, because our selectors are still able to detect it.
 */
function isPlayerOffscreen() {
	var $player = $('#player-api');
	if ($player.length === 0) {
		return false;
	}

	var offset = $player.offset();
	return offset.left < 0 || offset.top < 0;
}

function setupMutationObserver() {
	let isMusicVideoPresent = false;

	let playerObserver = new MutationObserver(function() {
		if (!isPlayerOffscreen()) {
			if (isMusicVideoPresent) {
				return;
			}

			$(Connector.videoSelector).on('timeupdate', () => {
				Connector.onStateChanged();
			});
			isMusicVideoPresent = true;
		} else {
			Connector.onStateChanged();
			isMusicVideoPresent = false;
		}
	});

	let pageElement = document.getElementById('page');
	playerObserver.observe(pageElement, {
		subtree: true,
		childList: true,
		attributes: false,
		characterData: false
	});
}

setupMutationObserver();
<commit_msg>Youtube: Get uniqueId from 'meta' tag data<commit_after>'use strict';

/* global Connector, MetadataFilter */

var scrobbleMusicOnly = false;
chrome.storage.local.get('Connectors', function(data) {
	if (data && data.Connectors && data.Connectors.YouTube) {
		var options = data.Connectors.YouTube;
		if (options.scrobbleMusicOnly === true) {
			scrobbleMusicOnly = true;
		}

		console.log('connector options: ' + JSON.stringify(options));
	}
});

Connector.videoSelector = '#player-api .html5-main-video';

Connector.artistTrackSelector = '#eow-title';

Connector.escapeBadTimeValues = function (time) {
	if (typeof time !== 'number') {
		return null;
	}
	if (isNaN(time) || !isFinite(time)) {
		return null;
	}
	return time;
};

/**
 * Because player can be still present in the page, we need to detect that it's invisible
 * and don't return current time. Otherwise resulting state may not be considered empty.
 */
Connector.getCurrentTime = function() {
	if (isPlayerOffscreen()) {
		return null;
	}
	const currentTime = $(this.videoSelector).prop('currentTime');
	return this.escapeBadTimeValues(currentTime);
};

/**
 * Because player can be still present in the page, we need to detect that it's invisible
 * and don't return duration. Otherwise resulting state may not be considered empty.
 */
Connector.getDuration = function() {
	if (isPlayerOffscreen()) {
		return null;
	}
	const duration = $(this.videoSelector).prop('duration');
	return this.escapeBadTimeValues(duration);
};

Connector.getUniqueID = function() {
	return $('meta[itemprop="videoId"]').attr('content');
};

Connector.isPlaying = function() {
	return $('#player-api .html5-video-player').hasClass('playing-mode');
};

Connector.isStateChangeAllowed = function() {
	var videoCategory = $('meta[itemprop=\"genre\"]').attr('content');
	return !scrobbleMusicOnly || (scrobbleMusicOnly && videoCategory === 'Music');
};

Connector.getArtistTrack = function () {
	var text =$(Connector.artistTrackSelector).text();

	// Remove [genre] from the beginning of the title
	text = text.replace(/^\[[^\]]+\]\s*-*\s*/i, '');

	let {artist, track} = Connector.splitArtistTrack(text);
	if (artist === null && track === null) {
		// Look for Artist "Track"
		let artistTrack = text.match(/(.+?)\s"(.+?)"/);
		if (artistTrack) {
			artist = artistTrack[1];
			track = artistTrack[2];
		}
	}
	return {artist, track};
};

Connector.filter = MetadataFilter.getYoutubeFilter();

/**
 * YouTube doesn't really unload the player. It simply moves it outside viewport.
 * That has to be checked, because our selectors are still able to detect it.
 */
function isPlayerOffscreen() {
	var $player = $('#player-api');
	if ($player.length === 0) {
		return false;
	}

	var offset = $player.offset();
	return offset.left < 0 || offset.top < 0;
}

function setupMutationObserver() {
	let isMusicVideoPresent = false;

	let playerObserver = new MutationObserver(function() {
		if (!isPlayerOffscreen()) {
			if (isMusicVideoPresent) {
				return;
			}

			$(Connector.videoSelector).on('timeupdate', () => {
				Connector.onStateChanged();
			});
			isMusicVideoPresent = true;
		} else {
			Connector.onStateChanged();
			isMusicVideoPresent = false;
		}
	});

	let pageElement = document.getElementById('page');
	playerObserver.observe(pageElement, {
		subtree: true,
		childList: true,
		attributes: false,
		characterData: false
	});
}

setupMutationObserver();
<|endoftext|>


<commit_before>import styled, { css } from 'styled-components';
import PropTypes from 'prop-types';
import classicThemeForPill from './pill-classic.style';
import styleConfig from './pill.style.config';
import { baseTheme } from '../../style/themes';
import { isClassic } from '../../utils/helpers/style-helper';
import OptionsHelper from '../../utils/helpers/options-helper';
import StyledIcon from '../icon/icon.style';

function addStyleToPillIcon(padding, fontSize, margin) {
  return `
    ${StyledIcon} {
      padding: ${padding};
      margin-top: ${margin};

      &:before {
        font-size: ${fontSize};
      }
    }
  `;
}

const PillStyle = styled.span`
 ${({
    colorVariant, theme, inFill, isDeletable, pillRole, size, ml, mr
  }) => {
    const { colors, text } = baseTheme;

    let carbonColor = colorVariant;
    if (!isClassic(theme) && !hasCarbonColorVariant(colorVariant)) {
      carbonColor = 'neutral';
    }
    const variety = (pillRole === 'status') ? carbonColor : 'primary';
    const { varietyColor, buttonFocus } = styleConfig(theme)[pillRole][variety];

    return css`
      border-radius: 12px;
      font-size: 10px;
      letter-spacing: 0.7px;
      font-weight: 600;
      position: relative;
      display: inline-block;
      text-align: center;

      ${hasCarbonColorVariant(carbonColor) && css`
        border: 2px solid ${varietyColor};
        height: auto;

        ${inFill && css`
          background-color: ${varietyColor};
          color: ${(variety === 'warning') ? text.color : colors.white};
        `}

        ${size === 'S' && css`
          min-height: 16px;
          line-height: 16px;
          font-size: 10px;
        `}

        ${size === 'M' && css`
          min-height: 20px;
          line-height: 20px;
          font-size: 12px;
        `}

        ${size === 'L' && css`
          min-height: 24px;
          line-height: 24px;
          font-size: 14px;
        `}

        ${size === 'XL' && css`
          min-height: 26px;
          line-height: 26px;
          font-size: 16px;
        `}

        ${isDeletable && css`
          button {
            -webkit-appearance: none;
            border-radius: 0 6px 6px 0;
            border: none;
            bottom: 0;
            font-size: 100%;
            position: absolute;
            right: 0;
            top: 0;
            width: 20px;
            margin: 0;
            line-height: 16px;

            ${inFill && css`
              background-color: ${varietyColor};
              color: ${(variety === 'warning') ? text.color : colors.white};
              ${StyledIcon} {
                color: ${(variety === 'warning') ? text.color : colors.white};
              }
            `}

            ${!inFill && css`
              background-color: transparent;
              color: ${text.color};
            `}

            &:focus {
              outline: none;
              box-shadow: 0 0 0 3px ${colors.focus};
              background-color: ${buttonFocus};
              & { color: ${(variety === 'warning') ? text.color : colors.white} }
              ::-moz-focus-inner {
                border: 0;
              }
              ${StyledIcon} {
                color: ${(variety === 'warning') ? text.color : colors.white};
              }
            }

            &:hover {
              background-color: ${buttonFocus};
              color: ${(variety === 'warning') ? text.color : colors.white};
              cursor: pointer;
              ${StyledIcon} {
                color: ${(variety === 'warning') ? text.color : colors.white};
              }
            }

            ${StyledIcon} {
              font-size: 12px;
              padding: 0 4px;

              &:hover,
              &:focus {
                color: ${(variety === 'warning') ? text.color : colors.white};
              }
            }
          }

          ${size === 'S' && css`
            padding: 0 24px 0 7px;

            button {
              padding: 0;
              border-radius: 0 8px 8px 0;
              line-height: 14px;

              ${addStyleToPillIcon('0', '7px')}
            }
          `}

          ${size === 'M' && css`
            padding: 0 32px 0 11px;
            border-radius: 12px;

            button {
              width: 24px;
              padding: 0;
              border-radius: 0 10px 10px 0;
              line-height: 15px;

              ${addStyleToPillIcon('2px 7px 3px 7px', '10px')}
            }
          `}

          ${size === 'L' && css`
            padding: 0 36px 0 15px;
            border-radius: 13px;

            button {
              width: 28px;
              padding: 0;
              border-radius: 0 11px 11px 0;
              line-height: 16px;

              ${addStyleToPillIcon('3px 8px 4px 8px', '12px', '1px')}
            }
          `}

          ${size === 'XL' && css`
            padding: 0 41px 0 19px;
            border-radius: 15px;

            button {
              width: 32px;
              padding: 0;
              border-radius: 0 12px 12px 0;
              line-height: 18px;

              ${addStyleToPillIcon('3px 9px 5px 9px', '13px', '1px')}
            }
          `}
        `}

        ${!isDeletable && css`
          ${size === 'S' && css`
            padding: 0 7px;

            button {
              padding: 0;
            }
          `}

          ${size === 'M' && css`
            padding: 0 11px;
            border-radius: 12px;

            button {
              width: 24px;
              padding: 0;
              border-radius: 0 8px 8px 0;
            }
          `}

          ${size === 'L' && css`
            padding: 0 15px;
            border-radius: 13px;

            button {
              width: 28px;
              padding: 0;
              border-radius: 0 10px 10px 0;
            }
          `}

          ${size === 'XL' && css`
            padding: 0 19px;
            border-radius: 15px;

            button {
              width: 32px;
              padding: 0;
              border-radius: 0 12px 12px 0;
            }
          `}
        `}
      `}

      ${ml && css`margin-left: ${ml * theme.spacing}px`};
      ${mr && css`margin-right: ${mr * theme.spacing}px`};

      ${isClassic(theme) && classicThemeForPill(colorVariant, inFill, isDeletable, size)}
    `;
  }
}
`;

function hasCarbonColorVariant(colorVariant) {
  return [...OptionsHelper.pillColors, 'warning'].includes(colorVariant);
}

PillStyle.defaultProps = {
  inFill: false,
  colorVariant: 'default',
  isDeletable: false,
  theme: baseTheme
};

PillStyle.propTypes = {
  inFill: PropTypes.bool,
  colorVariant: PropTypes.string,
  isDeletable: PropTypes.func,

  /** Assigns a size to the pill */
  size: PropTypes.oneOf(OptionsHelper.pillSizesRestricted)
};

export default PillStyle;
<commit_msg>fix(pill): fix incorrect margin top applied to pill<commit_after>import styled, { css } from 'styled-components';
import PropTypes from 'prop-types';
import classicThemeForPill from './pill-classic.style';
import styleConfig from './pill.style.config';
import { baseTheme } from '../../style/themes';
import { isClassic } from '../../utils/helpers/style-helper';
import OptionsHelper from '../../utils/helpers/options-helper';
import StyledIcon from '../icon/icon.style';

function addStyleToPillIcon(fontSize) {
  return `
    ${StyledIcon} {
      &:before {
        font-size: ${fontSize};
      }
    }
  `;
}

const PillStyle = styled.span`
 ${({
    colorVariant, theme, inFill, isDeletable, pillRole, size, ml, mr
  }) => {
    const { colors, text } = baseTheme;

    let carbonColor = colorVariant;
    if (!isClassic(theme) && !hasCarbonColorVariant(colorVariant)) {
      carbonColor = 'neutral';
    }
    const variety = (pillRole === 'status') ? carbonColor : 'primary';
    const { varietyColor, buttonFocus } = styleConfig(theme)[pillRole][variety];

    return css`
      border-radius: 12px;
      font-size: 10px;
      letter-spacing: 0.7px;
      font-weight: 600;
      position: relative;
      display: inline-flex;
      text-align: center;
      align-items: center;
      justify-content: center;

      ${hasCarbonColorVariant(carbonColor) && css`
        border: 2px solid ${varietyColor};
        height: auto;

        ${inFill && css`
          background-color: ${varietyColor};
          color: ${(variety === 'warning') ? text.color : colors.white};
        `}

        ${size === 'S' && css`
          min-height: 16px;
          line-height: 16px;
          font-size: 10px;
        `}

        ${size === 'M' && css`
          min-height: 20px;
          line-height: 20px;
          font-size: 12px;
        `}

        ${size === 'L' && css`
          min-height: 24px;
          line-height: 24px;
          font-size: 14px;
        `}

        ${size === 'XL' && css`
          min-height: 26px;
          line-height: 26px;
          font-size: 16px;
        `}

        ${isDeletable && css`
          button {
            -webkit-appearance: none;
            border-radius: 0 6px 6px 0;
            border: none;
            bottom: 0;
            font-size: 100%;
            position: absolute;
            right: 0;
            top: 0;
            width: 20px;
            margin: 0;
            line-height: 16px;

            ${inFill && css`
              background-color: ${varietyColor};
              color: ${(variety === 'warning') ? text.color : colors.white};
              ${StyledIcon} {
                color: ${(variety === 'warning') ? text.color : colors.white};
              }
            `}

            ${!inFill && css`
              background-color: transparent;
              color: ${text.color};
            `}

            &:focus {
              outline: none;
              box-shadow: 0 0 0 3px ${colors.focus};
              background-color: ${buttonFocus};
              & { color: ${(variety === 'warning') ? text.color : colors.white} }
              ::-moz-focus-inner {
                border: 0;
              }
              ${StyledIcon} {
                color: ${(variety === 'warning') ? text.color : colors.white};
              }
            }

            &:hover {
              background-color: ${buttonFocus};
              color: ${(variety === 'warning') ? text.color : colors.white};
              cursor: pointer;
              ${StyledIcon} {
                color: ${(variety === 'warning') ? text.color : colors.white};
              }
            }

            ${StyledIcon} {
              font-size: 12px;
              padding: 0 4px;

              &:hover,
              &:focus {
                color: ${(variety === 'warning') ? text.color : colors.white};
              }
            }
          }

          ${size === 'S' && css`
            padding: 0 24px 0 7px;

            button {
              padding: 0;
              border-radius: 0 8px 8px 0;
              line-height: 14px;

              ${addStyleToPillIcon('7px')}
            }
          `}

          ${size === 'M' && css`
            padding: 0 32px 0 11px;
            border-radius: 12px;

            button {
              width: 24px;
              padding: 0;
              border-radius: 0 10px 10px 0;
              line-height: 15px;

              ${addStyleToPillIcon('10px')}
            }
          `}

          ${size === 'L' && css`
            padding: 0 36px 0 15px;
            border-radius: 13px;

            button {
              width: 28px;
              padding: 0;
              border-radius: 0 11px 11px 0;
              line-height: 16px;

              ${addStyleToPillIcon('12px')}
            }
          `}

          ${size === 'XL' && css`
            padding: 0 41px 0 19px;
            border-radius: 15px;

            button {
              width: 32px;
              padding: 0;
              border-radius: 0 12px 12px 0;
              line-height: 18px;

              ${addStyleToPillIcon('13px')}
            }
          `}
        `}

        ${!isDeletable && css`
          ${size === 'S' && css`
            padding: 0 7px;

            button {
              padding: 0;
            }
          `}

          ${size === 'M' && css`
            padding: 0 11px;
            border-radius: 12px;

            button {
              width: 24px;
              padding: 0;
              border-radius: 0 8px 8px 0;
            }
          `}

          ${size === 'L' && css`
            padding: 0 15px;
            border-radius: 13px;

            button {
              width: 28px;
              padding: 0;
              border-radius: 0 10px 10px 0;
            }
          `}

          ${size === 'XL' && css`
            padding: 0 19px;
            border-radius: 15px;

            button {
              width: 32px;
              padding: 0;
              border-radius: 0 12px 12px 0;
            }
          `}
        `}
      `}

      ${ml && css`margin-left: ${ml * theme.spacing}px`};
      ${mr && css`margin-right: ${mr * theme.spacing}px`};

      ${isClassic(theme) && classicThemeForPill(colorVariant, inFill, isDeletable, size)}
    `;
  }
}
`;

function hasCarbonColorVariant(colorVariant) {
  return [...OptionsHelper.pillColors, 'warning'].includes(colorVariant);
}

PillStyle.defaultProps = {
  inFill: false,
  colorVariant: 'default',
  isDeletable: false,
  theme: baseTheme
};

PillStyle.propTypes = {
  inFill: PropTypes.bool,
  colorVariant: PropTypes.string,
  isDeletable: PropTypes.func,

  /** Assigns a size to the pill */
  size: PropTypes.oneOf(OptionsHelper.pillSizesRestricted)
};

export default PillStyle;
<|endoftext|>


<commit_before>export const ADD_UNIT = 'ADD_UNIT';
export const MAKE_UNIT_LIVE = 'MAKE_UNIT_LIVE';
export const MAKE_UNIT_GROW = 'MAKE_UNIT_GROW';
export const MAKE_UNIT_DIE = 'MAKE_UNIT_DIE';
<commit_msg>ActionType constants<commit_after>export const INIT_UNITS = 'INIT_UNITS';
export const UPDATE_UNIT_STATE = 'UPDATE_UNIT_STATE';
export const UPDATE_UNITS_STATE = 'UPDATE_UNITS_STATE';
export const GAME_BEGIN = 'GAME_BEGIN';
export const GAME_END = 'GAME_END';

export const UnitStates = {
  YOUNG: 'YOUNG',
  OLD: 'OLD',
  DEAD: 'DEAD',
}
<|endoftext|>


<commit_before><commit_msg>fix(gatsby): Use publicLoader in production-app (#16800)<commit_after><|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { Icon, RippleButton } from '../shared'
import { connect } from 'react-redux'
import { authActions } from 'src/core/auth'

export function SignIn({ signInWithFacebook, isAuthenticating }) {
  const signInButton = (
    <RippleButton
      className="glare-button"
      onClick={() => {
        setTimeout(() => {
          signInWithFacebook()
        }, 200)
      }}>
      <Icon icon="facebook" />
      {'Sign In'}
    </RippleButton>
  )

  return (

     {isAuthenticating ? null : signInButton}

  )
}

SignIn.propTypes = {
  isAuthenticating: PropTypes.bool.isRequired,
  signInWithFacebook: PropTypes.func.isRequired,
}

export default connect(state => ({
  isAuthenticating: state.auth.isAuthenticating,
}), authActions)(SignIn)
<commit_msg>Rearrange icon<commit_after>import React, { PropTypes } from 'react'
import { Icon, RippleButton } from '../shared'
import { connect } from 'react-redux'
import { authActions } from 'src/core/auth'

export function SignIn({ signInWithFacebook, isAuthenticating }) {
  const signInButton = (
    <RippleButton
      className="glare-button"
      onClick={() => {
        setTimeout(() => {
          signInWithFacebook()
        }, 200)
      }}>
      <Icon icon="facebook" />
      {'Sign In'}
    </RippleButton>
  )

  return (

     {isAuthenticating ? null : signInButton}

  )
}

SignIn.propTypes = {
  isAuthenticating: PropTypes.bool.isRequired,
  signInWithFacebook: PropTypes.func.isRequired,
}

export default connect(state => ({
  isAuthenticating: state.auth.isAuthenticating,
}), authActions)(SignIn)
<|endoftext|>


<commit_before>"use strict";
var every = require('schedule').every;
var Officer = (function () {
    function Officer(name, title) {
        this.name = name;
        this.title = title;
    }
    return Officer;
})();
var OfficerData = (function () {
    function OfficerData(title, people) {
        this.title = title;
        this.people = people;
    }
    return OfficerData;
})();
var OfficerList = (function () {
    function OfficerList(bus) {
        var _this = this;
        this.rotateList = function () {
            _this.currentList++;
            if (_this.currentList >= _this.lists.length) {
                _this.currentList = 0;
            }
        };
        this.updateWidgets = function () {
            console.log('Updating officers list');
            _this.bus.post({
                event: 'widgetUpdate',
                messageType: 'officers:update',
                messageData: _this.lists[_this.currentList]
            });
        };
        this.currentList = -1;
        this.lists = new Array();
        this.lists.push(new OfficerData('Administrative Officers', [
            { name: "Renard Rose", title: "President" },
            { name: "Ed Swift", title: "Vice President" },
            { name: "Sandy Byerly", title: "Secretary" },
            { name: "Brendan Devlin", title: "Treasurer" }
        ]));
        this.lists.push(new OfficerData('Fire Officers', [
            { name: "Chris Schwartz", title: "Chief" },
            { name: "Renard Rose", title: "Deputy Chief" },
            { name: "Tim Tygh", title: "Assistant Chief" },
            { name: "Scott Yoder", title: "Batallion Chief" },
            { name: "Bucky Swider", title: "Captain" },
            { name: "Jamie Viall", title: "Lieutenant" },
            { name: "Chris Hummel", title: "Lieutenant 1" },
            { name: "Pat Dicicco", title: "Safety Officer" },
            { name: "Mike Gaffney", title: "Chief Engineer" },
            { name: "Scott Rotenbury", title: "Fire Police Captain" }
        ]));
        this.lists.push(new OfficerData('Trustees', [
            { name: "Shel Klein", title: "Chairman" },
            { name: "Jamie Viall", title: "Secretary" },
            { name: "Pat Dicicco", title: "" },
            { name: "Tim Tygh", title: "" },
            { name: "William Keely", title: "" },
            { name: "John Lynch", title: "" },
            { name: "Scott Yoder", title: "" },
        ]));
        var instance = this;
        bus.subscribe({ event: 'userConnected' }, instance.updateWidgets);
        console.log('Setting officer update schedule');
        every('15s').do(function () {
            console.log('Officer update schedule triggered');
            instance.rotateList();
            instance.updateWidgets();
        });
        console.log('Done setting officer update schedule');
        this.bus = bus;
    }
    return OfficerList;
})();
exports.OfficerList = OfficerList;
//# sourceMappingURL=officers.js.map<commit_msg>Update officers.js<commit_after>"use strict";
var every = require('schedule').every;
var Officer = (function () {
    function Officer(name, title) {
        this.name = name;
        this.title = title;
    }
    return Officer;
})();
var OfficerData = (function () {
    function OfficerData(title, people) {
        this.title = title;
        this.people = people;
    }
    return OfficerData;
})();
var OfficerList = (function () {
    function OfficerList(bus) {
        var _this = this;
        this.rotateList = function () {
            _this.currentList++;
            if (_this.currentList >= _this.lists.length) {
                _this.currentList = 0;
            }
        };
        this.updateWidgets = function () {
            console.log('Updating officers list');
            _this.bus.post({
                event: 'widgetUpdate',
                messageType: 'officers:update',
                messageData: _this.lists[_this.currentList]
            });
        };
        this.currentList = -1;
        this.lists = new Array();
        this.lists.push(new OfficerData('Administrative Officers', [
            { name: "Renard Rose", title: "President" },
            { name: "Ed Swift", title: "Vice President" },
            { name: "Sandy Byerly", title: "Secretary" },
            { name: "Brendan Devlin", title: "Treasurer" },
            { name: "John Lynch", title: "Financial Secretary" }
       ]));
        this.lists.push(new OfficerData('Fire Officers', [
            { name: "Chris Schwartz", title: "Chief" },
            { name: "Renard Rose", title: "Deputy Chief" },
            { name: "Tim Tygh", title: "Assistant Chief" },
            { name: "Scott Yoder", title: "Batallion Chief" },
            { name: "Bucky Swider", title: "Captain" },
            { name: "Jamie Viall", title: "Lieutenant" },
            { name: "Chris Hummel", title: "Lieutenant 1" },
            { name: "Pat Dicicco", title: "Safety Officer" },
            { name: "Mike Gaffney", title: "Chief Engineer" },
            { name: "Scott Rotenbury", title: "Fire Police Captain" }
        ]));
        this.lists.push(new OfficerData('Trustees', [
            { name: "Shel Klein", title: "Chairman" },
            { name: "Jamie Viall", title: "Secretary" },
            { name: "Pat Dicicco", title: "" },
            { name: "Tim Tygh", title: "" },
            { name: "William Keely", title: "" },
            { name: "John Lynch", title: "" },
            { name: "Scott Yoder", title: "" },
        ]));
        var instance = this;
        bus.subscribe({ event: 'userConnected' }, instance.updateWidgets);
        console.log('Setting officer update schedule');
        every('15s').do(function () {
            console.log('Officer update schedule triggered');
            instance.rotateList();
            instance.updateWidgets();
        });
        console.log('Done setting officer update schedule');
        this.bus = bus;
    }
    return OfficerList;
})();
exports.OfficerList = OfficerList;
//# sourceMappingURL=officers.js.map
<|endoftext|>


<commit_before>import YearDateObject from './dateObjects/year-date-object';
import MonthDateObject from './dateObjects/month-date-object';
import WeekDateObject from './dateObjects/week-date-object';

function DateObjectFactory() {}

DateObjectFactory.prototype.createDateObject = function (interval, date) {
  if (interval === 'month') {
    return new MonthDateObject(date);
  }
  if (interval === 'week') {
    return new WeekDateObject(date);
  }
  return new YearDateObject(date);
};

export default DateObjectFactory;
<commit_msg>fix `if` statement for date-object-factory<commit_after>import YearDateObject from './dateObjects/year-date-object';
import MonthDateObject from './dateObjects/month-date-object';
import WeekDateObject from './dateObjects/week-date-object';

function DateObjectFactory() {}

DateObjectFactory.prototype.createDateObject = function (interval, date) {
  if (interval === 'month') {
    return new MonthDateObject(date);
  }

  if (interval === 'week') {
    return new WeekDateObject(date);
  }

  return new YearDateObject(date);
};

export default DateObjectFactory;
<|endoftext|>


<commit_before>import {join} from 'path';
import pascalCase from 'pascal-case';
import merge from 'lodash.merge';
import {transform, buildExternalHelpers} from 'babel-core';
import template from './react-class.tmpl';
import dependencyTemplate from './require.tmpl';

export default function createReactCodeFactory(application) {
	const config = application.configuration.transforms['react'] || {};

	return async function createReactCode(file, demo) {
		let helpers = buildExternalHelpers(undefined, 'var');
		let result = convertCode(file, config.opts);
		let requireBlock = createRequireBlock(getDependencies(file));
		result = helpers + requireBlock + result;
		if (demo) {
			demo.dependencies = {
				pattern: file
			};
			merge(demo.dependencies, file.dependencies);
			let demoResult = convertCode(demo, config.opts);
			let requireBlock = createRequireBlock(getDependencies(demo));
			demoResult = helpers + requireBlock + demoResult;
			file.demoSource = demo.source;
			file.demoBuffer = new Buffer(demoResult, 'utf-8');
		}

		file.buffer = result;
		file.in = config.inFormat;
		file.out = config.outFormat;
		return file;
	}
}

function convertCode(file, opts) {
	let source = file.buffer.toString('utf-8');
	// TODO: This is a weak criteria to check if we have to create a wrapper
	if (source.indexOf('extends React.Component') === -1 || source.indexOf('React.createClass') !== -1)	 {
		source = createWrappedRenderFunction(file, source);
	} else {
		source = rewriteImportsToGlobalNames(file, source);
	}
	return transform(source, merge({externalHelpers: true}, opts)).code;
}

function createWrappedRenderFunction(file, source) {
	let patternJson = loadPatternJson(file.path);
	let dependencies = writeDependencyImports(file).join('\n');
	return renderCodeTemplate(source, dependencies, template, pascalCase(patternJson.name));
}

function loadPatternJson(path) {
	return require(
		join(
			path.substring(0,
				path.lastIndexOf('/')), 'pattern.json'));
}

function writeDependencyImports(file) {
	let patterns = loadPatternJson(file.path).patterns || {};
	let dependencies = [];
	for (let name of Object.keys(file.dependencies)) {
		dependencies.push(`import ${pascalCase(name)} from '${patterns[name] || name}';`);
	}
	return dependencies;
}

function renderCodeTemplate(source, dependencies, template, className) {
	return template
		.replace('$$dependencies$$', dependencies)
		.replace('$$class-name$$', className)
		.replace('$$render-code$$', matchFirstJsxExpressionAndWrapWithReturn(source));
}

const TAG_START = '<[-_a-z0-9]+';
const ATTRIBUTE_NAME = '[-_a-z0-9]+';
const HTML_ATTRIBUTE_VALUE = `"[^"]*"`;
const REACT_ATTRIBUTE_VALUE = `{(?:{[^}]*}|[^}]*)}`;
const ATTRIBUTE_VALUE = `\\s*=\\s*(?:${HTML_ATTRIBUTE_VALUE}|${REACT_ATTRIBUTE_VALUE})`;
const NAMED_ATTRIBUTE= `(?:${ATTRIBUTE_NAME}(?:${ATTRIBUTE_VALUE})?)`;
const SPREAD_ATTRIBUTE = '{\\.\\.\\.[^}]+}';
const ATTRIBUTE = `(?:${NAMED_ATTRIBUTE}|${SPREAD_ATTRIBUTE})`;
const ATTRIBUTES = `(?:\\s+${ATTRIBUTE})*`;
const TAG_END = '\\s*\\/?>';
const EXPR = new RegExp(`(${TAG_START}${ATTRIBUTES}${TAG_END}[^]*)`, 'gi');
//console.log('EXPR', EXPR);

function matchFirstJsxExpressionAndWrapWithReturn(source) {
	return source.replace(EXPR, (match, jsxExpr) => {
		return 'return (\n' + jsxExpr/*.split('\n').map(line => indent + line).join('\n')*/ + '\n);\n'
	});
}

function rewriteImportsToGlobalNames(file, source) {
	let patterns = loadPatternJson(file.path).patterns || {};
	return source.replace(/(import\s+(?:\* as\s)?[^\s]+\s+from\s+["'])([^"']+)(["'];)/g, (match, before, name, after) => {
		return `${before}${patterns[name] || name}${after}`;
	});
}

function getDependencies(file) {
	let patterns = loadPatternJson(file.path).patterns || {};
	let dependencies = {};
	for (let name of Object.keys(file.dependencies)) {
		let globalName = patterns[name] || name;
		let dependencyFile = file.dependencies[name];
		dependencies[globalName] = dependencyFile;
		merge(dependencies, getDependencies(dependencyFile));
	}
	return dependencies;
}

function createRequireBlock(dependencies) {
	let source = [];
	for (let name of Object.keys(dependencies)) {
		source.push(`
			'${name}': function(module, exports, require) {
				${convertCode(dependencies[name]).split('\n').map(line => '\t\t\t' + line).join('\n')}
			}
		`);
	}
	return dependencyTemplate.replace('$$localDependencies$$', source.join('\n,'));
}
<commit_msg>Fixed demo dependencies<commit_after>import {join} from 'path';
import pascalCase from 'pascal-case';
import merge from 'lodash.merge';
import template from './react-class.tmpl';

export default function createReactCodeFactory(application) {
	const config = application.configuration.transforms['react'] || {};

	return async function createReactCode(file, demo) {
		let result = convertCode(file);
		if (demo) {
			demo.dependencies = {
				pattern: file
			};
			merge(demo.dependencies, file.dependencies);
			let demoResult = convertCode(demo);
			file.demoSource = demo.source;
			file.demoBuffer = new Buffer(demoResult, 'utf-8');
		}

		file.buffer = result;
		file.in = config.inFormat;
		file.out = config.outFormat;
		return file;
	}
}

function convertCode(file, removeReact = false) {
	let source = file.buffer.toString('utf-8');
	if (source.indexOf('export default class') === -1 || source.indexOf('React.createClass') !== -1)	 {
		source = createWrappedRenderFunction(file, source);
	}
	let dependencies = convertDependencies(file);
	return fixDependencyImports(source, dependencies, removeReact);
}

function createWrappedRenderFunction(file, source) {
	let patternJson = loadPatternJson(file.path);
	let dependencies = writeDependencyImports(file).join('\n');
	return renderCodeTemplate(source, dependencies, template, pascalCase(patternJson.name));
}

function loadPatternJson(path) {
	return require(
		join(
			path.substring(0,
				path.lastIndexOf('/')), 'pattern.json'));
}

function writeDependencyImports(file) {
	let dependencies = [];
	for (let dependencyName of Object.keys(file.dependencies)) {
		dependencies.push(`import ${pascalCase(dependencyName)} from '${dependencyName}';`);
	}
	return dependencies;
}

function renderCodeTemplate(source, dependencies, template, className) {
	return template
		.replace('$$dependencies$$', dependencies)
		.replace('$$class-name$$', className)
		.replace('$$render-code$$', matchFirstJsxExpressionAndWrapWithReturn(source));
}

function matchFirstJsxExpressionAndWrapWithReturn(source) {
	return source
		.replace(/(<[a-z0-9]+(?:\s+[a-z0-9]+=["{][^"}]*?["}]|\s+\{\.\.\.[^}]+\})*\s*\/?>[^]*)/gi,
			'return (\n$1\n);')
}

function convertDependencies(file) {
	let dependencies = {};
	for (let dependencyName of Object.keys(file.dependencies)) {
		let dependencyFile = file.dependencies[dependencyName];
		dependencies[dependencyName] = convertCode(dependencyFile, true);
	}
	return dependencies;
}

function fixDependencyImports(source, dependencies, removeReact) {
	// Replace import statements (but react) with a dumb module loader
	return source.replace(/^\s*import\s+(?:\*\s+as\s+)?(.*?)\s+from\s+['"]([-_a-zA-Z0-9]+)['"].*$/gm, (match, name, module) => {
		if (name === 'React' || module === 'react') {
			if (removeReact) {
				return '';
			}
			return "import * as React from 'react'";
		}
		return `let ${name} = (() => {
			${dependencies[module].replace("import * as React from 'react';", '').replace('export default ', 'return ')}
		})();
		`;
	})
}
<|endoftext|>


<commit_before>import React from 'react'
import renderer from 'react-test-renderer'
import * as enzyme from 'enzyme'
import * as emotion from 'emotion'
import styled from 'react-emotion'
import { createMatchers } from '../src'

const matchers = createMatchers(emotion)
const { toHaveStyleRule } = matchers

expect.extend(matchers)

describe('toHaveStyleRule', () => {
  const divStyle = emotion.css`
    color: red;
  `

  const svgStyle = emotion.css`
    width: 100%;
  `

  const enzymeMethods = ['shallow', 'mount', 'render']

  it('matches styles on the top-most node passed in', () => {
    const tree = renderer
      .create(

          <svg className={svgStyle} />

      )
      .toJSON()

    expect(tree).toHaveStyleRule('color', 'red')
    expect(tree).not.toHaveStyleRule('width', '100%')

    const svgNode = tree.children[0]

    expect(svgNode).toHaveStyleRule('width', '100%')
    expect(svgNode).not.toHaveStyleRule('color', 'red')
  })

  it('supports asymmetric matchers', () => {
    const tree = renderer
      .create(

          <svg className={svgStyle} />

      )
      .toJSON()

    expect(tree).toHaveStyleRule('color', expect.anything())
    expect(tree).not.toHaveStyleRule('padding', expect.anything())

    const svgNode = tree.children[0]

    expect(svgNode).toHaveStyleRule('width', expect.stringMatching(/.*%$/))
  })

  it('supports enzyme render methods', () => {
    const Component = () => (

        <svg className={svgStyle} />

    )

    enzymeMethods.forEach(method => {
      const wrapper = enzyme[method](<Component />)
      expect(wrapper).toHaveStyleRule('color', 'red')
      expect(wrapper).not.toHaveStyleRule('width', '100%')
      const svgNode = wrapper.find('svg')
      expect(svgNode).toHaveStyleRule('width', '100%')
      expect(svgNode).not.toHaveStyleRule('color', 'red')
    })
  })

  it('supports styled components', () => {
    const Div = styled('div')`
      color: red;
    `
    const Svg = styled('svg')`
      width: 100%;
    `

    enzymeMethods.forEach(method => {
      const wrapper = enzyme[method](

          <Svg />

      )
      expect(wrapper).toHaveStyleRule('color', 'red')
      expect(wrapper).not.toHaveStyleRule('width', '100%')
      const svgNode =
        method === 'render' ? wrapper.find('svg') : wrapper.find(Svg)
      expect(svgNode).toHaveStyleRule('width', '100%')
      expect(svgNode).not.toHaveStyleRule('color', 'red')
    })
  })

  it('fails if no styles are found', () => {
    const tree = renderer.create(
).toJSON()
    const result = toHaveStyleRule(tree, 'color', 'red')
    expect(result.pass).toBe(false)
    expect(result.message()).toBe('Property not found: color')
  })

  it('supports regex values', () => {
    const tree = renderer.create(
).toJSON()
    expect(tree).toHaveStyleRule('color', /red/)
  })

  it('returns a message explaining the failure', () => {
    const tree = renderer.create(
).toJSON()

    // When expect(tree).toHaveStyleRule('color', 'blue') fails
    const resultFail = toHaveStyleRule(tree, 'color', 'blue')
    expect(resultFail.message()).toMatchSnapshot()

    // When expect(tree).not.toHaveStyleRule('color', 'red')
    const resultPass = toHaveStyleRule(tree, 'color', 'red')
    expect(resultPass.message()).toMatchSnapshot()
  })
})
<commit_msg>Add a skip because chalk seems to be acting strangely on travis<commit_after>import React from 'react'
import renderer from 'react-test-renderer'
import * as enzyme from 'enzyme'
import * as emotion from 'emotion'
import styled from 'react-emotion'
import { createMatchers } from '../src'

const matchers = createMatchers(emotion)
const { toHaveStyleRule } = matchers

expect.extend(matchers)

describe('toHaveStyleRule', () => {
  const divStyle = emotion.css`
    color: red;
  `

  const svgStyle = emotion.css`
    width: 100%;
  `

  const enzymeMethods = ['shallow', 'mount', 'render']

  it('matches styles on the top-most node passed in', () => {
    const tree = renderer
      .create(

          <svg className={svgStyle} />

      )
      .toJSON()

    expect(tree).toHaveStyleRule('color', 'red')
    expect(tree).not.toHaveStyleRule('width', '100%')

    const svgNode = tree.children[0]

    expect(svgNode).toHaveStyleRule('width', '100%')
    expect(svgNode).not.toHaveStyleRule('color', 'red')
  })

  it('supports asymmetric matchers', () => {
    const tree = renderer
      .create(

          <svg className={svgStyle} />

      )
      .toJSON()

    expect(tree).toHaveStyleRule('color', expect.anything())
    expect(tree).not.toHaveStyleRule('padding', expect.anything())

    const svgNode = tree.children[0]

    expect(svgNode).toHaveStyleRule('width', expect.stringMatching(/.*%$/))
  })

  it('supports enzyme render methods', () => {
    const Component = () => (

        <svg className={svgStyle} />

    )

    enzymeMethods.forEach(method => {
      const wrapper = enzyme[method](<Component />)
      expect(wrapper).toHaveStyleRule('color', 'red')
      expect(wrapper).not.toHaveStyleRule('width', '100%')
      const svgNode = wrapper.find('svg')
      expect(svgNode).toHaveStyleRule('width', '100%')
      expect(svgNode).not.toHaveStyleRule('color', 'red')
    })
  })

  it('supports styled components', () => {
    const Div = styled('div')`
      color: red;
    `
    const Svg = styled('svg')`
      width: 100%;
    `

    enzymeMethods.forEach(method => {
      const wrapper = enzyme[method](

          <Svg />

      )
      expect(wrapper).toHaveStyleRule('color', 'red')
      expect(wrapper).not.toHaveStyleRule('width', '100%')
      const svgNode =
        method === 'render' ? wrapper.find('svg') : wrapper.find(Svg)
      expect(svgNode).toHaveStyleRule('width', '100%')
      expect(svgNode).not.toHaveStyleRule('color', 'red')
    })
  })

  it('fails if no styles are found', () => {
    const tree = renderer.create(
).toJSON()
    const result = toHaveStyleRule(tree, 'color', 'red')
    expect(result.pass).toBe(false)
    expect(result.message()).toBe('Property not found: color')
  })

  it('supports regex values', () => {
    const tree = renderer.create(
).toJSON()
    expect(tree).toHaveStyleRule('color', /red/)
  })

  it.skip('returns a message explaining the failure', () => {
    const tree = renderer.create(
).toJSON()

    // When expect(tree).toHaveStyleRule('color', 'blue') fails
    const resultFail = toHaveStyleRule(tree, 'color', 'blue')
    expect(resultFail.message()).toMatchSnapshot()

    // When expect(tree).not.toHaveStyleRule('color', 'red')
    const resultPass = toHaveStyleRule(tree, 'color', 'red')
    expect(resultPass.message()).toMatchSnapshot()
  })
})
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { ListView } from 'react-native';
import { Container, Content } from 'native-base';
import JobListItem from '../../common/job-list-item/jobListItem';
import ListSectionHeader from '../../common/list-section-header/listSectionHeader';
import { JOB_STATUS } from '../../common/constants';

export default class MyJobsTab extends Component {
  static propTypes = {
    data: React.PropTypes.objectOf(
      React.PropTypes.arrayOf(
        React.PropTypes.shape({
          date: React.PropTypes.string.isRequired,
          status: React.PropTypes.oneOf(Object.values(JOB_STATUS)),
          title: React.PropTypes.string.isRequired,
        }).isRequired,
      ).isRequired,
    ).isRequired,
  };

  constructor(props) {
    super(props);

    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
    });

    this.state = {
      dataSource: ds.cloneWithRowsAndSections(this.props.data),
    };
  }

  renderRow = job => <JobListItem title={job.title} date={job.date} status={job.status} />;

  renderSectionHeader = (sectionData, sectionID) => <ListSectionHeader title={sectionID} />;

  render() {
    return (
      <Container>
        <Content>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this.renderRow}
            renderSectionHeader={this.renderSectionHeader}
          />
        </Content>
      </Container>
    );
  }
}
<commit_msg>Make MyJobsTab use AvatarListItem instead of JobListItem<commit_after>import React, { Component } from 'react';
import { ListView } from 'react-native';
import { Container, Content } from 'native-base';
import AvatarListItem from '../../common/avatar-list-item/avatarListItem';
import ListSectionHeader from '../../common/list-section-header/listSectionHeader';
import { JOB_STATUS } from '../../common/constants';

// Temporary logo
const LOGO_URL = 'https://facebook.github.io/react/img/logo_og.png';

export default class MyJobsTab extends Component {
  static propTypes = {
    data: React.PropTypes.objectOf(
      React.PropTypes.arrayOf(
        React.PropTypes.shape({
          date: React.PropTypes.string.isRequired,
          status: React.PropTypes.oneOf(Object.values(JOB_STATUS)),
          title: React.PropTypes.string.isRequired,
        }).isRequired,
      ).isRequired,
    ).isRequired,
  };

  constructor(props) {
    super(props);

    const ds = new ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
    });

    this.state = {
      dataSource: ds.cloneWithRowsAndSections(this.props.data),
    };
  }

  renderRow = job => <AvatarListItem
    title={job.title} note={job.date}
    status={job.status} icon={{ uri: LOGO_URL }}
  />;

  renderSectionHeader = (sectionData, sectionID) => <ListSectionHeader title={sectionID} />;

  render() {
    return (
      <Container>
        <Content>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this.renderRow}
            renderSectionHeader={this.renderSectionHeader}
          />
        </Content>
      </Container>
    );
  }
}
<|endoftext|>


<commit_before>describe("success event tracking", function () {

    var guideMarkup = $("
" +
        "link" +
        "link" +
        "
");

    var articleContainer = $("
link
")

    beforeEach(function () {
        $('a').unbind();
        articleContainer.clone().appendTo('body');
        guideMarkup.clone().appendTo('body');
        spyOn(GOVUK, 'sendToAnalytics');
    });

    afterEach(function () {
        Alphagov.delete_cookie("successEvents")
        $(".test-stub").remove();
        $.event.trigger("smartanswerOutcome");
    });

    describe("isTheSameArtefact", function () {
        it("should support basic case", function () {
            var result = GOVUK.Analytics.isTheSameArtefact(
                "http://www.gov.uk/claim-tax/first",
                "http://www.gov.uk/claim-tax/second");

            expect(result).toBeTruthy();
        });

        it("should support coming to very same url", function () {
            var result = GOVUK.Analytics.isTheSameArtefact(
                "http://www.gov.uk/claim-tax/first",
                "http://www.gov.uk/claim-tax/first");

            expect(result).toBeTruthy();
        });

        it("should support local anchor on previous url", function () {
            var result = GOVUK.Analytics.isTheSameArtefact(
                "http://www.gov.uk/claim-tax",
                "http://www.gov.uk/claim-tax#foobar");

            expect(result).toBeTruthy();
        });

        it("should support local anchor on current url", function () {
            var result = GOVUK.Analytics.isTheSameArtefact(
                "http://www.gov.uk/claim-tax#foobar",
                "http://www.gov.uk/claim-tax");

            expect(result).toBeTruthy();
        });
    });

    describe("isRootArtefact", function () {
        it("should be true for standard artefact url", function () {
            var result = GOVUK.Analytics.isRootOfArtefact("http://smartanswers.dev.gov.uk/student-finance-calculator");

            expect(result).toBeTruthy();
        });

        it("should be true for standard artefact url ending with a slash", function () {
            var result = GOVUK.Analytics.isRootOfArtefact("http://smartanswers.dev.gov.uk/student-finance-calculator/");

            expect(result).toBeTruthy();
        });

        it("should be false for non-root artefact url", function () {
            var result = GOVUK.Analytics.isRootOfArtefact("http://smartanswers.dev.gov.uk/student-finance-calculator/y");

            expect(result).toBeFalsy();
        });
    });

    describe("analytics integration", function () {
        it("should register entry event", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            var expectedDataToSendToGoogle = ['_trackEvent', 'MS_guide', '99999', 'Entry'];
            expect(arguments.length).toBe(1);
            // using JSONEquals because there is a bug in the .toHaveBeenCalledWith() method
            // see: https://github.com/pivotal/jasmine/issues/45
            expect(arguments[0][0]).toBeEqualAsJSON(expectedDataToSendToGoogle);
        });

        it("should not register an entry event if there is no need id", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = undefined;
            GOVUK.Analytics.startAnalytics();

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(0);
        });

        it("should only call guide strategy when format is guide", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers, 'guide');
            spyOn(GOVUK.Analytics.Trackers, 'transaction');

            GOVUK.Analytics.startAnalytics();

            expect(GOVUK.Analytics.Trackers.transaction).not.toHaveBeenCalled();
            expect(GOVUK.Analytics.Trackers.guide).toHaveBeenCalled();
        });

        it("should only call transaction strategy when format is transaction", function () {
            GOVUK.Analytics.Format = 'transaction';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers, 'guide');
            spyOn(GOVUK.Analytics.Trackers, 'transaction');

            GOVUK.Analytics.startAnalytics();

            expect(GOVUK.Analytics.Trackers.transaction).toHaveBeenCalled();
            expect(GOVUK.Analytics.Trackers.guide).not.toHaveBeenCalled();
        });

        it("should not error if format is not supported", function () {
            GOVUK.Analytics.Format = 'blahblah';
            GOVUK.Analytics.NeedID = '99999';

            GOVUK.Analytics.startAnalytics();
        });
    });

    describe("user interactions", function () {
        it("should register success event for guide format when an internal link inside #content receives a 'return' key press", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            var e = jQuery.Event("keydown");
            e.which = 13;
            e.keyCode = 13;
            $("#guide-internal-link").trigger(e);

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(2);
            expect(arguments[1][0]).toBeEqualAsJSON(['_trackEvent', 'MS_guide', '99999', 'Success']);
        });

        it("should register success event for guide format when an internal link inside #content is clicked", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            $('#guide-internal-link').click();

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(2);
            expect(arguments[1][0]).toBeEqualAsJSON(['_trackEvent', 'MS_guide', '99999', 'Success']);
        });

        it("should not register multiple guide success events when navigating to items on the same page", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            $('#guide-internal-link').click();
            $('#guide-internal-link').click();
            $('#guide-internal-link').click();
            $('#guide-internal-link').click();

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(2);
            expect(arguments[1][0]).toBeEqualAsJSON(['_trackEvent', 'MS_guide', '99999', 'Success']);
        });

        it("should not register external click if internal link has been clicked", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            $('#guide-internal-link').click();
            $('#guide-external-link').click();

            var href = $("#guide-external-link").prop("href");
                expect(href).toEqual("http://www.google.com/");
        });

        it("should not register internal click if external link has been clicked", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            $('#guide-external-link').click();
            $('#guide-internal-link').click();

            expect(Alphagov.read_cookie("successEvents")).toBe(null);
        });

        it("should register a smart answer success if the smartanswerOutcome event is fired", function () {
            GOVUK.Analytics.Format = 'smart_answer';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers.smart_answer, 'shouldTrackSuccess').andReturn(true);
            GOVUK.Analytics.startAnalytics();

            $.event.trigger("smartanswerOutcome");

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(1);
            expect(arguments[0][0]).toBeEqualAsJSON(['_trackEvent', 'MS_smart_answer', '99999', 'Success']);
        });

        it("should not register a smart answer success if a smartanswerOutcome event has already been fired", function () {
            GOVUK.Analytics.Format = 'smart_answer';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers.smart_answer, 'shouldTrackSuccess').andReturn(true);
            GOVUK.Analytics.startAnalytics();

            $.event.trigger("smartanswerOutcome");
            $.event.trigger("smartanswerOutcome");

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(1);
            expect(arguments[0][0]).toBeEqualAsJSON(['_trackEvent', 'MS_smart_answer', '99999', 'Success']);
        });

        it("should register custom condition for entry and success tracking for smart answers", function () {
            GOVUK.Analytics.Format = 'smart_answer';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers.smart_answer, 'shouldTrackEntry');
            spyOn(GOVUK.Analytics.Trackers.smart_answer, 'shouldTrackSuccess');

            GOVUK.Analytics.startAnalytics();

            expect(GOVUK.Analytics.Trackers.smart_answer.shouldTrackEntry).toHaveBeenCalled();
            expect(GOVUK.Analytics.Trackers.smart_answer.shouldTrackSuccess).toHaveBeenCalled();
        })
    });
});<commit_msg>Add test for transaction exit link tracking.<commit_after>describe("success event tracking", function () {

    var guideMarkup = $("
" +
        "link" +
        "link" +
        "
" +
        "link" +
        "
" +
        "
");

    var articleContainer = $("
link
");

    beforeEach(function () {
        $('a').unbind();
        articleContainer.clone().appendTo('body');
        guideMarkup.clone().appendTo('body');
        spyOn(GOVUK, 'sendToAnalytics');
    });

    afterEach(function () {
        Alphagov.delete_cookie("successEvents");
        $(".test-stub").remove();
        $.event.trigger("smartanswerOutcome");
    });

    describe("isTheSameArtefact", function () {
        it("should support basic case", function () {
            var result = GOVUK.Analytics.isTheSameArtefact(
                "http://www.gov.uk/claim-tax/first",
                "http://www.gov.uk/claim-tax/second");

            expect(result).toBeTruthy();
        });

        it("should support coming to very same url", function () {
            var result = GOVUK.Analytics.isTheSameArtefact(
                "http://www.gov.uk/claim-tax/first",
                "http://www.gov.uk/claim-tax/first");

            expect(result).toBeTruthy();
        });

        it("should support local anchor on previous url", function () {
            var result = GOVUK.Analytics.isTheSameArtefact(
                "http://www.gov.uk/claim-tax",
                "http://www.gov.uk/claim-tax#foobar");

            expect(result).toBeTruthy();
        });

        it("should support local anchor on current url", function () {
            var result = GOVUK.Analytics.isTheSameArtefact(
                "http://www.gov.uk/claim-tax#foobar",
                "http://www.gov.uk/claim-tax");

            expect(result).toBeTruthy();
        });
    });

    describe("isRootArtefact", function () {
        it("should be true for standard artefact url", function () {
            var result = GOVUK.Analytics.isRootOfArtefact("http://smartanswers.dev.gov.uk/student-finance-calculator");

            expect(result).toBeTruthy();
        });

        it("should be true for standard artefact url ending with a slash", function () {
            var result = GOVUK.Analytics.isRootOfArtefact("http://smartanswers.dev.gov.uk/student-finance-calculator/");

            expect(result).toBeTruthy();
        });

        it("should be false for non-root artefact url", function () {
            var result = GOVUK.Analytics.isRootOfArtefact("http://smartanswers.dev.gov.uk/student-finance-calculator/y");

            expect(result).toBeFalsy();
        });
    });

    describe("analytics integration", function () {
        it("should register entry event", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            var expectedDataToSendToGoogle = ['_trackEvent', 'MS_guide', '99999', 'Entry'];
            expect(arguments.length).toBe(1);
            // using JSONEquals because there is a bug in the .toHaveBeenCalledWith() method
            // see: https://github.com/pivotal/jasmine/issues/45
            expect(arguments[0][0]).toBeEqualAsJSON(expectedDataToSendToGoogle);
        });

        it("should not register an entry event if there is no need id", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = undefined;
            GOVUK.Analytics.startAnalytics();

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(0);
        });

        it("should only call guide strategy when format is guide", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers, 'guide');
            spyOn(GOVUK.Analytics.Trackers, 'transaction');

            GOVUK.Analytics.startAnalytics();

            expect(GOVUK.Analytics.Trackers.transaction).not.toHaveBeenCalled();
            expect(GOVUK.Analytics.Trackers.guide).toHaveBeenCalled();
        });

        it("should only call transaction strategy when format is transaction", function () {
            GOVUK.Analytics.Format = 'transaction';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers, 'guide');
            spyOn(GOVUK.Analytics.Trackers, 'transaction');

            GOVUK.Analytics.startAnalytics();

            expect(GOVUK.Analytics.Trackers.transaction).toHaveBeenCalled();
            expect(GOVUK.Analytics.Trackers.guide).not.toHaveBeenCalled();
        });

        it("should not error if format is not supported", function () {
            GOVUK.Analytics.Format = 'blahblah';
            GOVUK.Analytics.NeedID = '99999';

            GOVUK.Analytics.startAnalytics();
        });
    });

    describe("user interactions", function () {
        it("should register success event for guide format when an internal link inside #content receives a 'return' key press", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            var e = jQuery.Event("keydown");
            e.which = 13;
            e.keyCode = 13;
            $("#guide-internal-link").trigger(e);

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(2);
            expect(arguments[1][0]).toBeEqualAsJSON(['_trackEvent', 'MS_guide', '99999', 'Success']);
        });

        it("should register success event for guide format when an internal link inside #content is clicked", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            $('#guide-internal-link').click();

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(2);
            expect(arguments[1][0]).toBeEqualAsJSON(['_trackEvent', 'MS_guide', '99999', 'Success']);
        });

        it("should not register multiple guide success events when navigating to items on the same page", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            $('#guide-internal-link').click();
            $('#guide-internal-link').click();
            $('#guide-internal-link').click();
            $('#guide-internal-link').click();

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(2);
            expect(arguments[1][0]).toBeEqualAsJSON(['_trackEvent', 'MS_guide', '99999', 'Success']);
        });

        it("should not register external click if internal link has been clicked", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            $('#guide-internal-link').click();
            $('#guide-external-link').click();

            var href = $("#guide-external-link").prop("href");
                expect(href).toEqual("http://www.google.com/");
        });

        it("should not register internal click if external link has been clicked", function () {
            GOVUK.Analytics.Format = 'guide';
            GOVUK.Analytics.NeedID = '99999';
            GOVUK.Analytics.startAnalytics();

            $('#guide-external-link').click();
            $('#guide-internal-link').click();

            expect(Alphagov.read_cookie("successEvents")).toBe(null);
        });

        it("should register a smart answer success if the smartanswerOutcome event is fired", function () {
            GOVUK.Analytics.Format = 'smart_answer';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers.smart_answer, 'shouldTrackSuccess').andReturn(true);
            GOVUK.Analytics.startAnalytics();

            $.event.trigger("smartanswerOutcome");

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(1);
            expect(arguments[0][0]).toBeEqualAsJSON(['_trackEvent', 'MS_smart_answer', '99999', 'Success']);
        });

        it("should not register a smart answer success if a smartanswerOutcome event has already been fired", function () {
            GOVUK.Analytics.Format = 'smart_answer';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers.smart_answer, 'shouldTrackSuccess').andReturn(true);
            GOVUK.Analytics.startAnalytics();

            $.event.trigger("smartanswerOutcome");
            $.event.trigger("smartanswerOutcome");

            var arguments = GOVUK.sendToAnalytics.argsForCall;
            expect(arguments.length).toBe(1);
            expect(arguments[0][0]).toBeEqualAsJSON(['_trackEvent', 'MS_smart_answer', '99999', 'Success']);
        });

        it("should register custom condition for entry and success tracking for smart answers", function () {
            GOVUK.Analytics.Format = 'smart_answer';
            GOVUK.Analytics.NeedID = '99999';
            spyOn(GOVUK.Analytics.Trackers.smart_answer, 'shouldTrackEntry');
            spyOn(GOVUK.Analytics.Trackers.smart_answer, 'shouldTrackSuccess');

            GOVUK.Analytics.startAnalytics();

            expect(GOVUK.Analytics.Trackers.smart_answer.shouldTrackEntry).toHaveBeenCalled();
            expect(GOVUK.Analytics.Trackers.smart_answer.shouldTrackSuccess).toHaveBeenCalled();
        });

        it("should track clicks on the get started link for transactions", function() {
            GOVUK.Analytics.Format = "transaction";
            GOVUK.Analytics.NeedID = "99999";
            GOVUK.Analytics.startAnalytics();

            $('#transaction-external-link').click();

            var href = $("#transaction-external-link").prop("href");
            var parts = href.split("/");
            var expected = "exit?slug=&need_id=99999&format=transaction";
            expect(parts[3]).toEqual(expected)
        });
    });
});<|endoftext|>


<commit_before>define(function( require ){

  var brushDistance = require("paintingUtils/brushDistance");

  describe("BrushDistanceUtils", function() {

    it("Should know when it's not far enough", function() {
      expect(brushDistance.isFarEnough(
        {x: 0,y: 0},
        {x: 1, y: 1},
        10
      )).toBeFalsy();
    });

  });

});<commit_msg>it should know when its far enough<commit_after>define(function( require ){

  var brushDistance = require("paintingUtils/brushDistance");

  describe("BrushDistanceUtils", function() {

    it("Should know when it's not far enough", function() {
      expect(brushDistance.isFarEnough(
        {x: 0,y: 0},
        {x: 1, y: 1},
        10
      )).toBeFalsy();

      expect(brushDistance.isFarEnough(
        {x: 3,y: 3},
        {x: 9, y: 2},
        10
      )).toBeFalsy();
    });

    it("Should know when it's far enought", function() {
      expect(brushDistance.isFarEnough(
        {x: 0,y: 0},
        {x: 11, y: 11},
        10
      )).toBeTruthy();

      expect(brushDistance.isFarEnough(
        {x: 3,y: 3},
        {x: 13, y: 13},
        10
      )).toBeTruthy();
    });

  });

});<|endoftext|>


<commit_before>// nodejs script to start a http server with the feed from this directory
// default is port 4000

var express = require('express')

var app = express()

app.use('/', express.static(__dirname + '/../../build/tmp-angstrom_next-eglibc/deploy/ipk/'))
app.use('/', express.directory(__dirname +'/../../build/tmp-angstrom_next-eglibc/deploy/ipk/'))

console.log("feed server started on port 4000")
app.listen(4000)

<commit_msg>fix up feed server<commit_after>// nodejs script to start a http server with the feed from this directory
// default is port 4000

var express = require('express')

var app = express()

app.use('/', express.static(__dirname + '/../../build/tmp-angstrom-glibc/deploy/ipk/'))
app.use('/', express.directory(__dirname +'/../../build/tmp-angstrom-glibc/deploy/ipk/'))

console.log("feed server started on port 4000")
app.listen(4000)

<|endoftext|>


<commit_before>//= require jquery
//= require jquery.validate
//= require validation
//= require will_it_work_for_me

describe("Will it work for me form", function () {
    //$('html').addClass('js-enabled');

    var formWithNoErrors =
        '<form method="POST" action="" id="validate-will-it-work-for-me" data-msg="Please answer all the questions">' +
        '
' +
        '<fieldset class="inline">' +
        '<legend>Are you 20 or over?</legend>' +
        '' +
        '<input id="will_it_work_for_me_form_above_age_threshold_true" name="will_it_work_for_me_form[above_age_threshold]" type="radio" value="true">' +
        'Yes' +
        '' +
        '' +
        '<input id="will_it_work_for_me_form_above_age_threshold_false" name="will_it_work_for_me_form[above_age_threshold]" type="radio" value="false">' +
        'No' +
        '' +
        '</fieldset>' +
        '
' +
        '
' +
        '<fieldset class="inline"><legend>Have you lived in the UK for the last 12 months?</legend>' +
        '' +
        '<input id="will_it_work_for_me_form_resident_last_12_months_true" name="will_it_work_for_me_form[resident_last_12_months]" type="radio" value="true">' +
        'Yes' +
        '' +
        '' +
        '<input id="will_it_work_for_me_form_resident_last_12_months_false" name="will_it_work_for_me_form[resident_last_12_months]" type="radio" value="false">' +
        'No' +
        '' +
        '</fieldset>' +
        '
' +
        '
' +
        '<fieldset class="inline">' +
        '<legend>Which of these applies to you?</legend>' +
        '' +
        '<input id="will_it_work_for_me_form_not_resident_reason_movedrecently" name="will_it_work_for_me_form[not_resident_reason]" type="radio" value="MovedRecently">' +
        'I moved to the UK in the last 12 months' +
        '' +
        '' +
        '<input id="will_it_work_for_me_form_not_resident_reason_addressbutnotresident" name="will_it_work_for_me_form[not_resident_reason]" type="radio" value="AddressButNotResident">' +
        'I have an address in the UK but I don’t live there' +
        '' +
        '' +
        '<input id="will_it_work_for_me_form_not_resident_reason_noaddress" name="will_it_work_for_me_form[not_resident_reason]" type="radio" value="NoAddress">' +
        'I don’t have a UK address' +
        '' +
        '</fieldset>' +
        '
' +
        '

' +
        '
' +
        '<input class="button" id="next-button" type="submit" value="Continue">' +
        '
' +
        '</form>';

    var willItWorkForMeForm;
    var $dom;
    $('html').addClass('js-enabled');

    beforeEach(function () {
        $dom = $('
' + formWithNoErrors + '
');
        $(document.body).append($dom);
        GOVUK.validation.init();
        GOVUK.willItWorkForMe.init();
        willItWorkForMeForm = GOVUK.willItWorkForMe.$form;
        this.submitForm = function () {
            willItWorkForMeForm.triggerHandler('submit');
        };
        this.checkOverAgeThreshold = function () {
            this.checkRadio(willItWorkForMeForm.find('input[name="will_it_work_for_me_form[above_age_threshold]"][value=true]'));
        };
        this.checkResident12Months = function () {
            this.checkRadio(willItWorkForMeForm.find('input[name="will_it_work_for_me_form[resident_last_12_months]"][value=true]'));
        };
        this.checkNotResident12Months = function () {
            this.checkRadio(willItWorkForMeForm.find('input[name="will_it_work_for_me_form[resident_last_12_months]"][value=false]'));
        };
        this.checkNoUKAddress = function () {
            this.checkRadio(willItWorkForMeForm.find('input[name="will_it_work_for_me_form[not_resident_reason]"][value=NoAddress]'));
        };
        this.checkMovedToUKInLast12Months = function () {
            this.checkRadio(willItWorkForMeForm.find('#will_it_work_for_me_form_not_resident_reason_movedrecently'));
        };
        this.checkRadio = function (el) {
            el.prop('checked', true).trigger('click');
        };
    });

    function answerQuestion(document, answer) {
        wilItWorkForMeForm.find('input[name="will_it_work_for_me_form[' + document + ']"][value=' + answer + ']')
            .prop('checked', true)
            .trigger('click');
    }

    function submitForm() {
        wilItWorkForMeForm.triggerHandler('submit')
    }

    function expectErrorMessage() {
        expect(willItWorkForMeForm.children('.form-group:first').is('.error')).toBe(true);
        expect(willItWorkForMeForm.find('#validation-error-message-js').text()).toBe("Please answer all the questions");
    }

    function expectNoError() {
        expect(willItWorkForMeForm.children('.form-group:first').is('.error')).toBe(false);
        expect(willItWorkForMeForm.find('#validation-error-message-js').text()).toBe('');
    }

    afterEach(function () {
        $dom.remove();
    });

    it("should have no errors on initialising the form.", function () {
        expectNoError();
    });

    it("should not initially show the which of these applies to you section.", function () {
        expect(willItWorkForMeForm.find('#not_resident_reason').attr("class")).toContain("js-hidden");
    });

    it("should show the which of these applies section when user indicates no residency for 12 months", function () {
        this.checkNotResident12Months();

        expect(willItWorkForMeForm.find('#not_resident_reason').attr("class")).not.toContain("js-hidden");
    });

    it("should not show the which of these applies section when user indicates residency for 12 months", function () {
        this.checkResident12Months();

        expect(willItWorkForMeForm.find('#not_resident_reason').attr("class")).toContain("js-hidden");
    });

    it("should have errors on submit if user does not answer over the age threshold", function () {
        this.submitForm();

        expect(willItWorkForMeForm.children('#above-age-threshold').attr("class")).toContain('error');
        expectErrorMessage();
    });

    it("should have errors on submit if the residency question isn't answered", function () {
        this.submitForm();

        expect(willItWorkForMeForm.children('#resident_last_12_months').attr("class")).toContain('error');
        expectErrorMessage();
    });

    it("should have errors on submit if user indicates not resident for 12 months and does not supply reason", function () {
        this.checkNotResident12Months();

        this.submitForm();

        expect(willItWorkForMeForm.children('#not_resident_reason').attr("class")).toContain('error');
        expectErrorMessage();
    });

    it("should have no errors on submit if user has answered over age threshold and lived in UK for 12 months", function () {
        this.checkOverAgeThreshold();
        this.checkResident12Months();

        this.submitForm();

        expectNoError();
    });

    it("should have no errors on submit if user has indicated over age threshold and lived in UK for 12 months and no uk address", function () {
        this.checkOverAgeThreshold();
        this.checkNotResident12Months();
        this.checkNoUKAddress();

        this.submitForm();

        expectNoError();
    });

    it("should have no errors on submit if user has indicated over age threshold and lived in UK for 12 months and uk address", function () {
        this.checkOverAgeThreshold();
        this.checkNotResident12Months();
        this.checkMovedToUKInLast12Months();

        this.submitForm();

        expectNoError();
    });
});<commit_msg>3497 Added missing scenarios to js specs<commit_after>//= require jquery
//= require jquery.validate
//= require validation
//= require will_it_work_for_me

describe("Will it work for me form", function () {
    //$('html').addClass('js-enabled');

    var formWithNoErrors =
        '<form method="POST" action="" id="validate-will-it-work-for-me" data-msg="Please answer all the questions">' +
        '
' +
        '<fieldset class="inline">' +
        '<legend>Are you 20 or over?</legend>' +
        '' +
        '<input id="will_it_work_for_me_form_above_age_threshold_true" name="will_it_work_for_me_form[above_age_threshold]" type="radio" value="true">' +
        'Yes' +
        '' +
        '' +
        '<input id="will_it_work_for_me_form_above_age_threshold_false" name="will_it_work_for_me_form[above_age_threshold]" type="radio" value="false">' +
        'No' +
        '' +
        '</fieldset>' +
        '
' +
        '
' +
        '<fieldset class="inline"><legend>Have you lived in the UK for the last 12 months?</legend>' +
        '' +
        '<input id="will_it_work_for_me_form_resident_last_12_months_true" name="will_it_work_for_me_form[resident_last_12_months]" type="radio" value="true">' +
        'Yes' +
        '' +
        '' +
        '<input id="will_it_work_for_me_form_resident_last_12_months_false" name="will_it_work_for_me_form[resident_last_12_months]" type="radio" value="false">' +
        'No' +
        '' +
        '</fieldset>' +
        '
' +
        '
' +
        '<fieldset class="inline">' +
        '<legend>Which of these applies to you?</legend>' +
        '' +
        '<input id="will_it_work_for_me_form_not_resident_reason_movedrecently" name="will_it_work_for_me_form[not_resident_reason]" type="radio" value="MovedRecently">' +
        'I moved to the UK in the last 12 months' +
        '' +
        '' +
        '<input id="will_it_work_for_me_form_not_resident_reason_addressbutnotresident" name="will_it_work_for_me_form[not_resident_reason]" type="radio" value="AddressButNotResident">' +
        'I have an address in the UK but I don’t live there' +
        '' +
        '' +
        '<input id="will_it_work_for_me_form_not_resident_reason_noaddress" name="will_it_work_for_me_form[not_resident_reason]" type="radio" value="NoAddress">' +
        'I don’t have a UK address' +
        '' +
        '</fieldset>' +
        '
' +
        '

' +
        '
' +
        '<input class="button" id="next-button" type="submit" value="Continue">' +
        '
' +
        '</form>';

    var willItWorkForMeForm;
    var $dom;
    $('html').addClass('js-enabled');

    beforeEach(function () {
        $dom = $('
' + formWithNoErrors + '
');
        $(document.body).append($dom);
        GOVUK.validation.init();
        GOVUK.willItWorkForMe.init();
        willItWorkForMeForm = GOVUK.willItWorkForMe.$form;
        this.submitForm = function () {
            willItWorkForMeForm.triggerHandler('submit');
        };
        this.selectAboveAgeThreshold = function () {
            this.checkRadio(willItWorkForMeForm.find('input[name="will_it_work_for_me_form[above_age_threshold]"][value=true]'));
        };
        this.selectResident12Months = function () {
            this.checkRadio(willItWorkForMeForm.find('input[name="will_it_work_for_me_form[resident_last_12_months]"][value=true]'));
        };
        this.selectNotResident12Months = function () {
            this.checkRadio(willItWorkForMeForm.find('input[name="will_it_work_for_me_form[resident_last_12_months]"][value=false]'));
        };
        this.selectNoUKAddress = function () {
            this.checkRadio(willItWorkForMeForm.find('input[name="will_it_work_for_me_form[not_resident_reason]"][value=NoAddress]'));
        };

        this.checkRadio = function (el) {
            el.prop('checked', true).trigger('click');
        };
    });

    function submitForm() {
        wilItWorkForMeForm.triggerHandler('submit')
    }

    function expectErrorMessage() {
        expect(willItWorkForMeForm.find('#validation-error-message-js').text()).toBe("Please answer all the questions");
    }

    function expectNoError() {
        expect(willItWorkForMeForm.children('.form-group:first').is('.error')).toBe(false);
        expect(willItWorkForMeForm.find('#validation-error-message-js').text()).toBe('');
    }

    afterEach(function () {
        $dom.remove();
    });

    it("should have no errors on initialising the form.", function () {
        expectNoError();
    });

    it("should not initially show 'not-resident-reason' section.", function () {
        expect(willItWorkForMeForm.find('#not_resident_reason').attr("class")).toContain("js-hidden");
    });

    it("should show 'not-resident-reason' section when user indicates no residency for 12 months", function () {
        this.selectNotResident12Months();

        expect(willItWorkForMeForm.find('#not_resident_reason').attr("class")).not.toContain("js-hidden");
    });

    it("should not show 'not-resident-reason' section when user indicates residency for 12 months", function () {
        this.selectResident12Months();

        expect(willItWorkForMeForm.find('#not_resident_reason').attr("class")).toContain("js-hidden");
    });

    it("should have errors on submit if user does not answer any questions", function () {
        this.submitForm();
        expect(willItWorkForMeForm.children('#above-age-threshold').attr("class")).toContain('error');
        expect(willItWorkForMeForm.children('#resident_last_12_months').attr("class")).toContain('error');
        expectErrorMessage();
    });

    it("should have errors on submit if user does not answer over the age threshold", function () {
        this.selectNotResident12Months();
        this.submitForm();
        expect(willItWorkForMeForm.children('#above-age-threshold').attr("class")).toContain('error');
        expectErrorMessage();
    });

    it("should have errors on submit if the residency question isn't answered", function () {
        this.selectAboveAgeThreshold();
        this.submitForm();
        expect(willItWorkForMeForm.children('#resident_last_12_months').attr("class")).toContain('error');
        expectErrorMessage();
    });

    it("should have errors on submit if user indicates not resident for 12 months and does not supply reason", function () {
        this.selectNotResident12Months();
        this.submitForm();
        expect(willItWorkForMeForm.children('#not_resident_reason').attr("class")).toContain('error');
        expectErrorMessage();
    });

    it("should have no errors on submit if user has answered over age threshold and lived in UK for 12 months", function () {
        this.selectAboveAgeThreshold();
        this.selectResident12Months();

        this.submitForm();

        expectNoError();
    });

    it("should have no errors on submit if user has answered above age threshold and lived in UK for 12 months and has chosen the reason", function () {
        this.selectAboveAgeThreshold();
        this.selectNotResident12Months();
        this.selectNoUKAddress();

        this.submitForm();

        expectNoError();
    });
});<|endoftext|>


<commit_before>import { EJSON } from 'meteor/ejson';

import { webAppConnectHandlersUse } from './meteor_patch.js';

// InjectData object
export const InjectData = {
  // encode object to string
  _encode(ejson) {
    const ejsonString = EJSON.stringify(ejson);
    return encodeURIComponent(ejsonString);
  },

  // decode string to object
  _decode(encodedEjson) {
    const decodedEjsonString = decodeURIComponent(encodedEjson);
    if (!decodedEjsonString) return null;
    return EJSON.parse(decodedEjsonString);
  },

  // push data to res._injectPayload and generate res._injectHtml
  pushData(res, key, value) {
    if (!res._injectPayload) {
      res._injectPayload = {};
    }

    res._injectPayload[key] = value;

    // if cors headers included if may cause some security holes
    // so we simply turn off injecting if we detect an cors header
    // read more: http://goo.gl/eGwb4e
    // if (res._headers && res._headers['access-control-allow-origin']) {
    //   const warnMessage =
    //     'warn: injecting data turned off due to CORS headers. ' +
    //     'read more: http://goo.gl/eGwb4e';
    //   console.warn(warnMessage); // eslint-disable-line no-console
    //   return;
    // }

    // inject data
    const data = this._encode(res._injectPayload);
    res._injectHtml = `<script type="text/inject-data">${data}</script>`;
  },

  // get data from res._injectPayload
  getData(res, key) {
    if (res._injectPayload) {
      // same as _.clone(res._injectPayload[key]);
      const data = res._injectPayload[key];
      const clonedData = EJSON.parse(EJSON.stringify(data));
      return clonedData;
    }
    return null;
  },
};

// **injectDataMiddleware, Notes that it must after router connect handler**
webAppConnectHandlersUse(function injectDataMiddleware(req, res, next) {
  if (res._injectHtml) {
    req.dynamicHead = req.dynamicHead || '';
    req.dynamicHead += res._injectHtml;
  }
  next();
}, { order: 900 });
<commit_msg>enable CORS warning in inject-data again<commit_after>import { EJSON } from 'meteor/ejson';

import { webAppConnectHandlersUse } from './meteor_patch.js';

// InjectData object
export const InjectData = {
  // encode object to string
  _encode(ejson) {
    const ejsonString = EJSON.stringify(ejson);
    return encodeURIComponent(ejsonString);
  },

  // decode string to object
  _decode(encodedEjson) {
    const decodedEjsonString = decodeURIComponent(encodedEjson);
    if (!decodedEjsonString) return null;
    return EJSON.parse(decodedEjsonString);
  },

  // push data to res._injectPayload and generate res._injectHtml
  pushData(res, key, value) {
    if (!res._injectPayload) {
      res._injectPayload = {};
    }

    res._injectPayload[key] = value;

    // if cors headers included if may cause some security holes
    // so we simply turn off injecting if we detect an cors header
    // read more: http://goo.gl/eGwb4e
    if (res._headers && res._headers['access-control-allow-origin']) {
      const warnMessage =
        'warn: injecting data turned off due to CORS headers. ' +
        'read more: http://goo.gl/eGwb4e';
      console.warn(warnMessage); // eslint-disable-line no-console
      return;
    }

    // inject data
    const data = this._encode(res._injectPayload);
    res._injectHtml = `<script type="text/inject-data">${data}</script>`;
  },

  // get data from res._injectPayload
  getData(res, key) {
    if (res._injectPayload) {
      // same as _.clone(res._injectPayload[key]);
      const data = res._injectPayload[key];
      const clonedData = EJSON.parse(EJSON.stringify(data));
      return clonedData;
    }
    return null;
  },
};

// **injectDataMiddleware, Notes that it must after router connect handler**
webAppConnectHandlersUse(function injectDataMiddleware(req, res, next) {
  if (res._injectHtml) {
    req.dynamicHead = req.dynamicHead || '';
    req.dynamicHead += res._injectHtml;
  }
  next();
}, { order: 900 });
<|endoftext|>


<commit_before>(function (Filter) {
    'use strict';

    var async      = require('async'),
        database   = require('./database'),
        controller = require('./controller');

    /**
     * Hook to render user profile.
     * 'userData' will be used as payload in hook handler.
     * @param params {object} Payload :{userData: userData, uid: callerUID}
     * @param callback {function}
     */
    Filter.account = function (params, callback) {
        database.getPoints(params.userData.uid, function (error, points) {
            if (error) {
                return callback(error);
            }
            params.userData.points = points || 0;
            callback(null, params);
        });
    };

    Filter.menuAdmin = function (header, callback) {
        header.plugins.push({
            route: '/plugins/points',
            icon : 'fa-gamepad',
            name : 'Points'
        });
        callback(null, header);
    };

    Filter.navigation = function (items, callback) {
        items.push({
            route    : "/points",
            title    : "Points",
            enabled  : true,
            iconClass: "fa-gamepad",
            textClass: "visible-xs-inline",
            text     : "Points"
        });
        callback(null, items);
    };

    /**
     * Hook to render single posted post
     * @param postData {object} Fields: {pid, uid, tid, content, timestamp, reputation, votes, editor, edited, deleted, cid}
     * @param callback {function}
     */
    Filter.postGet = function (postData, callback) {
        database.getPoints(postData.uid, function (error, points) {
            if (error) {
                return callback(error);
            }
            postData.points = points || 0;
            callback(null, postData);
        });
    };

    /**
     * Hook to render topic thread
     * @param payload {object} Fields: {posts: posts, uid: uid}
     * @param callback {function}
     */
    Filter.postGetPosts = function (payload, callback) {
        async.map(payload.posts, function (post, next) {
            database.getPoints(post.uid, function (error, points) {
                if (error) {
                    return next(error);
                }
                post.points = points || 0;
                next(null, post);
            });
        }, function (error, results) {
            if (error) {
                return callback(error);
            }
            payload.posts = results;
            callback(null, payload);
        });
    };

    /**
     * Hook to inject points settings and values
     * @param topicData {object} Fields: {topic: topicData, uid: uid}
     * @param callback {function}
     */
    Filter.topicGet = function (topicData, callback) {
        controller.injectSettings(topicData.topic, function (error, topicWithSettings) {
            if (error) {
                return callback(error);
            }
            topicData.topic = topicWithSettings;
            callback(null, topicData);
        });
    };

})(module.exports);<commit_msg>add extra line for jsdoc<commit_after>(function (Filter) {
    'use strict';

    var async      = require('async'),
        database   = require('./database'),
        controller = require('./controller');

    /**
     * Hook to render user profile.
     * 'userData' will be used as payload in hook handler.
     *
     * @param params {object} Payload :{userData: userData, uid: callerUID}
     * @param callback {function}
     */
    Filter.account = function (params, callback) {
        database.getPoints(params.userData.uid, function (error, points) {
            if (error) {
                return callback(error);
            }
            params.userData.points = points || 0;
            callback(null, params);
        });
    };

    Filter.menuAdmin = function (header, callback) {
        header.plugins.push({
            route: '/plugins/points',
            icon : 'fa-gamepad',
            name : 'Points'
        });
        callback(null, header);
    };

    Filter.navigation = function (items, callback) {
        items.push({
            route    : "/points",
            title    : "Points",
            enabled  : true,
            iconClass: "fa-gamepad",
            textClass: "visible-xs-inline",
            text     : "Points"
        });
        callback(null, items);
    };

    /**
     * Hook to render single posted post
     *
     * @param postData {object} Fields: {pid, uid, tid, content, timestamp, reputation, votes, editor, edited, deleted, cid}
     * @param callback {function}
     */
    Filter.postGet = function (postData, callback) {
        database.getPoints(postData.uid, function (error, points) {
            if (error) {
                return callback(error);
            }
            postData.points = points || 0;
            callback(null, postData);
        });
    };

    /**
     * Hook to render topic thread
     *
     * @param payload {object} Fields: {posts: posts, uid: uid}
     * @param callback {function}
     */
    Filter.postGetPosts = function (payload, callback) {
        async.map(payload.posts, function (post, next) {
            database.getPoints(post.uid, function (error, points) {
                if (error) {
                    return next(error);
                }
                post.points = points || 0;
                next(null, post);
            });
        }, function (error, results) {
            if (error) {
                return callback(error);
            }
            payload.posts = results;
            callback(null, payload);
        });
    };

    /**
     * Hook to inject points settings and values
     * @param topicData {object} Fields: {topic: topicData, uid: uid}
     * @param callback {function}
     */
    Filter.topicGet = function (topicData, callback) {
        controller.injectSettings(topicData.topic, function (error, topicWithSettings) {
            if (error) {
                return callback(error);
            }
            topicData.topic = topicWithSettings;
            callback(null, topicData);
        });
    };

})(module.exports);<|endoftext|>