<commit_before>const moment               = require('moment');
const SetCurrency          = require('./set_currency');
const BinaryPjax           = require('../../base/binary_pjax');
const Client               = require('../../base/client');
const BinarySocket         = require('../../base/socket');
const showPopup            = require('../../common/attach_dom/popup');
const Currency             = require('../../common/currency');
const localize             = require('../../../_common/localize').localize;
const State                = require('../../../_common/storage').State;
const urlFor               = require('../../../_common/url').urlFor;

const Accounts = (() => {
    let landing_company;
    const form_id = '#new_accounts';

    const TableHeaders = (() => {
        let table_headers;

        const initTableHeaders = () => ({
            account          : localize('Account'),
            available_markets: localize('Available Markets'),
            type             : localize('Type'),
            currency         : localize('Currency'),
        });

        return {
            get: () => {
                if (!table_headers) {
                    table_headers = initTableHeaders();
                }
                return table_headers;
            },
        };
    })();

    const onLoad = () => {
        if (!Client.get('residence')) {
            // ask client to set residence first since cannot wait landing_company otherwise
            BinaryPjax.load(urlFor('user/settings/detailsws'));
        }
        SetCurrency.cleanupPopup();
        BinarySocket.send({ statement: 1, limit: 1 });
        BinarySocket.wait('landing_company', 'get_settings', 'statement', 'mt5_login_list').then(() => {
            landing_company           = State.getResponse('landing_company');
            const can_change_currency = Client.canChangeCurrency(State.getResponse('statement'), State.getResponse('mt5_login_list'));

            populateExistingAccounts();

            let element_to_show = '#no_new_accounts_wrapper';
            const upgrade_info  = Client.getUpgradeInfo();
            if (upgrade_info.can_upgrade) {
                populateNewAccounts(upgrade_info);
                element_to_show = '#new_accounts_wrapper';
            }

            if (upgrade_info.can_open_multi) {
                populateMultiAccount();
            } else if (!can_change_currency) {
                doneLoading(element_to_show);
            }

            if (can_change_currency) {
                addChangeCurrencyOption();
                element_to_show = '#new_accounts_wrapper';
                if (!upgrade_info.can_open_multi) {
                    doneLoading(element_to_show);
                }
            }
        });
    };

    const doneLoading = (element_to_show) => {
        $(element_to_show).setVisibility(1);
        $('#accounts_loading').remove();
        $('#accounts_wrapper').setVisibility(1);
    };

    const getCompanyName = account => Client.getLandingCompanyValue(account, landing_company, 'name');

    const getCompanyCountry = account => Client.getLandingCompanyValue(account, landing_company, 'country');

    const populateNewAccounts = (upgrade_info) => {
        const table_headers = TableHeaders.get();
        const new_account   = upgrade_info;
        const account       = {
            real     : new_account.type === 'real',
            financial: new_account.type === 'financial',
        };
        const new_account_title    = new_account.type === 'financial' ? localize('Financial Account') : localize('Real Account');
        $(form_id).find('tbody')
            .append($('<tr/>')
                .append($('<td/>', { datath: table_headers.account }).html($('<span/>', {
                    text                 : new_account_title,
                    'data-balloon'       : `${localize('Counterparty')}: ${getCompanyName(account)}, ${localize('Jurisdiction')}: ${getCompanyCountry(account)}`,
                    'data-balloon-length': 'large',
                })))
                .append($('<td/>', { text: getAvailableMarkets(account), datath: table_headers.available_markets }))
                .append($('<td/>')
                    .html($('<a/>', { class: 'button', href: urlFor(new_account.upgrade_link) })
                        .html($('<span/>', { text: localize('Create account') })))));
    };

    const addChangeCurrencyOption = () => {
        const table_headers = TableHeaders.get();
        const loginid       = Client.get('loginid');

        // Set the table row
        $(form_id).find('tbody')
            .append($('<tr/>', { id: 'change_account_currency' })
                .append($('<td/>', { datath: table_headers.account }).html($('<span/>', {
                    text: loginid,
                })))
                .append($('<td/>', { text: getAvailableMarkets(loginid), datath: table_headers.available_markets }))
                .append($('<td/>', { id: 'change_currency_action' })
                    .html($('<button/>', { id: 'change_currency_btn', class: 'button no-margin', type: 'button', text: localize('Change currency') }).click(() => showCurrencyPopUp('change')))));

        // Replace note to reflect ability to change currency
        $('#note > .hint').text(`${localize('Note: You are limited to one fiat currency account. The currency of your fiat account can be changed before you deposit into your fiat account for the first time or create an MT5 account. You may also open one account for each supported cryptocurrency.')}`);
    };

    const onConfirmSetCurrency = () => {
        const can_change_currency = Client.canChangeCurrency(State.getResponse('statement'), State.getResponse('mt5_login_list'));
        if (can_change_currency) {
            addChangeCurrencyOption();
        }
    };

    const action_map = {
        create: 'multi_account',
        set   : 'set_currency',
        change: 'change_currency',
    };

    const showCurrencyPopUp = (action) => {
        showPopup({
            url               : urlFor('user/set-currency'),
            content_id        : '#set_currency',
            form_id           : 'frm_set_currency',
            additionalFunction: () => {
                localStorage.setItem('popup_action', action_map[action]);
                SetCurrency.onLoad(onConfirmSetCurrency);
            },
        });
    };

    const populateExistingAccounts = () => {
        const all_login_ids = Client.getAllLoginids();
        // Populate active loginids first.
        all_login_ids
            .filter(loginid => !Client.get('is_disabled', loginid) && !Client.get('excluded_until', loginid))
            .sort((a, b) => a > b)
            .forEach((loginid) => {
                appendExistingAccounts(loginid);
            });

        // Populate disabled or self excluded loginids.
        all_login_ids
            .filter(loginid => Client.get('is_disabled', loginid) || Client.get('excluded_until', loginid))
            .sort((a, b) => a > b)
            .forEach((loginid) => {
                appendExistingAccounts(loginid);
            });
    };

    const appendExistingAccounts = (loginid) => {
        const table_headers     = TableHeaders.get();
        const account_currency  = Client.get('currency', loginid);
        const account_type_prop = { text: Client.getAccountTitle(loginid) };

        if (!Client.isAccountOfType('virtual', loginid)) {
            const company_name    = getCompanyName(loginid);
            const company_country = getCompanyCountry(loginid);
            account_type_prop['data-balloon'] = `${localize('Counterparty')}: ${company_name}, ${localize('Jurisdiction')}: ${company_country}`;
            account_type_prop['data-balloon-length'] = 'large';
        }

        const is_disabled    = Client.get('is_disabled', loginid);
        const excluded_until = Client.get('excluded_until', loginid);
        let txt_markets = '';
        if (is_disabled) {
            txt_markets = localize('This account is disabled');
        } else if (excluded_until) {
            txt_markets = localize('This account is excluded until [_1]', moment(+excluded_until * 1000).format('YYYY-MM-DD HH:mm:ss Z'));
        } else {
            txt_markets = getAvailableMarkets(loginid);
        }

        $('#existing_accounts').find('tbody')
            .append($('<tr/>', { id: loginid, class: ((is_disabled || excluded_until) ? 'color-dark-white' : '') })
                .append($('<td/>', { text: loginid, datath: table_headers.account }))
                .append($('<td/>', { datath: table_headers.type }).html($('<span/>', account_type_prop)))
                .append($('<td/>', { text: txt_markets, datath: table_headers.available_markets }))
                .append($('<td/>', { datath: table_headers.currency })
                    .html(!account_currency && loginid === Client.get('loginid') ? $('<button/>', { text: localize('Set currency'), type: 'button' }).click(() => showCurrencyPopUp('set')) : (Currency.getCurrencyFullName(account_currency) || '-'))));

        if (is_disabled || excluded_until) {
            $('#note_support').setVisibility(1);
        }
    };

    const getAvailableMarkets = (loginid) => {
        let legal_allowed_markets = Client.getLandingCompanyValue(loginid, landing_company, 'legal_allowed_markets') || '';
        if (Array.isArray(legal_allowed_markets) && legal_allowed_markets.length) {
            legal_allowed_markets =
                legal_allowed_markets
                    .map(market => getMarketName(market))
                    .filter((value, index, self) => value && self.indexOf(value) === index)
                    .join(', ');
        }
        return legal_allowed_markets;
    };

    const MarketsConfig = (() => {
        let markets_config;

        const initMarketsConfig = () => ({
            commodities    : localize('Commodities'),
            forex          : localize('Forex'),
            indices        : localize('Stock Indices'),
            stocks         : localize('Stocks'),
            synthetic_index: localize('Synthetic Indices'),
        });

        return {
            get: () => {
                if (!markets_config) {
                    markets_config = initMarketsConfig();
                }
                return markets_config;
            },
        };
    })();

    const getMarketName = market => MarketsConfig.get()[market] || '';

    const populateMultiAccount = () => {
        const table_headers = TableHeaders.get();
        const account       = { real: 1 };
        $(form_id).find('tbody')
            .append($('<tr/>', { id: 'new_account_opening' })
                .append($('<td/>', { datath: table_headers.account }).html($('<span/>', {
                    text                 : localize('Real Account'),
                    'data-balloon'       : `${localize('Counterparty')}: ${getCompanyName(account)}, ${localize('Jurisdiction')}: ${getCompanyCountry(account)}`,
                    'data-balloon-length': 'large',
                })))
                .append($('<td/>', { text: getAvailableMarkets({ real: 1 }), datath: table_headers.available_markets }))
                .append($('<td/>').html($('<button/>', { text: localize('Create account'), type: 'button' }).click(() => showCurrencyPopUp('create')))));

        $('#note').setVisibility(1);

        doneLoading('#new_accounts_wrapper');
    };

    return {
        onLoad,
    };
})();

module.exports = Accounts;
<commit_msg>fix: avoid adding duplicates<commit_after>const moment               = require('moment');
const SetCurrency          = require('./set_currency');
const BinaryPjax           = require('../../base/binary_pjax');
const Client               = require('../../base/client');
const BinarySocket         = require('../../base/socket');
const showPopup            = require('../../common/attach_dom/popup');
const Currency             = require('../../common/currency');
const localize             = require('../../../_common/localize').localize;
const State                = require('../../../_common/storage').State;
const urlFor               = require('../../../_common/url').urlFor;

const Accounts = (() => {
    let landing_company;
    const form_id = '#new_accounts';

    const TableHeaders = (() => {
        let table_headers;

        const initTableHeaders = () => ({
            account          : localize('Account'),
            available_markets: localize('Available Markets'),
            type             : localize('Type'),
            currency         : localize('Currency'),
        });

        return {
            get: () => {
                if (!table_headers) {
                    table_headers = initTableHeaders();
                }
                return table_headers;
            },
        };
    })();

    const onLoad = () => {
        if (!Client.get('residence')) {
            // ask client to set residence first since cannot wait landing_company otherwise
            BinaryPjax.load(urlFor('user/settings/detailsws'));
        }
        SetCurrency.cleanupPopup();
        BinarySocket.send({ statement: 1, limit: 1 });
        BinarySocket.wait('landing_company', 'get_settings', 'statement', 'mt5_login_list').then(() => {
            landing_company           = State.getResponse('landing_company');
            const can_change_currency = Client.canChangeCurrency(State.getResponse('statement'), State.getResponse('mt5_login_list'));

            populateExistingAccounts();

            let element_to_show = '#no_new_accounts_wrapper';
            const upgrade_info  = Client.getUpgradeInfo();
            if (upgrade_info.can_upgrade) {
                populateNewAccounts(upgrade_info);
                element_to_show = '#new_accounts_wrapper';
            }

            if (upgrade_info.can_open_multi) {
                populateMultiAccount();
            } else if (!can_change_currency) {
                doneLoading(element_to_show);
            }

            if (can_change_currency) {
                addChangeCurrencyOption();
                element_to_show = '#new_accounts_wrapper';
                if (!upgrade_info.can_open_multi) {
                    doneLoading(element_to_show);
                }
            }
        });
    };

    const doneLoading = (element_to_show) => {
        $(element_to_show).setVisibility(1);
        $('#accounts_loading').remove();
        $('#accounts_wrapper').setVisibility(1);
    };

    const getCompanyName = account => Client.getLandingCompanyValue(account, landing_company, 'name');

    const getCompanyCountry = account => Client.getLandingCompanyValue(account, landing_company, 'country');

    const populateNewAccounts = (upgrade_info) => {
        const table_headers = TableHeaders.get();
        const new_account   = upgrade_info;
        const account       = {
            real     : new_account.type === 'real',
            financial: new_account.type === 'financial',
        };
        const new_account_title    = new_account.type === 'financial' ? localize('Financial Account') : localize('Real Account');
        $(form_id).find('tbody')
            .append($('<tr/>')
                .append($('<td/>', { datath: table_headers.account }).html($('<span/>', {
                    text                 : new_account_title,
                    'data-balloon'       : `${localize('Counterparty')}: ${getCompanyName(account)}, ${localize('Jurisdiction')}: ${getCompanyCountry(account)}`,
                    'data-balloon-length': 'large',
                })))
                .append($('<td/>', { text: getAvailableMarkets(account), datath: table_headers.available_markets }))
                .append($('<td/>')
                    .html($('<a/>', { class: 'button', href: urlFor(new_account.upgrade_link) })
                        .html($('<span/>', { text: localize('Create account') })))));
    };

    const addChangeCurrencyOption = () => {
        if ($(form_id).find('#change_account_currency').length) {
            return;
        }
        const table_headers = TableHeaders.get();
        const loginid       = Client.get('loginid');

        // Set the table row
        $(form_id).find('tbody')
            .append($('<tr/>', { id: 'change_account_currency' })
                .append($('<td/>', { datath: table_headers.account }).html($('<span/>', {
                    text: loginid,
                })))
                .append($('<td/>', { text: getAvailableMarkets(loginid), datath: table_headers.available_markets }))
                .append($('<td/>', { id: 'change_currency_action' })
                    .html($('<button/>', { id: 'change_currency_btn', class: 'button no-margin', type: 'button', text: localize('Change currency') }).click(() => showCurrencyPopUp('change')))));

        // Replace note to reflect ability to change currency
        $('#note > .hint').text(`${localize('Note: You are limited to one fiat currency account. The currency of your fiat account can be changed before you deposit into your fiat account for the first time or create an MT5 account. You may also open one account for each supported cryptocurrency.')}`);
    };

    const onConfirmSetCurrency = () => {
        const can_change_currency = Client.canChangeCurrency(State.getResponse('statement'), State.getResponse('mt5_login_list'));
        if (can_change_currency) {
            addChangeCurrencyOption();
        }
    };

    const action_map = {
        create: 'multi_account',
        set   : 'set_currency',
        change: 'change_currency',
    };

    const showCurrencyPopUp = (action) => {
        showPopup({
            url               : urlFor('user/set-currency'),
            content_id        : '#set_currency',
            form_id           : 'frm_set_currency',
            additionalFunction: () => {
                localStorage.setItem('popup_action', action_map[action]);
                SetCurrency.onLoad(onConfirmSetCurrency);
            },
        });
    };

    const populateExistingAccounts = () => {
        const all_login_ids = Client.getAllLoginids();
        // Populate active loginids first.
        all_login_ids
            .filter(loginid => !Client.get('is_disabled', loginid) && !Client.get('excluded_until', loginid))
            .sort((a, b) => a > b)
            .forEach((loginid) => {
                appendExistingAccounts(loginid);
            });

        // Populate disabled or self excluded loginids.
        all_login_ids
            .filter(loginid => Client.get('is_disabled', loginid) || Client.get('excluded_until', loginid))
            .sort((a, b) => a > b)
            .forEach((loginid) => {
                appendExistingAccounts(loginid);
            });
    };

    const appendExistingAccounts = (loginid) => {
        const table_headers     = TableHeaders.get();
        const account_currency  = Client.get('currency', loginid);
        const account_type_prop = { text: Client.getAccountTitle(loginid) };

        if (!Client.isAccountOfType('virtual', loginid)) {
            const company_name    = getCompanyName(loginid);
            const company_country = getCompanyCountry(loginid);
            account_type_prop['data-balloon'] = `${localize('Counterparty')}: ${company_name}, ${localize('Jurisdiction')}: ${company_country}`;
            account_type_prop['data-balloon-length'] = 'large';
        }

        const is_disabled    = Client.get('is_disabled', loginid);
        const excluded_until = Client.get('excluded_until', loginid);
        let txt_markets = '';
        if (is_disabled) {
            txt_markets = localize('This account is disabled');
        } else if (excluded_until) {
            txt_markets = localize('This account is excluded until [_1]', moment(+excluded_until * 1000).format('YYYY-MM-DD HH:mm:ss Z'));
        } else {
            txt_markets = getAvailableMarkets(loginid);
        }

        $('#existing_accounts').find('tbody')
            .append($('<tr/>', { id: loginid, class: ((is_disabled || excluded_until) ? 'color-dark-white' : '') })
                .append($('<td/>', { text: loginid, datath: table_headers.account }))
                .append($('<td/>', { datath: table_headers.type }).html($('<span/>', account_type_prop)))
                .append($('<td/>', { text: txt_markets, datath: table_headers.available_markets }))
                .append($('<td/>', { datath: table_headers.currency })
                    .html(!account_currency && loginid === Client.get('loginid') ? $('<button/>', { text: localize('Set currency'), type: 'button' }).click(() => showCurrencyPopUp('set')) : (Currency.getCurrencyFullName(account_currency) || '-'))));

        if (is_disabled || excluded_until) {
            $('#note_support').setVisibility(1);
        }
    };

    const getAvailableMarkets = (loginid) => {
        let legal_allowed_markets = Client.getLandingCompanyValue(loginid, landing_company, 'legal_allowed_markets') || '';
        if (Array.isArray(legal_allowed_markets) && legal_allowed_markets.length) {
            legal_allowed_markets =
                legal_allowed_markets
                    .map(market => getMarketName(market))
                    .filter((value, index, self) => value && self.indexOf(value) === index)
                    .join(', ');
        }
        return legal_allowed_markets;
    };

    const MarketsConfig = (() => {
        let markets_config;

        const initMarketsConfig = () => ({
            commodities    : localize('Commodities'),
            forex          : localize('Forex'),
            indices        : localize('Stock Indices'),
            stocks         : localize('Stocks'),
            synthetic_index: localize('Synthetic Indices'),
        });

        return {
            get: () => {
                if (!markets_config) {
                    markets_config = initMarketsConfig();
                }
                return markets_config;
            },
        };
    })();

    const getMarketName = market => MarketsConfig.get()[market] || '';

    const populateMultiAccount = () => {
        const table_headers = TableHeaders.get();
        const account       = { real: 1 };
        $(form_id).find('tbody')
            .append($('<tr/>', { id: 'new_account_opening' })
                .append($('<td/>', { datath: table_headers.account }).html($('<span/>', {
                    text                 : localize('Real Account'),
                    'data-balloon'       : `${localize('Counterparty')}: ${getCompanyName(account)}, ${localize('Jurisdiction')}: ${getCompanyCountry(account)}`,
                    'data-balloon-length': 'large',
                })))
                .append($('<td/>', { text: getAvailableMarkets({ real: 1 }), datath: table_headers.available_markets }))
                .append($('<td/>').html($('<button/>', { text: localize('Create account'), type: 'button' }).click(() => showCurrencyPopUp('create')))));

        $('#note').setVisibility(1);

        doneLoading('#new_accounts_wrapper');
    };

    return {
        onLoad,
    };
})();

module.exports = Accounts;
<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';

import config from '../config'
import actions from '../actions';

class Messenger extends React.Component {

  sendMessage() {
    const message = this.messageInput.value;
    this.props.sendMessage(this.props.chatId, message);
    this.messageInput.value = '';
    this.props.onSizeChanged(50);
  }

  onKeyUp(event) {
    event.persist();

    // Send message on 'return' key press
    if ( event.keyCode === 13 && !event.shiftKey ) {
      this.sendMessage();
    }

    // Update height of input element
    setTimeout(() => {
      this.props.onSizeChanged(50);
      let height = event.target.scrollHeight;
      this.props.onSizeChanged(height);
    }, 0);
  }

  render() {
    let messengerAttachmentClass = `c-messenger__attachment ${ this.props.showAttachment ? 'state-active' : '' }`;

    let inputHeight = { height: `${ this.props.messengerHeight }px` };

    return (

        <button className={ messengerAttachmentClass } onClick={ this.props.toggleAttachment }>

        </button>

        <textarea ref={ input => this.messageInput = input }
          style={ inputHeight }
          placeholder="Share knowledge"
          onKeyUp={ this.onKeyUp.bind(this) }
        ></textarea>

        <button className="c-messenger__submit" onClick={ () => this.sendMessage() }>

        </button>

    );
  }
}

const mapStateToProps = (state, ownProps) => state[config.stateName];

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    sendMessage: (chatId, message) => dispatch(actions.chats.sendMessage(chatId, message)),
  };
};

const MessengerConnect = connect(mapStateToProps, mapDispatchToProps)(Messenger);

export default MessengerConnect;
<commit_msg>Bind listener on key down to prevent new lines in text area when sending a message.<commit_after>import React from 'react';
import { connect } from 'react-redux';

import config from '../config'
import actions from '../actions';

class Messenger extends React.Component {

  sendMessage() {
    const message = this.messageInput.value;
    this.props.sendMessage(this.props.chatId, message);
    this.messageInput.value = '';
    this.props.onSizeChanged(50);
  }

  onKeyDown(event) {
    event.persist();

    // Send message on 'return' key press
    if ( event.keyCode === 13 && !event.shiftKey ) {
      event.preventDefault();
      this.sendMessage();
    } else {
      setTimeout(() => {
        this.props.onSizeChanged(50);
        let height = event.target.scrollHeight;
        this.props.onSizeChanged(height);
      }, 0);
    }
  }

  render() {
    let messengerAttachmentClass = `c-messenger__attachment ${ this.props.showAttachment ? 'state-active' : '' }`;

    let inputHeight = { height: `${ this.props.messengerHeight }px` };

    return (

        <button className={ messengerAttachmentClass } onClick={ this.props.toggleAttachment }>

        </button>

        <textarea ref={ input => this.messageInput = input }
          style={ inputHeight }
          placeholder="Share knowledge"
          onKeyDown={ this.onKeyDown.bind(this) }
        ></textarea>

        <button className="c-messenger__submit" onClick={ () => this.sendMessage() }>

        </button>

    );
  }
}

const mapStateToProps = (state, ownProps) => state[config.stateName];

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    sendMessage: (chatId, message) => dispatch(actions.chats.sendMessage(chatId, message)),
  };
};

const MessengerConnect = connect(mapStateToProps, mapDispatchToProps)(Messenger);

export default MessengerConnect;
<|endoftext|>


<commit_before>define(['backbone', 'zeroclipboard'], function(Backbone, ZeroClipboard) {
  'use strict';

  return Backbone.View.extend({
    el: '#share-container',

    initialize: function() {
      ZeroClipboard.config({
        swfPath: 'bower_components/ZeroClipboard/dist/ZeroClipboard.swf'
      });

      var copyToClipboard = $('#copy-to-clipboard'),
          clip = new ZeroClipboard(copyToClipboard),
          shortURLInput = $('#short-url');

      function getShortURL(callback) {
        var shortURL = shortURLInput.val();
        if (shortURL) {
          callback(shortURL);
        } else {
          $.getJSON('short_url.php', {
            url: location.href
          }, function(data) {
            shortURL = data.shorturl;
            if (shortURL) {
              shortURLInput.val(shortURL);
              callback(shortURL);
            }
          });
        }
      }

      shortURLInput.on('cut keydown', function (event) {
        // Prevent default actions on cut and keydown to simulate readOnly
        // behavior on input, as the readOnly attribute does not allow selection
        // on some mobile platforms.
        event.preventDefault();
      }).focus(function() {
        getShortURL(function() {
          // shortURLInput.select() does not work on iOS
          shortURLInput[0].setSelectionRange(0, 99);
        });
      }).mouseup(function (event) {
        // Prevent the mouseup event from unselecting the selection
        event.preventDefault();
      });

      var CLIPBOARD_TOOLTIP = 'Copy to Clipboard';
      copyToClipboard.qtip({
        content: CLIPBOARD_TOOLTIP,
        events: {
          hidden: function() {
            // Set to original text when hidden as text may have been changed.
            copyToClipboard.qtip('option', 'content.text', CLIPBOARD_TOOLTIP);
          }
        }
      });

      clip.on('mouseover', function() {
        getShortURL(function(shortURL) {
          clip.setText(shortURL);
        });
        copyToClipboard.qtip('show');
      });
      clip.on('mouseout', function() {
        copyToClipboard.qtip('hide');
      });
      clip.on('complete', function() {
        copyToClipboard.qtip('option', 'content.text', 'Copied!');
      });

      $('#share-email').click(function() {
        getShortURL(function(shortURL) {
          window.location.href = 'mailto:?subject=My%20NUSMods.com%20Timetable&' +
              'body=' + encodeURIComponent(shortURL);
        });
      }).qtip({
            content: 'Share via Email'
          });

      $('#share-facebook').click(function() {
        getShortURL(function(shortURL) {
          window.open('http://www.facebook.com/sharer.php?u=' +
              encodeURIComponent(shortURL), '', 'width=660,height=350');
        });
      }).qtip({
            content: 'Share via Facebook'
          });

      $('#share-twitter').click(function() {
        getShortURL(function(shortURL) {
          window.open('http://twitter.com/intent/tweet?url=' +
              encodeURIComponent(shortURL), '', 'width=660,height=350');
        });
      }).qtip({
            content: 'Share via Twitter'
          });
    }
  });
});
<commit_msg>Fix copy to clipboard<commit_after>define(['backbone', 'zeroclipboard'], function(Backbone, ZeroClipboard) {
  'use strict';

  return Backbone.View.extend({
    el: '#share-container',

    initialize: function() {
      ZeroClipboard.config({
        swfPath: 'bower_components/ZeroClipboard/dist/ZeroClipboard.swf'
      });

      var copyToClipboard = $('#copy-to-clipboard'),
          clip = new ZeroClipboard(copyToClipboard),
          shortURLInput = $('#short-url');

      function getShortURL(callback) {
        var shortURL = shortURLInput.val();
        if (shortURL) {
          callback(shortURL);
        } else {
          $.getJSON('short_url.php', {
            url: location.href
          }, function(data) {
            shortURL = data.shorturl;
            if (shortURL) {
              shortURLInput.val(shortURL);
              callback(shortURL);
            }
          });
        }
      }

      shortURLInput.on('cut keydown', function (event) {
        // Prevent default actions on cut and keydown to simulate readOnly
        // behavior on input, as the readOnly attribute does not allow selection
        // on some mobile platforms.
        event.preventDefault();
      }).focus(function() {
        getShortURL(function() {
          // shortURLInput.select() does not work on iOS
          shortURLInput[0].setSelectionRange(0, 99);
        });
      }).mouseup(function (event) {
        // Prevent the mouseup event from unselecting the selection
        event.preventDefault();
      });

      var CLIPBOARD_TOOLTIP = 'Copy to Clipboard';
      copyToClipboard.qtip({
        content: CLIPBOARD_TOOLTIP,
        events: {
          hidden: function() {
            // Set to original text when hidden as text may have been changed.
            copyToClipboard.qtip('option', 'content.text', CLIPBOARD_TOOLTIP);
          }
        }
      });
      copyToClipboard.on('mouseover', function() {
        getShortURL(function(shortURL) {
          clip.setText(shortURL);
        });
      });
      clip.on('aftercopy', function() {
        copyToClipboard.qtip('option', 'content.text', 'Copied!');
      });

      $('#share-email').click(function() {
        getShortURL(function(shortURL) {
          window.location.href = 'mailto:?subject=My%20NUSMods.com%20Timetable&' +
              'body=' + encodeURIComponent(shortURL);
        });
      }).qtip({
            content: 'Share via Email'
          });

      $('#share-facebook').click(function() {
        getShortURL(function(shortURL) {
          window.open('http://www.facebook.com/sharer.php?u=' +
              encodeURIComponent(shortURL), '', 'width=660,height=350');
        });
      }).qtip({
            content: 'Share via Facebook'
          });

      $('#share-twitter').click(function() {
        getShortURL(function(shortURL) {
          window.open('http://twitter.com/intent/tweet?url=' +
              encodeURIComponent(shortURL), '', 'width=660,height=350');
        });
      }).qtip({
            content: 'Share via Twitter'
          });
    }
  });
});
<|endoftext|>


<commit_before>import {dialog} from 'electron';
import {isEmpty, first} from 'lodash';
import csv from 'fast-csv';
import fs from 'fs';
import {basename} from 'path';
import log from 'karmapa-log';
import sleep from 'sleep-promise';
import shortid from 'shortid';

import csvProcessor, {FIELD_PAGE_NUM} from './../../helpers/csvProcessor';
import pageNumToFloat from './../../helpers/pageNumToFloat';
import FRACTION_LENGTH from './../../constants/fractionLength';

export default async function addFolderByCsv(event, data) {

  const {models, importEmitter} = this.params;
  const {Folder, Entry} = models;
  const {broadcast, resolve, reject} = this;
  const {writeDelay} = data;

  const options = {
    properties: ['openFile'],
    filters: [
      {name: 'Csv Files', extensions: ['csv']}
    ]
  };

  dialog.showOpenDialog(options, handleDialogOpen);

  function processCsv(csvFilePath) {

    let cancelImporting = false;
    importEmitter.removeAllListeners();

    importEmitter.once('cancel-importing', () => {
      cancelImporting = true;
    });

    const filename = basename(csvFilePath);
    const stream = fs.createReadStream(csvFilePath);
    const timeStart = +new Date();

    let completedLines = 0;
    let hasColumnRow = false;
    let folder = null;
    let fields = [];
    let currentEntry = null;

    async function handleData(data) {

      if (cancelImporting) {
        return Promise.reject('User stopped importing');
      }

      if (isEmpty(folder) && csvProcessor.isColumnRow(data)) {
        const columnData = csvProcessor.getColumnData(data);
        folder = await Folder.create({
          name: `${filename} - ${shortid.generate()}`,
          data: columnData
        });
        broadcast('csv-folder-created', {folderId: folder.id});
        fields = csvProcessor.getFields(data);
        hasColumnRow = true;
      }
      else if (folder) {

        const rowData = csvProcessor.getRowDataByFields(data, fields);
        const {sourceEntry} = rowData;
        const pageNum = pageNumToFloat(rowData[FIELD_PAGE_NUM], FRACTION_LENGTH) || '';

        if (sourceEntry) {

          delete rowData.sourceEntry;
          delete rowData[FIELD_PAGE_NUM];

          await sleep(writeDelay);
          currentEntry = await Entry.create({
            folderId: folder.id,
            sourceEntry,
            pageNum,
            data: rowData
          });
        }
        else if (currentEntry) {
          const newData = csvProcessor.appendData(data, currentEntry.data, fields);
          await sleep(writeDelay);
          const rowsAffected = await Entry.update({id: currentEntry.id}, {data: newData});

          if (rowsAffected) {
            currentEntry.data = newData;
          }
        }
      }
      ++completedLines;

      const seconds = parseInt((+new Date() - timeStart) / 1000, 10);
      const linesPerSecond = Math.floor(completedLines / seconds);
      broadcast('csv-processing-status', {completedLines, linesPerSecond});
    }

    csv.fromStream(stream)
      .validate((data, next) => {
        handleData(data)
          .then(() => next(null, true))
          .catch((err) => next(err));
      })
      .on('data', () => {})
      .on('error', (err) => {
        log.error(err);
        reject({message: `${err}`});
      })
      .on('end', () => {

        if (! hasColumnRow) {
          reject({messageId: 'no-column-row-detected', filename});
          return;
        }

        broadcast('csv-processing-status', {completedLines});
        broadcast('csv-processing-done', {filename});
        resolve({message: 'done'});
      });
  }

  function handleDialogOpen(paths) {

    if (isEmpty(paths)) {
      resolve({message: 'User did not choose csv file'});
      return;
    }
    broadcast('csv-processing-start');
    const csvFilePath = first(paths);
    processCsv(csvFilePath);
  }
}
<commit_msg>add const NUMBER_CONCURRNT_WRITE<commit_after>import {dialog} from 'electron';
import {isEmpty, first} from 'lodash';
import csv from 'fast-csv';
import fs from 'fs';
import {basename} from 'path';
import log from 'karmapa-log';
import sleep from 'sleep-promise';
import shortid from 'shortid';

import csvProcessor, {FIELD_PAGE_NUM} from './../../helpers/csvProcessor';
import pageNumToFloat from './../../helpers/pageNumToFloat';
import FRACTION_LENGTH from './../../constants/fractionLength';

const NUMBER_CONCURRNT_WRITE = 5000;

export default async function addFolderByCsv(event, data) {

  const {models, importEmitter} = this.params;
  const {Folder, Entry} = models;
  const {broadcast, resolve, reject} = this;
  const {writeDelay} = data;

  const options = {
    properties: ['openFile'],
    filters: [
      {name: 'Csv Files', extensions: ['csv']}
    ]
  };

  dialog.showOpenDialog(options, handleDialogOpen);

  function processCsv(csvFilePath) {

    let cancelImporting = false;
    importEmitter.removeAllListeners();

    importEmitter.once('cancel-importing', () => {
      cancelImporting = true;
    });

    const filename = basename(csvFilePath);
    const stream = fs.createReadStream(csvFilePath);
    const timeStart = +new Date();

    let completedLines = 0;
    let hasColumnRow = false;
    let folder = null;
    let fields = [];
    let currentEntry = null;

    async function handleData(data) {

      if (cancelImporting) {
        return Promise.reject('User stopped importing');
      }

      if (isEmpty(folder) && csvProcessor.isColumnRow(data)) {
        const columnData = csvProcessor.getColumnData(data);
        folder = await Folder.create({
          name: `${filename} - ${shortid.generate()}`,
          data: columnData
        });
        broadcast('csv-folder-created', {folderId: folder.id});
        fields = csvProcessor.getFields(data);
        hasColumnRow = true;
      }
      else if (folder) {

        const rowData = csvProcessor.getRowDataByFields(data, fields);
        const {sourceEntry} = rowData;
        const pageNum = pageNumToFloat(rowData[FIELD_PAGE_NUM], FRACTION_LENGTH) || '';

        if (sourceEntry) {

          delete rowData.sourceEntry;
          delete rowData[FIELD_PAGE_NUM];

          await sleep(writeDelay);
          currentEntry = await Entry.create({
            folderId: folder.id,
            sourceEntry,
            pageNum,
            data: rowData
          });
        }
        else if (currentEntry) {
          const newData = csvProcessor.appendData(data, currentEntry.data, fields);
          await sleep(writeDelay);
          const rowsAffected = await Entry.update({id: currentEntry.id}, {data: newData});

          if (rowsAffected) {
            currentEntry.data = newData;
          }
        }
      }
      ++completedLines;

      const seconds = parseInt((+new Date() - timeStart) / 1000, 10);
      const linesPerSecond = Math.floor(completedLines / seconds);
      broadcast('csv-processing-status', {completedLines, linesPerSecond});
    }

    csv.fromStream(stream)
      .validate((data, next) => {
        handleData(data)
          .then(() => next(null, true))
          .catch((err) => next(err));
      })
      .on('data', () => {})
      .on('error', (err) => {
        log.error(err);
        reject({message: `${err}`});
      })
      .on('end', () => {

        if (! hasColumnRow) {
          reject({messageId: 'no-column-row-detected', filename});
          return;
        }

        broadcast('csv-processing-status', {completedLines});
        broadcast('csv-processing-done', {filename});
        resolve({message: 'done'});
      });
  }

  function handleDialogOpen(paths) {

    if (isEmpty(paths)) {
      resolve({message: 'User did not choose csv file'});
      return;
    }
    broadcast('csv-processing-start');
    const csvFilePath = first(paths);
    processCsv(csvFilePath);
  }
}
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  internal bootstrapping flag  */
_cs.bootstrapped = false;

/*  initialize library  */
$cs.bootstrap = function () {
    /*  sanity check environment  */
    if (_cs.bootstrapped)
        throw _cs.exception("bootstrap", "library already bootstrapped");

    /*  give plugins a chance to modify the component class definition  */
    _cs.hook("ComponentJS:bootstrap:comp:mixin",  "none", _cs.comp_mixins);
    _cs.hook("ComponentJS:bootstrap:comp:protos", "none", _cs.comp_protos);

    /*  lazy define component class
        (to give plugins a chance to have added mixins)  */
    _cs.comp = $cs.clazz({
        mixin:   _cs.comp_mixins,
        cons:    _cs.comp_cons,
        protos:  _cs.comp_protos
    });

    /*  create singleton component: root of the tree */
    _cs.root = new _cs.comp("<root>", null, []);

    /*  create singleton component: special return value on lookups */
    _cs.none = new _cs.comp("<none>", null, []);

    /*  reasonable error catching for _cs.none usage
        ATTENTION: method "exists" intentionally is missing here,
                   because it is required to be called on _cs.none, of course!  */
    var methods = [
        "call", "callable", "create", "destroy", "guard", "hook", "invoke",
        "latch", "link", "model", "observe", "plug", "property",
        "publish", "register", "registration", "socket", "spool",
        "spooled", "state", "state_compare", "store", "subscribe",
        "subscription", "touch", "unlatch", "unobserve", "unplug",
        "unregister", "unspool", "unsubscribe", "value"
    ];
    _cs.foreach(methods, function (method) {
        _cs.none[method] = function () {
            throw _cs.exception(method, "no such component " +
                "(you are calling method \"" + method + "\" on component \"<none>\")");
        };
    });

    /*  give plugins a chance to bootstrap, too  */
    _cs.hook("ComponentJS:bootstrap", "none");

    /*  set new state  */
    _cs.bootstrapped = true;
    return;
};

/*  shutdown library  */
$cs.shutdown = function () {
    /*  sanity check environment  */
    if (!_cs.bootstrapped)
        throw _cs.exception("shutdown", "library still not bootstrapped");

    /*  give plugins a chance to shutdown, too  */
    _cs.hook("ComponentJS:shutdown", "none");

    /*  destroy singleton "<none>" component
        (its "destroy" method was intentionally killed above!)  */
    _cs.none = null;

    /*  destroy singleton "<root>" component
        (its "destroy" method will destroy whole component tree!)  */
    _cs.root.destroy();
    _cs.root = null;

    /*  destroy component class  */
    _cs.comp = null;

    /*  set new state  */
    _cs.bootstrapped = false;
    return;
};

<commit_msg>correctly tear down the component tree in shutdown() as the root component cannot be directly destroyed<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*  internal bootstrapping flag  */
_cs.bootstrapped = false;

/*  initialize library  */
$cs.bootstrap = function () {
    /*  sanity check environment  */
    if (_cs.bootstrapped)
        throw _cs.exception("bootstrap", "library already bootstrapped");

    /*  give plugins a chance to modify the component class definition  */
    _cs.hook("ComponentJS:bootstrap:comp:mixin",  "none", _cs.comp_mixins);
    _cs.hook("ComponentJS:bootstrap:comp:protos", "none", _cs.comp_protos);

    /*  lazy define component class
        (to give plugins a chance to have added mixins)  */
    _cs.comp = $cs.clazz({
        mixin:   _cs.comp_mixins,
        cons:    _cs.comp_cons,
        protos:  _cs.comp_protos
    });

    /*  create singleton component: root of the tree */
    _cs.root = new _cs.comp("<root>", null, []);

    /*  create singleton component: special return value on lookups */
    _cs.none = new _cs.comp("<none>", null, []);

    /*  reasonable error catching for _cs.none usage
        ATTENTION: method "exists" intentionally is missing here,
                   because it is required to be called on _cs.none, of course!  */
    var methods = [
        "call", "callable", "create", "destroy", "guard", "hook", "invoke",
        "latch", "link", "model", "observe", "plug", "property",
        "publish", "register", "registration", "socket", "spool",
        "spooled", "state", "state_compare", "store", "subscribe",
        "subscription", "touch", "unlatch", "unobserve", "unplug",
        "unregister", "unspool", "unsubscribe", "value"
    ];
    _cs.foreach(methods, function (method) {
        _cs.none[method] = function () {
            throw _cs.exception(method, "no such component " +
                "(you are calling method \"" + method + "\" on component \"<none>\")");
        };
    });

    /*  give plugins a chance to bootstrap, too  */
    _cs.hook("ComponentJS:bootstrap", "none");

    /*  set new state  */
    _cs.bootstrapped = true;

    return;
};

/*  shutdown library  */
$cs.shutdown = function () {
    /*  sanity check environment  */
    if (!_cs.bootstrapped)
        throw _cs.exception("shutdown", "library still not bootstrapped");

    /*  give plugins a chance to shutdown, too  */
    _cs.hook("ComponentJS:shutdown", "none");

    /*  tear down the whole component tree  */
    _cs.foreach(_cs.root.children(), function (child) {
        child.destroy();
    });
    _cs.root.state({ state: "dead", sync: true });

    /*  destroy singleton "<none>" component  */
    _cs.none = null;

    /*  destroy singleton "<root>" component  */
    _cs.root = null;

    /*  destroy component class  */
    _cs.comp = null;

    /*  set new state  */
    _cs.bootstrapped = false;

    return;
};

<|endoftext|>


<commit_before>var Bitlash = require('../');
var SerialPort = require("serialport");
var async = require('async');

var baud = 115200;

function sendCommand(path, command, done){

  var self = this;
  var timeout = 30000;

  var data;

  var serialPort;
  async.series([
    function(cbStep) {
      serialPort = new SerialPort.SerialPort(path, {
          baudrate: baud
        }, cbStep);
    },
    function(cbStep){
      Bitlash.send(serialPort, cbStep);
    },
    function(cbStep){
      var opt = {
        timeout: 5000,
        cmd: command
      };

      Bitlash.send(serialPort, opt, function(err, results){
        if (err) {
          return cbStep(err);
        }

        data = results;
        cbStep();
      });
    }
    ],
    function(err) {
      serialPort.close();

      done(err, data);
    });
}

if(process && process.argv && process.argv[2] && process.argv[3])
{
  sendCommand(process.argv[2], process.argv[3], function(err, results){
    if(err){
      console.log(err);
      process.exit(1);
    }

    console.log(results);
    console.log("send success!");
    process.exit(0);

  });
}else
{
  console.log("call with /dev/tty.something led.on");
  process.exit(0);
}<commit_msg>jshint sendcommand<commit_after>var Bitlash = require('../');
var SerialPort = require('serialport');
var async = require('async');

var baud = 115200;

function sendCommand(path, command, done){

  var self = this;
  var timeout = 30000;

  var data;

  var serialPort;
  async.series([
    function(cbStep) {
      serialPort = new SerialPort.SerialPort(path, {
          baudrate: baud
        }, cbStep);
    },
    function(cbStep){
      Bitlash.send(serialPort, cbStep);
    },
    function(cbStep){
      var opt = {
        timeout: 5000,
        cmd: command
      };

      Bitlash.send(serialPort, opt, function(err, results){
        if (err) {
          return cbStep(err);
        }

        data = results;
        cbStep();
      });
    }
  ],
    function(err) {
      serialPort.close();

      done(err, data);
    });
}

if(process && process.argv && process.argv[2] && process.argv[3])
{
  sendCommand(process.argv[2], process.argv[3], function(err, results){
    if(err){
      console.log(err);
      process.exit(1);
    }

    console.log(results);
    console.log('send success!');
    process.exit(0);

  });
}else
{
  console.log('call with /dev/tty.something led.on');
  process.exit(0);
}<|endoftext|>


<commit_before>var cooking = require('cooking');
var config = require('./config');

cooking.set({
  entry: './src/index.js',
  dist: './lib/',
  clean: false,
  template: false,
  format: 'umd',
  moduleName: 'MINT',
  extractCSS: 'style.min.css',
  extends: ['vue2', 'saladcss', 'buble'],
  alias: config.alias,
  externals: { vue: config.externals.vue }
});

cooking.remove('output.publicPath');
cooking.add('output.filename', 'index.js');
cooking.add('loader.js.exclude', config.jsexclude);
cooking.add('vue.preserveWhitespace', false);

module.exports = cooking.resolve();
<commit_msg>设置sourceMap<commit_after>var cooking = require('cooking');
var config = require('./config');

cooking.set({
  entry: './src/index.js',
  dist: './lib/',
  clean: false,
  template: false,
  format: 'umd',
  moduleName: 'MINT',
  extractCSS: 'style.min.css',
  extends: ['vue2', 'saladcss', 'buble'],
  alias: config.alias,
  sourceMap: true,
  externals: { vue: config.externals.vue }
});

cooking.remove('output.publicPath');
cooking.add('output.filename', 'index.js');
cooking.add('loader.js.exclude', config.jsexclude);
cooking.add('vue.preserveWhitespace', false);

module.exports = cooking.resolve();
<|endoftext|>


<commit_before>module("editor");

window.editor = new Editor({
  toolbar: '#qunit-fixture .toolbar',
  editable: '#qunit-fixture .editable'
});

test("create", function() {
  ok(editor);
  ok(editor.toolbar.length);
  ok(editor.editable.length);
});

test("sanitize p", function() {
  // flatten nested p
  editor.editable.html(
    $('
').append($('
').text('line one')).append($('
').text('line two'))
  );
  editor.sanitize();
  equal(editor.editable.html(),
    '
line one
' +
    '
line two
'
  );

  // stript nested p if has text node
  editor.editable.html(
    $('
').text('text').append($('
').text('nested'))
  );
  editor.sanitize();
  equal(editor.editable.html(), '
textnested
');

  // stript more nested block
  editor.editable.html(
    $('
').text('text').append($('
').append($('
').text('nested')))
  );
  editor.sanitize();
  equal(editor.editable.html(), '
textnested
');
});
<commit_msg>add sanitizeTest funciton, add div to p test.<commit_after>module("editor");

window.editor = new Editor({
  toolbar: '#qunit-fixture .toolbar',
  editable: '#qunit-fixture .editable'
});

test("create", function() {
  ok(editor);
  ok(editor.toolbar.length);
  ok(editor.editable.length);
});

var sanitizeTest = function(html, expected) {
  editor.editable.html(html);
  editor.sanitize();
  equal(editor.editable.html(), expected);
};

test("sanitize p", function() {
  // flatten nested p
  sanitizeTest(
    $('
').append($('
').text('line one')).append($('
').text('line two')),
    '
line one

line two
'
  );

  // stript nested p if has text node
  sanitizeTest(
    $('
').text('text').append($('
').text('nested')),
    '
textnested
'
  );

  // stript more nested block
  sanitizeTest(
    $('
').text('text').append($('
').append($('
').text('nested'))),
    '
textnested
'
  );
});

test("div to p", function() {
  sanitizeTest(
    '
text
',
    '
text
'
  );
});
<|endoftext|>


<commit_before>/* jshint -W003, -W117, -W026, -W040 */

(function () {
  'use strict';

  angular.module('angular-royalslider', [])
    .directive('royalslider', npRoyalSliderDirective);

  /**
   * @inject
   * @constructor
   */
  function npRoyalSliderDirective($log, $timeout, $rootScope, sliders, screenSize) {
    var directive = {
      restrict: 'A',
      scope: {},
      link: link,
      controller: npRoyalSliderCtrl,
      controllerAs: 'vm'
    };

    return directive;

    /**
     * ngInject
     */
    function link(scope, element, attrs) {
      $log.debug('npRoyalSliderCtrl link', element);
      var opts = {
        keyboardNavEnabled: true,
        autoScaleSlider: true,
        controlNavigation: 'thumbnails',
        transitionType: 'fade'
      };

      var options = element.data();
      if (options.match) {
        if (!screenSize.is('xs, sm')) {
          opts = {
            addActiveClass: false,
            arrowsNav: false,
            autoScaleSlider: true,
            autoScaleSliderWidth: 200,
            autoScaleSliderHeight: 100,
            imageAlignCenter: false,
            imageScaleMode: 'fit-if-small',
            controlNavigation: 'none',
            autoHeight: true,
            loop: true,
            randomizeSlides: true,
            fadeinLoadedSlide: false,
            navigateByClick: false,
            visibleNearby: {
              enabled: true,
              centerArea: 0.2,
              center: true,
              breakpoint: 0,
              breakpointCenterArea: 0.6,
              navigateByCenterClick: false
            }
          };
        } else {
          opts = {
            addActiveClass: false,
            arrowsNav: false,
            autoScaleSlider: true,
            autoScaleSliderWidth: 800,
            autoScaleSliderHeight: 900,
            imageAlignCenter: false,
            imageScaleMode: 'fit',
            controlNavigation: 'none',
            autoHeight: true,
            loop: true,
            randomizeSlides: true,
            fadeinLoadedSlide: false,
            navigateByClick: false,
            visibleNearby: {
              enabled: false
            }
          };
        }
      }

      $timeout(function () {
        scope.$apply($(element).royalSlider(opts));
        $(element).data('royalSlider').ev.on('rsSlideClick', function(event, originalEvent) {
          // TODO - I think they want something to happen here...
          return;
        });

        // each slider is responsible for graying out their own slides
        $rootScope.$on('slider-disable-wrong', function () {
          var $correct = $(element).data('royalSlider').currSlide.holder;
          $correct.css('opacity', '0.5');
          $correct.data('correct', 'true');
        });

        $rootScope.$on('slider-enable-all', function () {
          $(element).find('.rsSlide').css('opacity', '').data('correct', 'false');
        });

        var slider = $(element).data('royalSlider');
        sliders[slider.uid] = slider;
      });
    }

    /**
     * @ngInject
     * @param $scope
     * @param $log
     */
    function npRoyalSliderCtrl($scope, $log) {
      var vm = this;
    }
  }

})();
<commit_msg>One more size update for the match game on desktop.<commit_after>/* jshint -W003, -W117, -W026, -W040 */

(function () {
  'use strict';

  angular.module('angular-royalslider', [])
    .directive('royalslider', npRoyalSliderDirective);

  /**
   * @inject
   * @constructor
   */
  function npRoyalSliderDirective($log, $timeout, $rootScope, sliders, screenSize) {
    var directive = {
      restrict: 'A',
      scope: {},
      link: link,
      controller: npRoyalSliderCtrl,
      controllerAs: 'vm'
    };

    return directive;

    /**
     * ngInject
     */
    function link(scope, element, attrs) {
      $log.debug('npRoyalSliderCtrl link', element);
      var opts = {
        keyboardNavEnabled: true,
        autoScaleSlider: true,
        controlNavigation: 'thumbnails',
        transitionType: 'fade'
      };

      var options = element.data();
      if (options.match) {
        if (!screenSize.is('xs, sm')) {
          opts = {
            addActiveClass: false,
            arrowsNav: false,
            autoScaleSlider: true,
            autoScaleSliderWidth: 600,
            autoScaleSliderHeight: 100,
            imageAlignCenter: false,
            imageScaleMode: 'fit-if-small',
            controlNavigation: 'none',
            autoHeight: true,
            loop: true,
            randomizeSlides: true,
            fadeinLoadedSlide: false,
            navigateByClick: false,
            visibleNearby: {
              enabled: true,
              centerArea: 0.2,
              center: true,
              breakpoint: 0,
              breakpointCenterArea: 0.6,
              navigateByCenterClick: false
            }
          };
        } else {
          opts = {
            addActiveClass: false,
            arrowsNav: false,
            autoScaleSlider: true,
            autoScaleSliderWidth: 800,
            autoScaleSliderHeight: 900,
            imageAlignCenter: false,
            imageScaleMode: 'fit',
            controlNavigation: 'none',
            autoHeight: true,
            loop: true,
            randomizeSlides: true,
            fadeinLoadedSlide: false,
            navigateByClick: false,
            visibleNearby: {
              enabled: false
            }
          };
        }
      }

      $timeout(function () {
        scope.$apply($(element).royalSlider(opts));
        $(element).data('royalSlider').ev.on('rsSlideClick', function(event, originalEvent) {
          // TODO - I think they want something to happen here...
          return;
        });

        // each slider is responsible for graying out their own slides
        $rootScope.$on('slider-disable-wrong', function () {
          var $correct = $(element).data('royalSlider').currSlide.holder;
          $correct.css('opacity', '0.5');
          $correct.data('correct', 'true');
        });

        $rootScope.$on('slider-enable-all', function () {
          $(element).find('.rsSlide').css('opacity', '').data('correct', 'false');
        });

        var slider = $(element).data('royalSlider');
        sliders[slider.uid] = slider;
      });
    }

    /**
     * @ngInject
     * @param $scope
     * @param $log
     */
    function npRoyalSliderCtrl($scope, $log) {
      var vm = this;
    }
  }

})();
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { getPost } from 'grommet-cms/containers/Posts/PostPage/actions';
import ContentBlocks from 'grommet-cms/containers/ContentBlocks';
import { WithLoading } from 'grommet-cms/components';
import Box from 'grommet/components/Box';
import Headline from 'grommet/components/Headline';

export class PostPage extends Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    this.props.dispatch(getPost(undefined, this.props.params.slug));
  }

  render() {
    const { post, request } = this.props;
    const title = (post && post.title)
      ? post.title
      : 'Post';
    const blocks = (post && post.contentBlocks)
      ? post.contentBlocks
      : undefined;
    const image = (post && post.image)
      ? post.image.path
      : undefined;

    return (
      <WithLoading isLoading={request} fullHeight>
        <Box className="labs" align="center">
          <Helmet title={title} />
          <Box
            texture={image}
            full="horizontal"
            size={{ height: 'medium' }}
            colorIndex="grey-1"
            justify="center"
            align="center"
          >
            <Headline size="medium" margin="none" strong={true}>
              {title}
            </Headline>
          </Box>
          <Box full>
            <ContentBlocks blocks={blocks} />
          </Box>
        </Box>
      </WithLoading>
    );
  }
};

function mapStateToProps(state, props) {
  const { post, error, request } = state.posts;
  return {
    post,
    error,
    request
  };
}

export default connect(mapStateToProps)(PostPage);
<commit_msg>Feat: add content blocks with sections to the post page<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import Helmet from 'react-helmet';
import { getPost } from 'grommet-cms/containers/Posts/PostPage/actions';
import ContentBlocks from 'grommet-cms/containers/ContentBlocks';
import { WithLoading } from 'grommet-cms/components';
import Box from 'grommet/components/Box';
import Section from 'grommet/components/Section';
import Headline from 'grommet/components/Headline';

export class PostPage extends Component {
  constructor(props) {
    super(props);
  }

  componentWillMount() {
    this.props.dispatch(getPost(undefined, this.props.params.slug));
  }

  render() {
    const { post, request } = this.props;
    const { sections } = post;
    const title = (post && post.title)
      ? post.title
      : 'Post';
    const image = (post && post.image)
      ? post.image.path
      : undefined;

    return (
      <WithLoading isLoading={request} fullHeight>
        <Box className="labs" align="center">
          <Helmet title={title} />
          <Box
            texture={image}
            full="horizontal"
            size={{ height: 'medium' }}
            colorIndex="grey-1"
            justify="center"
            align="center"
          >
            <Headline size="medium" margin="none" strong={true}>
              {title}
            </Headline>
          </Box>
          <Box full={!sections.length}>
            {sections && sections.map((item, i) =>
              <Section key={i} pad="large">
                <ContentBlocks blocks={item.contentBlocks} />
              </Section>
            )}
          </Box>
        </Box>
      </WithLoading>
    );
  }
};

function mapStateToProps(state, props) {
  const { post, error, request } = state.posts;
  return {
    post,
    error,
    request
  };
}

export default connect(mapStateToProps)(PostPage);
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';

class IconButton extends Component {
  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    disabled: PropTypes.bool,
    href: PropTypes.string,
    icon: PropTypes.element,
    onMouseLeave: PropTypes.func,
    onMouseUp: PropTypes.func,
    size: PropTypes.oneOf(['small', 'medium']),
    color: PropTypes.oneOf(['neutral', 'white', 'mint', 'violet', 'ruby', 'gold', 'aqua']),
    type: PropTypes.string,
  };

  static defaultProps = {
    className: '',
    size: 'medium',
    color: 'neutral',
    type: 'button',
  };

  handleMouseUp = event => {
    this.buttonNode.blur();
    if (this.props.onMouseUp) {
      this.props.onMouseUp(event);
    }
  };

  handleMouseLeave = event => {
    this.buttonNode.blur();
    if (this.props.onMouseLeave) {
      this.props.onMouseLeave(event);
    }
  };

  render() {
    const { children, className, disabled, href, icon, size, color, type, ...others } = this.props;

    const element = href ? 'a' : 'button';

    const classNames = cx(
      theme['button'],
      theme['icon-button'],
      theme[color],
      {
        [theme[size]]: theme[size],
      },
      className,
    );

    const props = {
      ...others,
      href,
      ref: node => {
        this.buttonNode = node;
      },
      className: classNames,
      disabled,
      onMouseUp: this.handleMouseUp,
      onMouseLeave: this.handleMouseLeave,
      type: !href ? type : null,
      'data-teamleader-ui': 'button',
    };

    return React.createElement(element, props, icon, children);
  }
}

export default IconButton;
export { IconButton };
<commit_msg>IconButton: remove named export in component file<commit_after>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import theme from './theme.css';

class IconButton extends Component {
  static propTypes = {
    children: PropTypes.node,
    className: PropTypes.string,
    disabled: PropTypes.bool,
    href: PropTypes.string,
    icon: PropTypes.element,
    onMouseLeave: PropTypes.func,
    onMouseUp: PropTypes.func,
    size: PropTypes.oneOf(['small', 'medium']),
    color: PropTypes.oneOf(['neutral', 'white', 'mint', 'violet', 'ruby', 'gold', 'aqua']),
    type: PropTypes.string,
  };

  static defaultProps = {
    className: '',
    size: 'medium',
    color: 'neutral',
    type: 'button',
  };

  handleMouseUp = event => {
    this.buttonNode.blur();
    if (this.props.onMouseUp) {
      this.props.onMouseUp(event);
    }
  };

  handleMouseLeave = event => {
    this.buttonNode.blur();
    if (this.props.onMouseLeave) {
      this.props.onMouseLeave(event);
    }
  };

  render() {
    const { children, className, disabled, href, icon, size, color, type, ...others } = this.props;

    const element = href ? 'a' : 'button';

    const classNames = cx(
      theme['button'],
      theme['icon-button'],
      theme[color],
      {
        [theme[size]]: theme[size],
      },
      className,
    );

    const props = {
      ...others,
      href,
      ref: node => {
        this.buttonNode = node;
      },
      className: classNames,
      disabled,
      onMouseUp: this.handleMouseUp,
      onMouseLeave: this.handleMouseLeave,
      type: !href ? type : null,
      'data-teamleader-ui': 'button',
    };

    return React.createElement(element, props, icon, children);
  }
}

export default IconButton;
<|endoftext|>


<commit_before>/*! jsroller 2014-10-05; Copyright 2014 Adrian Toncean; released under the MIT license */
(function(){var a,b,c,d;a={add:function(a){return new b(a)},find:function(){return null},isEmpty:function(){return!0}},b=function(b,c){this.value=b,this.next=null!=c?c:a},b.prototype.add=function(a){return new b(a,this)},b.prototype.find=function(a){return a(this.value)?this:this.next.find(a)},b.prototype.isEmpty=function(){return!1},null==window.roller&&(window.roller={}),null==(c=window.roller).Emp&&(c.Emp=a),null==(d=window.roller).List&&(d.List=b)}).call(this),function(){var a,b,c,d,e,f,g,h,i,j;h=function(a){var b,c;return b=function(b,d,e,f){var g,h;h=null,g=!0,h=a(b,d,e,f,function(a){return h=a},function(a){return g=a}),g&&c(b,h)},c=function(a,c){return Array.isArray(a)?a.forEach(function(d,e){b(d,a,e,c)}):a&&"object"==typeof a?Object.keys(a).forEach(function(d){b(a[d],a,d,c)}):void 0}},f=function(a){var b,c,d,e,f,g,i;return c=function(a){return a.declarations.map(function(a){return a.id.name})},e=new Set,i=[],g=[],d=[],b=[],f=function(a,f,h,j,k,l){var m;return null==a?void l(!1):void("FunctionDeclaration"===a.type||"FunctionExpression"===a.type?("FunctionDeclaration"===a.type&&(e.add(a.id.name),i.push({parent:a,key:"id",name:a.id.name})),b.push(a),l(!1)):"VariableDeclaration"===a.type?(m=c(a),m.forEach(function(a){e.add(a)})):"property"!==h||"MemberExpression"!==f.type||f.computed?"Literal"!==a.type||"Property"===f.type&&"key"===h?"Identifier"!==a.type||"Property"===f.type&&"key"===h||i.push({parent:f,key:h,name:a.name}):d.push({parent:f,key:h,value:a.raw}):g.push(f))},("FunctionDeclaration"===a.type||"FunctionExpression"===a.type)&&("FunctionExpression"===a.type&&null!=a.id&&(e.add(a.id.name),i.push({parent:a,key:"id",name:a.id.name})),a.params.forEach(function(b,c){e.add(b.name),i.push({parent:a.params,key:c,name:b.name})})),h(f)("FunctionDeclaration"===a.type||"FunctionExpression"===a.type?a.body:a),{localVars:e,varIds:i,memberExpressions:g,literalEntries:d,functions:b}},e=function(a,b){var c,d,e;for(null==b&&(b=""),d=b,c=e=0;a>=0?a>e:e>a;c=a>=0?++e:--e)d+="_";return d},c=function(a,b){return{type:"MemberExpression",computed:!1,object:{type:"Identifier",name:a},property:{type:"Identifier",name:b}}},d=function(a){var b;return b="var _ = {\n",a.forEach(function(a,c){b+="    "+a.newName+": '"+c+"',\n"}),b+="};"},b=function(a){var b;return b="var __ = {\n",a.forEach(function(a,c){b+="    "+a.newName+": "+c+",\n"}),b+="};"},a=function(a){var b;return b="var ___ = window;\nvar ____ = {\n",a.forEach(function(a,c){b+="    "+a.newName+": ___."+c+",\n"}),b+="};"},g=function(g,h){var i,j,k,l,m,n,o,p,q,r,s,t,u,v;return null==h&&(h={}),null==h.headers&&(h.headers=!0),k=function(a,b){var c,d;return d=new Map,c="",a.forEach(function(a){var e;e=b.find(function(b){return b.varsMap.has(a)}),null!=e?d.set(a,e.value.varsMap.get(a)):(c+="_",d.set(a,b.value.prefix+c))}),d},s=new Map,l=function(a){var b,d;return s.has(a)?s.get(a).newProperty:(b=e(s.size,"_"),d=c("_",b),s.set(a,{newName:b,newProperty:d}),d)},p=new Map,j=function(a){var b,d;return p.has(a)?p.get(a).newProperty:(b=e(p.size,"_"),d=c("__",b),p.set(a,{newName:b,newProperty:d}),d)},m=new Map,i=function(a){var b,d;return m.has(a)?m.get(a).newProperty:(b=e(m.size,"_"),d=c("___",b),m.set(a,{newName:b,newProperty:d}),d)},u=function(a,b){var c,d,g,h,m,n,o,p;p=f(a),g=p.localVars,n=p.varIds,h=p.memberExpressions,d=p.literalEntries,c=p.functions,o=k(g,b,b.value.prefix),m=b.add({varsMap:o,prefix:b.value.prefix+e(o.size)}),n.forEach(function(a){var b,c;c=a.parent[a.key],("arguments"!==c.name&&"name"!==c.name||o.has(c.name))&&(b=m.find(function(a){return a.varsMap.has(c.name)}),null!=b?c.name=b.value.varsMap.get(c.name):"window"===c.name?c.name="___":a.parent[a.key]=i(a.name))}),h.forEach(function(a){a.property=l(a.property.name),a.computed=!0}),d.forEach(function(a){a.parent[a.key]=j(a.value)}),c.forEach(function(a){u(a,m)})},v=esprima.parse(g),u(v,roller.Emp.add({varsMap:new Map,prefix:"_____"})),r=escodegen.generate(v),h.headers?(t=d(s),q=b(p),n=a(m),o="",s.size&&(o+=""+t+"\n"),p.size&&(o+=""+q+"\n"),m.size&&(o+=""+n+"\n"),o+r):r},null==window.roller&&(window.roller={}),null==(i=window.roller).obfuscate&&(i.obfuscate=g),null==(j=window.roller).getLevelInfo&&(j.getLevelInfo=f)}.call(this);<commit_msg>Updated build<commit_after>/*! jsroller 2014-10-06; Copyright 2014 Adrian Toncean; released under the MIT license */
(function(){var a,b,c,d;a={add:function(a){return new b(a)},find:function(){return null},isEmpty:function(){return!0}},b=function(b,c){this.value=b,this.next=null!=c?c:a},b.prototype.add=function(a){return new b(a,this)},b.prototype.find=function(a){return a(this.value)?this:this.next.find(a)},b.prototype.isEmpty=function(){return!1},null==window.roller&&(window.roller={}),null==(c=window.roller).Emp&&(c.Emp=a),null==(d=window.roller).List&&(d.List=b)}).call(this),function(){var a,b,c,d,e,f,g,h,i,j;h=function(a){var b,c;return b=function(b,d,e,f){var g,h;h=null,g=!0,h=a(b,d,e,f,function(a){return h=a},function(a){return g=a}),g&&c(b,h)},c=function(a,c){return Array.isArray(a)?a.forEach(function(d,e){b(d,a,e,c)}):a&&"object"==typeof a?Object.keys(a).forEach(function(d){b(a[d],a,d,c)}):void 0}},f=function(a){var b,c,d,e,f,g,i;return c=function(a){return a.declarations.map(function(a){return a.id.name})},e=new Set,i=[],g=[],d=[],b=[],f=function(a,f,h,j,k,l){var m;return null==a?void l(!1):void("FunctionDeclaration"===a.type||"FunctionExpression"===a.type?("FunctionDeclaration"===a.type&&(e.add(a.id.name),i.push({parent:a,key:"id",name:a.id.name})),b.push(a),l(!1)):"VariableDeclaration"===a.type?(m=c(a),m.forEach(function(a){e.add(a)})):"property"!==h||"MemberExpression"!==f.type||f.computed?"Literal"!==a.type||"Property"===f.type&&"key"===h?"Identifier"!==a.type||"Property"===f.type&&"key"===h||i.push({parent:f,key:h,name:a.name}):d.push({parent:f,key:h,value:a.raw}):g.push(f))},("FunctionDeclaration"===a.type||"FunctionExpression"===a.type)&&("FunctionExpression"===a.type&&null!=a.id&&(e.add(a.id.name),i.push({parent:a,key:"id",name:a.id.name})),a.params.forEach(function(b,c){e.add(b.name),i.push({parent:a.params,key:c,name:b.name})})),h(f)("FunctionDeclaration"===a.type||"FunctionExpression"===a.type?a.body:a),{localVars:e,varIds:i,memberExpressions:g,literalEntries:d,functions:b}},e=function(a,b){var c,d,e;for(null==b&&(b=""),d=b,c=e=0;a>=0?a>e:e>a;c=a>=0?++e:--e)d+="_";return d},c=function(a,b){return{type:"MemberExpression",computed:!1,object:{type:"Identifier",name:a},property:{type:"Identifier",name:b}}},d=function(a){var b;return b="var _ = {\n",a.forEach(function(a,c){b+="    "+a.newName+": '"+c+"',\n"}),b+="};"},b=function(a){var b;return b="var __ = {\n",a.forEach(function(a,c){b+="    "+a.newName+": "+c+",\n"}),b+="};"},a=function(a){var b;return b="var ___ = window;\nvar ____ = {\n",a.forEach(function(a,c){b+="    "+a.newName+": ___."+c+",\n"}),b+="};"},g=function(g,h){var i,j,k,l,m,n,o,p,q,r,s,t,u,v;return null==h&&(h={}),null==h.headers&&(h.headers=!0),null==h.wrap&&(h.wrap=!1),k=function(a,b){var c,d;return d=new Map,c="",a.forEach(function(a){var e;e=b.find(function(b){return b.varsMap.has(a)}),null!=e?d.set(a,e.value.varsMap.get(a)):(c+="_",d.set(a,b.value.prefix+c))}),d},s=new Map,l=function(a){var b,d;return s.has(a)?s.get(a).newProperty:(b=e(s.size,"_"),d=c("_",b),s.set(a,{newName:b,newProperty:d}),d)},p=new Map,j=function(a){var b,d;return p.has(a)?p.get(a).newProperty:(b=e(p.size,"_"),d=c("__",b),p.set(a,{newName:b,newProperty:d}),d)},m=new Map,i=function(a){var b,d;return m.has(a)?m.get(a).newProperty:(b=e(m.size,"_"),d=c("___",b),m.set(a,{newName:b,newProperty:d}),d)},u=function(a,b){var c,d,g,h,m,n,o,p;p=f(a),g=p.localVars,n=p.varIds,h=p.memberExpressions,d=p.literalEntries,c=p.functions,o=k(g,b,b.value.prefix),m=b.add({varsMap:o,prefix:b.value.prefix+e(o.size)}),n.forEach(function(a){var b,c;c=a.parent[a.key],("arguments"!==c.name&&"name"!==c.name||o.has(c.name))&&(b=m.find(function(a){return a.varsMap.has(c.name)}),null!=b?c.name=b.value.varsMap.get(c.name):"window"===c.name?c.name="___":a.parent[a.key]=i(a.name))}),h.forEach(function(a){a.property=l(a.property.name),a.computed=!0}),d.forEach(function(a){a.parent[a.key]=j(a.value)}),c.forEach(function(a){u(a,m)})},v=esprima.parse(g),u(v,roller.Emp.add({varsMap:new Map,prefix:"_____"})),r=escodegen.generate(v),h.headers&&(t=d(s),q=b(p),n=a(m),o="",s.size&&(o+=""+t+"\n"),p.size&&(o+=""+q+"\n"),m.size&&(o+=""+n+"\n"),r=o+r),h.wrap&&(r="(function () {\n"+r+"\n})();"),r},null==window.roller&&(window.roller={}),null==(i=window.roller).obfuscate&&(i.obfuscate=g),null==(j=window.roller).getLevelInfo&&(j.getLevelInfo=f)}.call(this);<|endoftext|>


<commit_before>// @flow
import { ledgerUSBVendorId } from "@ledgerhq/devices";

const ledgerDevices = [{ vendorId: ledgerUSBVendorId }];

export async function requestLedgerDevice(): Promise<USBDevice> {
  // $FlowFixMe
  const device = await navigator.usb.requestDevice({ filters: ledgerDevices });
  return device;
}

export async function getLedgerDevices(): Promise<USBDevice[]> {
  // $FlowFixMe
  const devices = await navigator.usb.getDevices();
  return devices.filter(d => d.vendorId === ledgerUSBVendorId);
}

export async function getFirstLedgerDevice(): Promise<USBDevice> {
  const existingDevices = await getLedgerDevices();
  if (existingDevices.length > 0) return existingDevices[0];
  return requestLedgerDevice();
}

export const isSupported = (): Promise<boolean> =>
  Promise.resolve(
    // $FlowFixMe
    !!navigator &&
      !!navigator.usb &&
        typeof navigator.usb.getDevices === 'function'
  );
<commit_msg>prettier<commit_after>// @flow
import { ledgerUSBVendorId } from "@ledgerhq/devices";

const ledgerDevices = [{ vendorId: ledgerUSBVendorId }];

export async function requestLedgerDevice(): Promise<USBDevice> {
  // $FlowFixMe
  const device = await navigator.usb.requestDevice({ filters: ledgerDevices });
  return device;
}

export async function getLedgerDevices(): Promise<USBDevice[]> {
  // $FlowFixMe
  const devices = await navigator.usb.getDevices();
  return devices.filter(d => d.vendorId === ledgerUSBVendorId);
}

export async function getFirstLedgerDevice(): Promise<USBDevice> {
  const existingDevices = await getLedgerDevices();
  if (existingDevices.length > 0) return existingDevices[0];
  return requestLedgerDevice();
}

export const isSupported = (): Promise<boolean> =>
  Promise.resolve(
    // $FlowFixMe
    !!navigator &&
      !!navigator.usb &&
      typeof navigator.usb.getDevices === "function"
  );
<|endoftext|>


<commit_before>'use strict';
const path = require('path');
const chalk = require('chalk');

/**
 * @typedef {import('../../types').Identifier} Identifier
 * @typedef {import('../../types').SimpleSupportStatement} SimpleSupportStatement
 * @typedef {import('../../types').SupportBlock} SupportBlock
 * @typedef {import('../../types').VersionValue} VersionValue
 * @typedef {import('../utils').Logger} Logger
 */

/** @type {string[]} */
const blockMany = [
  'chrome',
  'chrome_android',
  'edge',
  'firefox',
  'firefox_android',
  'ie',
  'opera',
  'opera_android',
  'safari',
  'safari_ios',
  'samsunginternet_android',
  'webview_android',
];

/** @type {Record<string, string[]>} */
const blockList = {
  api: [],
  css: [
    'chrome',
    'chrome_android',
    'edge',
    'firefox',
    'firefox_android',
    'ie',
    'safari',
    'safari_ios',
    'webview_android',
  ],
  html: [],
  http: [],
  svg: [],
  javascript: [
    'chrome',
    'chrome_android',
    'edge',
    'firefox',
    'firefox_android',
    'ie',
    'safari',
    'safari_ios',
    'webview_android',
  ],
  mathml: blockMany,
  webdriver: blockMany,
  webextensions: [],
  xpath: [],
  xslt: [],
};

/**
 * @param {SupportBlock} supportData
 * @param {string[]} blockList
 * @param {string} relPath
 * @param {Logger} logger
 */
function checkRealValues(supportData, blockList, relPath, logger) {
  for (const browser of blockList) {
    /** @type {SimpleSupportStatement[]} */
    const supportStatements = [];
    if (Array.isArray(supportData[browser])) {
      Array.prototype.push.apply(supportStatements, supportData[browser]);
    } else {
      supportStatements.push(supportData[browser]);
    }

    for (const statement of supportStatements) {
      if (statement === undefined) {
        logger.error(
          chalk`{red → {bold ${browser}} must be defined for {bold ${relPath}}}`,
        );
      } else {
        if ([true, null].includes(statement.version_added)) {
          logger.error(
            chalk`{red → {bold ${relPath}} - {bold ${browser}} no longer accepts {bold ${statement.version_added}} as a value}`,
          );
        }
        if ([true, null].includes(statement.version_removed)) {
          logger.error(
            chalk`{red → {bold ${relPath}} - {bold ${browser}} no longer accepts} {bold ${statement.version_removed}} as a value}`,
          );
        }
      }
    }
  }
}

/**
 * @param {string} filename
 */
function testRealValues(filename) {
  const relativePath = path.relative(
    path.resolve(__dirname, '..', '..'),
    filename,
  );
  const category =
    relativePath.includes(path.sep) && relativePath.split(path.sep)[0];
  /** @type {Identifier} */
  const data = require(filename);

  /** @type {string[]} */
  const errors = [];
  const logger = {
    /** @param {...unknown} message */
    error: (...message) => {
      errors.push(message.join(' '));
    },
  };

  /**
   * @param {Identifier} data
   * @param {string} [relPath]
   */
  function findSupport(data, relPath) {
    for (const prop in data) {
      if (prop === '__compat' && data[prop].support) {
        if (blockList[category] && blockList[category].length > 0)
          checkRealValues(
            data[prop].support,
            blockList[category],
            relPath,
            logger,
          );
      }
      const sub = data[prop];
      if (typeof sub === 'object') {
        findSupport(sub, relPath ? `${relPath}.${prop}` : `${prop}`);
      }
    }
  }
  findSupport(data);

  if (errors.length) {
    console.error(
      chalk`{red   Real values – {bold ${errors.length}} ${
        errors.length === 1 ? 'error' : 'errors'
      }:}`,
    );
    for (const error of errors) {
      console.error(`  ${error}`);
    }
    return true;
  }
  return false;
}

module.exports = testRealValues;
<commit_msg>Require real values for Opera Desktop/Android in javascript/ (#5670)<commit_after>'use strict';
const path = require('path');
const chalk = require('chalk');

/**
 * @typedef {import('../../types').Identifier} Identifier
 * @typedef {import('../../types').SimpleSupportStatement} SimpleSupportStatement
 * @typedef {import('../../types').SupportBlock} SupportBlock
 * @typedef {import('../../types').VersionValue} VersionValue
 * @typedef {import('../utils').Logger} Logger
 */

/** @type {string[]} */
const blockMany = [
  'chrome',
  'chrome_android',
  'edge',
  'firefox',
  'firefox_android',
  'ie',
  'opera',
  'opera_android',
  'safari',
  'safari_ios',
  'samsunginternet_android',
  'webview_android',
];

/** @type {Record<string, string[]>} */
const blockList = {
  api: [],
  css: [
    'chrome',
    'chrome_android',
    'edge',
    'firefox',
    'firefox_android',
    'ie',
    'safari',
    'safari_ios',
    'webview_android',
  ],
  html: [],
  http: [],
  svg: [],
  javascript: [
    'chrome',
    'chrome_android',
    'edge',
    'firefox',
    'firefox_android',
    'ie',
    'opera',
    'opera_android',
    'safari',
    'safari_ios',
    'webview_android',
  ],
  mathml: blockMany,
  webdriver: blockMany,
  webextensions: [],
  xpath: [],
  xslt: [],
};

/**
 * @param {SupportBlock} supportData
 * @param {string[]} blockList
 * @param {string} relPath
 * @param {Logger} logger
 */
function checkRealValues(supportData, blockList, relPath, logger) {
  for (const browser of blockList) {
    /** @type {SimpleSupportStatement[]} */
    const supportStatements = [];
    if (Array.isArray(supportData[browser])) {
      Array.prototype.push.apply(supportStatements, supportData[browser]);
    } else {
      supportStatements.push(supportData[browser]);
    }

    for (const statement of supportStatements) {
      if (statement === undefined) {
        logger.error(
          chalk`{red → {bold ${browser}} must be defined for {bold ${relPath}}}`,
        );
      } else {
        if ([true, null].includes(statement.version_added)) {
          logger.error(
            chalk`{red → {bold ${relPath}} - {bold ${browser}} no longer accepts {bold ${statement.version_added}} as a value}`,
          );
        }
        if ([true, null].includes(statement.version_removed)) {
          logger.error(
            chalk`{red → {bold ${relPath}} - {bold ${browser}} no longer accepts} {bold ${statement.version_removed}} as a value}`,
          );
        }
      }
    }
  }
}

/**
 * @param {string} filename
 */
function testRealValues(filename) {
  const relativePath = path.relative(
    path.resolve(__dirname, '..', '..'),
    filename,
  );
  const category =
    relativePath.includes(path.sep) && relativePath.split(path.sep)[0];
  /** @type {Identifier} */
  const data = require(filename);

  /** @type {string[]} */
  const errors = [];
  const logger = {
    /** @param {...unknown} message */
    error: (...message) => {
      errors.push(message.join(' '));
    },
  };

  /**
   * @param {Identifier} data
   * @param {string} [relPath]
   */
  function findSupport(data, relPath) {
    for (const prop in data) {
      if (prop === '__compat' && data[prop].support) {
        if (blockList[category] && blockList[category].length > 0)
          checkRealValues(
            data[prop].support,
            blockList[category],
            relPath,
            logger,
          );
      }
      const sub = data[prop];
      if (typeof sub === 'object') {
        findSupport(sub, relPath ? `${relPath}.${prop}` : `${prop}`);
      }
    }
  }
  findSupport(data);

  if (errors.length) {
    console.error(
      chalk`{red   Real values – {bold ${errors.length}} ${
        errors.length === 1 ? 'error' : 'errors'
      }:}`,
    );
    for (const error of errors) {
      console.error(`  ${error}`);
    }
    return true;
  }
  return false;
}

module.exports = testRealValues;
<|endoftext|>


<commit_before>"use strict";

/**
 * Main JS file for Casper behaviours
 */

/* globals jQuery, document */
(function ($, undefined) {
    "use strict";

    var $document = $(document);

    $document.ready(function () {

        var $postContent = $(".post-content");
        // $postContent.fitVids();

        // $(".scroll-down").arctic_scroll();

        $(".menu-button, .nav-cover, .nav-close").on("click", function (e) {
            e.preventDefault();
            $("body").toggleClass("nav-opened nav-closed");
        });
    });

    // Arctic Scroll by Paul Adam Davis
    // https://github.com/PaulAdamDavis/Arctic-Scroll
    // $.fn.arctic_scroll = function (options) {

    //     var defaults = {
    //         elem: $(this),
    //         speed: 500
    //     },

    //     allOptions = $.extend(defaults, options);

    //     allOptions.elem.click(function (event) {
    //         event.preventDefault();
    //         var $this = $(this),
    //             $htmlBody = $('html, body'),
    //             offset = ($this.attr('data-offset')) ? $this.attr('data-offset') : false,
    //             position = ($this.attr('data-position')) ? $this.attr('data-position') : false,
    //             toMove;

    //         if (offset) {
    //             toMove = parseInt(offset);
    //             $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top + toMove) }, allOptions.speed);
    //         } else if (position) {
    //             toMove = parseInt(position);
    //             $htmlBody.stop(true, false).animate({scrollTop: toMove }, allOptions.speed);
    //         } else {
    //             $htmlBody.stop(true, false).animate({scrollTop: ($(this.hash).offset().top) }, allOptions.speed);
    //         }
    //     });

    // };
})(jQuery);<commit_msg>remove commented code<commit_after>"use strict";

(function ($, undefined) {
    "use strict";

    var $document = $(document);

    $document.ready(function () {

        var $postContent = $(".post-content");

        $(".menu-button, .nav-cover, .nav-close").on("click", function (e) {
            e.preventDefault();
            $("body").toggleClass("nav-opened nav-closed");
        });
    });
})(jQuery);<|endoftext|>


<commit_before>import Signal from "signals";
import { mat4 } from "pex-math";

class DirectionalLight {
  constructor(opts) {
    this.type = "DirectionalLight";
    this.enabled = true;
    this.changed = new Signal();
    this.shadows = false;
    this.color = [1, 1, 1, 1];
    this.intensity = 1;
    this.bias = 0.1;
    this.castShadows = false;

    const ctx = opts.ctx;
    this._ctx = ctx;

    this._left = -10;
    this._right = 10;
    this._bottom = -10;
    this._top = 10;
    this._near = 2;
    this._far = 40;

    this._viewMatrix = mat4.create();
    this._projectionMatrix = mat4.create();

    this.set(opts);
  }

  init(entity) {
    this.entity = entity;
  }

  set(opts) {
    Object.assign(this, opts);
    if (opts.color !== undefined || opts.intensity !== undefined) {
      this.color[3] = this.intensity;
    }
    Object.keys(opts).forEach((prop) => this.changed.dispatch(prop));

    if (
      opts.castShadows &&
      !this._ctx.capabilities.isWebGL2 &&
      !this._ctx.capabilities.depthTexture
    ) {
      console.warn(
        "DirectionalLight.castShadows is not supported. WEBGL_depth_texture missing."
      );
      this.castShadows = false;
    }

    if (this.castShadows) {
      if (!this._colorMap) this.allocateResources();
    } else {
      if (this._colorMap) this.disposeResources();
    }
  }

  allocateResources() {
    const ctx = this._ctx;

    this._colorMap = ctx.texture2D({
      name: "directionalLightColorMap",
      width: 1024,
      height: 1024,
      pixelFormat: ctx.PixelFormat.RGBA8,
      encoding: ctx.Encoding.Linear,
      min: ctx.Filter.Linear,
      mag: ctx.Filter.Linear,
    });

    this._shadowMap = ctx.texture2D({
      name: "directionalLightShadowMap",
      width: 1024,
      height: 1024,
      pixelFormat: ctx.PixelFormat.DEPTH_COMPONENT16,
      encoding: ctx.Encoding.Linear,
    });

    this._shadowMapDrawCommand = {
      name: "DirectionalLight.shadowMap",
      pass: ctx.pass({
        name: "DirectionalLight.shadowMap",
        color: [this._colorMap],
        depth: this._shadowMap,
        clearColor: [0, 0, 0, 1],
        clearDepth: 1,
      }),
      viewport: [0, 0, 1024, 1024], // TODO: viewport bug
      // colorMask: [0, 0, 0, 0] // TODO
    };
  }

  disposeResources() {
    const ctx = this._ctx;

    ctx.dispose(this._colorMap);
    this._colorMap = null;

    ctx.dispose(this._shadowMap);
    this._shadowMap = null;

    ctx.dispose(this._shadowMapDrawCommand.pipeline);
    this._shadowMapDrawCommand = null;
  }
}

export default (opts = {}) => {
  return {
    ...opts,
    castShadows: false, //TODO: temp overwrite
  };
};
<commit_msg>fix(components/directional-light): re-enable shadows <commit_after>import Signal from "signals";
import { mat4 } from "pex-math";

class DirectionalLight {
  constructor(opts) {
    this.type = "DirectionalLight";
    this.enabled = true;
    this.changed = new Signal();
    this.shadows = false;
    this.color = [1, 1, 1, 1];
    this.intensity = 1;
    this.bias = 0.1;
    this.castShadows = false;

    const ctx = opts.ctx;
    this._ctx = ctx;

    this._left = -10;
    this._right = 10;
    this._bottom = -10;
    this._top = 10;
    this._near = 2;
    this._far = 40;

    this._viewMatrix = mat4.create();
    this._projectionMatrix = mat4.create();

    this.set(opts);
  }

  init(entity) {
    this.entity = entity;
  }

  set(opts) {
    Object.assign(this, opts);
    if (opts.color !== undefined || opts.intensity !== undefined) {
      this.color[3] = this.intensity;
    }
    Object.keys(opts).forEach((prop) => this.changed.dispatch(prop));

    if (
      opts.castShadows &&
      !this._ctx.capabilities.isWebGL2 &&
      !this._ctx.capabilities.depthTexture
    ) {
      console.warn(
        "DirectionalLight.castShadows is not supported. WEBGL_depth_texture missing."
      );
      this.castShadows = false;
    }

    if (this.castShadows) {
      if (!this._colorMap) this.allocateResources();
    } else {
      if (this._colorMap) this.disposeResources();
    }
  }

  allocateResources() {
    const ctx = this._ctx;

    this._colorMap = ctx.texture2D({
      name: "directionalLightColorMap",
      width: 1024,
      height: 1024,
      pixelFormat: ctx.PixelFormat.RGBA8,
      encoding: ctx.Encoding.Linear,
      min: ctx.Filter.Linear,
      mag: ctx.Filter.Linear,
    });

    this._shadowMap = ctx.texture2D({
      name: "directionalLightShadowMap",
      width: 1024,
      height: 1024,
      pixelFormat: ctx.PixelFormat.DEPTH_COMPONENT16,
      encoding: ctx.Encoding.Linear,
    });

    this._shadowMapDrawCommand = {
      name: "DirectionalLight.shadowMap",
      pass: ctx.pass({
        name: "DirectionalLight.shadowMap",
        color: [this._colorMap],
        depth: this._shadowMap,
        clearColor: [0, 0, 0, 1],
        clearDepth: 1,
      }),
      viewport: [0, 0, 1024, 1024], // TODO: viewport bug
      // colorMask: [0, 0, 0, 0] // TODO
    };
  }

  disposeResources() {
    const ctx = this._ctx;

    ctx.dispose(this._colorMap);
    this._colorMap = null;

    ctx.dispose(this._shadowMap);
    this._shadowMap = null;

    ctx.dispose(this._shadowMapDrawCommand.pipeline);
    this._shadowMapDrawCommand = null;
  }
}

export default (opts = {}) => {
  return {
    ...opts,
  };
};
<|endoftext|>


<commit_before>var queue = [];
var blocking = false;

function reset(fixture) {
	synchronize(function() {
		document.getElementById('main').innerHTML = fixture;
	});
}

function synchronize(callback) {
	queue[queue.length] = callback;
	if(!blocking) {
		process();
	}
}

function process() {
	while(queue.length && !blocking) {
		var call = queue[0];
		queue = queue.slice(1);
		call();
	}
}

function runTests(files) {
	var fixture = document.getElementById('main').innerHTML;
	var startTime = new Date();
	for( var i=0; i < files.length; i++) {
		runTest( files, i );
		reset(fixture);
	}
	synchronize(function() {
		var runTime = new Date() - startTime;
		// lets use jQuery for this, its not important anyway
		$('body').append('
Tests completed in ' + runTime + ' milliseconds.');
	});
}

function runTest( files, num ) {
	synchronize(function() {
		blocking = true;
		$.get(files[num],function(js) {
			evaluateTest(files, num, js);
		});
	});
}

function evaluateTest(files, num, js) {
	var Test = [];
	js = js.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");

	try {
		eval(js);
	} catch(e) {
		if(typeof console != "undefined")
			console.error(e);
			console.debug(js);
		Test.push( [ false, "Died on test #" + (Test.length+1) + ": " + e ] );
	}

	var good = 0, bad = 0;
	var ol = document.createElement("ol");

	var li = "", state = "pass";
	for ( var i = 0; i < Test.length; i++ ) {
		var li = document.createElement("li");
		li.className = Test[i][0] ? "pass" : "fail";
		li.innerHTML = Test[i][1];
		ol.appendChild( li );

		if ( !Test[i][0] ) {
			state = "fail";
			bad++;
		} else good++;
	}

	var li = document.createElement("li");
	li.className = state;

	var b = document.createElement("b");
	b.innerHTML = files[num] + " (" + bad + ", " + good + ", " + Test.length + ")";
	b.onclick = function(){
		var n = this.nextSibling;
		if ( jQuery.css( n, "display" ) == "none" )
			n.style.display = "block";
		else
			n.style.display = "none";
	};
	li.appendChild( b );

	li.appendChild( ol );

	document.getElementById("tests").appendChild( li );

	blocking = false;
	process();

	function ok(a, msg) {
		Test.push( [ !!a, msg ] );
	}

	function cmpOK( a, c, b, msg ) {
		var res;
		eval( "res = (a " + c + " b)" );
		Test.push( [ res, msg ] );
	}

	function isSet(a, b, msg) {
		var ret = true;

		if ( a && b && a.length == b.length ) {
			for ( var i in a )
				if ( a[i] != b[i] )
					ret = false;
		} else
			ret = false;

		if ( !ret && console )
			console.log( msg, a, b );

		Test.push( [ ret, msg ] );
	}

	function q() {
		var r = [];

		for ( var i = 0; i < arguments.length; i++ )
			r.push( document.getElementById( arguments[i] ) );

		return r;
	}

	function t(a,b,c) {
		var f = jQuery.find(b);

		var s = "";
		for ( var i = 0; i < f.length; i++ )
			s += (s && ",") + '"' + f[i].id + '"';

		isSet(f, q.apply(q,c), a + " (" + b + ")");
	}
}<commit_msg>Fixed missing brackets (d'oh)<commit_after>var queue = [];
var blocking = false;

function reset(fixture) {
	synchronize(function() {
		document.getElementById('main').innerHTML = fixture;
	});
}

function synchronize(callback) {
	queue[queue.length] = callback;
	if(!blocking) {
		process();
	}
}

function process() {
	while(queue.length && !blocking) {
		var call = queue[0];
		queue = queue.slice(1);
		call();
	}
}

function runTests(files) {
	var fixture = document.getElementById('main').innerHTML;
	var startTime = new Date();
	for( var i=0; i < files.length; i++) {
		runTest( files, i );
		reset(fixture);
	}
	synchronize(function() {
		var runTime = new Date() - startTime;
		// lets use jQuery for this, its not important anyway
		$('body').append('
Tests completed in ' + runTime + ' milliseconds.');
	});
}

function runTest( files, num ) {
	synchronize(function() {
		blocking = true;
		$.get(files[num],function(js) {
			evaluateTest(files, num, js);
		});
	});
}

function evaluateTest(files, num, js) {
	var Test = [];
	js = js.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");

	try {
		eval(js);
	} catch(e) {
		if(typeof console != "undefined") {
			console.error(e);
			console.debug(js);
		}
		Test.push( [ false, "Died on test #" + (Test.length+1) + ": " + e ] );
	}

	var good = 0, bad = 0;
	var ol = document.createElement("ol");

	var li = "", state = "pass";
	for ( var i = 0; i < Test.length; i++ ) {
		var li = document.createElement("li");
		li.className = Test[i][0] ? "pass" : "fail";
		li.innerHTML = Test[i][1];
		ol.appendChild( li );

		if ( !Test[i][0] ) {
			state = "fail";
			bad++;
		} else good++;
	}

	var li = document.createElement("li");
	li.className = state;

	var b = document.createElement("b");
	b.innerHTML = files[num] + " (" + bad + ", " + good + ", " + Test.length + ")";
	b.onclick = function(){
		var n = this.nextSibling;
		if ( jQuery.css( n, "display" ) == "none" )
			n.style.display = "block";
		else
			n.style.display = "none";
	};
	li.appendChild( b );

	li.appendChild( ol );

	document.getElementById("tests").appendChild( li );

	blocking = false;
	process();

	function ok(a, msg) {
		Test.push( [ !!a, msg ] );
	}

	function cmpOK( a, c, b, msg ) {
		var res;
		eval( "res = (a " + c + " b)" );
		Test.push( [ res, msg ] );
	}

	function isSet(a, b, msg) {
		var ret = true;

		if ( a && b && a.length == b.length ) {
			for ( var i in a )
				if ( a[i] != b[i] )
					ret = false;
		} else
			ret = false;

		if ( !ret && console )
			console.log( msg, a, b );

		Test.push( [ ret, msg ] );
	}

	function q() {
		var r = [];

		for ( var i = 0; i < arguments.length; i++ )
			r.push( document.getElementById( arguments[i] ) );

		return r;
	}

	function t(a,b,c) {
		var f = jQuery.find(b);

		var s = "";
		for ( var i = 0; i < f.length; i++ )
			s += (s && ",") + '"' + f[i].id + '"';

		isSet(f, q.apply(q,c), a + " (" + b + ")");
	}
}<|endoftext|>