<commit_before>import { takeLatest, takeEvery } from 'redux-saga';
import { call, put, select, fork } from 'redux-saga/effects';
import { loadFollows, fetchFollowCount } from 'app/redux/FollowSaga';
import { getContent } from 'app/redux/SagaShared';
import * as globalActions from './GlobalReducer';
import * as appActions from './AppReducer';
import constants from './constants';
import { fromJS, Map, Set } from 'immutable';
import { api } from '@steemit/steem-js';

const REQUEST_DATA = 'fetchDataSaga/REQUEST_DATA';
const GET_CONTENT = 'fetchDataSaga/GET_CONTENT';
const FETCH_STATE = 'fetchDataSaga/FETCH_STATE';

export const fetchDataWatches = [
    watchLocationChange,
    watchDataRequests,
    watchFetchJsonRequests,
    watchFetchState,
    watchGetContent,
];

export function* watchDataRequests() {
    yield* takeLatest(REQUEST_DATA, fetchData);
}

export function* watchGetContent() {
    yield* takeEvery(GET_CONTENT, getContentCaller);
}

export function* getContentCaller(action) {
    yield getContent(action.payload);
}

let is_initial_state = true;
export function* fetchState(location_change_action) {
    const { pathname } = location_change_action.payload;
    const m = pathname.match(/^\/@([a-z0-9\.-]+)/);
    if (m && m.length === 2) {
        const username = m[1];
        yield fork(fetchFollowCount, username);
        yield fork(loadFollows, 'getFollowersAsync', username, 'blog');
        yield fork(loadFollows, 'getFollowingAsync', username, 'blog');
    }

    // `ignore_fetch` case should only trigger on initial page load. No need to call
    // fetchState immediately after loading fresh state from the server. Details: #593
    const server_location = yield select(state =>
        state.offchain.get('server_location')
    );
    const ignore_fetch = pathname === server_location && is_initial_state;
    is_initial_state = false;
    if (ignore_fetch) {
        // If a user's transfer page is being loaded, fetch related account data.
        yield call(getTransferUsers, pathname);

        return;
    }

    let url = `${pathname}`;
    if (url === '/') url = 'trending';
    // Replace /curation-rewards and /author-rewards with /transfers for UserProfile
    // to resolve data correctly
    if (url.indexOf('/curation-rewards') !== -1)
        url = url.replace('/curation-rewards', '/transfers');
    if (url.indexOf('/author-rewards') !== -1)
        url = url.replace('/author-rewards', '/transfers');

    yield put(appActions.fetchDataBegin());
    try {
        const state = yield call([api, api.getStateAsync], url);
        yield put(globalActions.receiveState(state));
        // If a user's transfer page is being loaded, fetch related account data.
        yield call(getTransferUsers, pathname);
    } catch (error) {
        console.error('~~ Saga fetchState error ~~>', url, error);
        yield put(appActions.steemApiError(error.message));
    }

    yield put(appActions.fetchDataEnd());
}

/**
 * Get transfer-related usernames from history and fetch their account data.
 *
 * @param {String} pathname
 */
function* getTransferUsers(pathname) {
    if (pathname.match(/^\/@([a-z0-9\.-]+)\/transfers/)) {
        const username = pathname.match(/^\/@([a-z0-9\.-]+)/)[1];

        const transferHistory = yield select(state =>
            state.global.getIn(['accounts', username, 'transfer_history'])
        );

        // Find users in the transfer history to consider sending users' reputations.
        const transferUsers = transferHistory.reduce((acc, cur) => {
            if (cur.getIn([1, 'op', 0]) === 'transfer') {
                const { from, to } = cur.getIn([1, 'op', 1]).toJS();
                return acc.add(from);
            }
            return acc;
            // Ensure current user is included in this list, even if they don't have transfer history.
            // This ensures their reputation is updated - fixes #2306
        }, new Set([username]));

        yield call(getAccounts, transferUsers);
    }
}

/**
 * Request account data for a set of usernames.
 *
 * @todo batch the put()s
 *
 * @param {Iterable} usernames
 */
function* getAccounts(usernames) {
    const accounts = yield call([api, api.getAccountsAsync], usernames);
    yield put(globalActions.receiveAccounts({ accounts }));
}

export function* watchLocationChange() {
    yield* takeLatest('@@router/LOCATION_CHANGE', fetchState);
}

export function* watchFetchState() {
    yield* takeLatest(FETCH_STATE, fetchState);
}

export function* fetchData(action) {
    const { order, author, permlink, accountname } = action.payload;
    let { category } = action.payload;
    if (!category) category = '';
    category = category.toLowerCase();

    yield put(globalActions.fetchingData({ order, category }));
    let call_name, args;
    if (order === 'trending') {
        call_name = 'getDiscussionsByTrendingAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'trending30') {
        call_name = 'getDiscussionsByTrending30Async';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'promoted') {
        call_name = 'getDiscussionsByPromotedAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'active') {
        call_name = 'getDiscussionsByActiveAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'cashout') {
        call_name = 'getDiscussionsByCashoutAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'payout') {
        call_name = 'getPostDiscussionsByPayout';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'payout_comments') {
        call_name = 'getCommentDiscussionsByPayout';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'updated') {
        call_name = 'getDiscussionsByActiveAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'created' || order === 'recent') {
        call_name = 'getDiscussionsByCreatedAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'by_replies') {
        call_name = 'getRepliesByLastUpdateAsync';
        args = [author, permlink, constants.FETCH_DATA_BATCH_SIZE];
    } else if (order === 'responses') {
        call_name = 'getDiscussionsByChildrenAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'votes') {
        call_name = 'getDiscussionsByVotesAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'hot') {
        call_name = 'getDiscussionsByHotAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'by_feed') {
        // https://github.com/steemit/steem/issues/249
        call_name = 'getDiscussionsByFeedAsync';
        args = [
            {
                tag: accountname,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'by_author') {
        call_name = 'getDiscussionsByBlogAsync';
        args = [
            {
                tag: accountname,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'by_comments') {
        call_name = 'getDiscussionsByCommentsAsync';
        args = [
            {
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else {
        call_name = 'getDiscussionsByActiveAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    }
    yield put(appActions.fetchDataBegin());
    try {
        const data = yield call([api, api[call_name]], ...args);
        yield put(
            globalActions.receiveData({
                data,
                order,
                category,
                author,
                permlink,
                accountname,
            })
        );
    } catch (error) {
        console.error('~~ Saga fetchData error ~~>', call_name, args, error);
        yield put(appActions.steemApiError(error.message));
    }
    yield put(appActions.fetchDataEnd());
}

// export function* watchMetaRequests() {
//     yield* takeLatest('global/REQUEST_META', fetchMeta);
// }
export function* fetchMeta({ payload: { id, link } }) {
    try {
        const metaArray = yield call(
            () =>
                new Promise((resolve, reject) => {
                    function reqListener() {
                        const resp = JSON.parse(this.responseText);
                        if (resp.error) {
                            reject(resp.error);
                            return;
                        }
                        resolve(resp);
                    }
                    const oReq = new XMLHttpRequest();
                    oReq.addEventListener('load', reqListener);
                    oReq.open('GET', '/http_metadata/' + link);
                    oReq.send();
                })
        );
        const { title, metaTags } = metaArray;
        let meta = { title };
        for (let i = 0; i < metaTags.length; i++) {
            const [name, content] = metaTags[i];
            meta[name] = content;
        }
        // http://postimg.org/image/kbefrpbe9/
        meta = {
            link,
            card: meta['twitter:card'],
            site: meta['twitter:site'], // @username tribbute
            title: meta['twitter:title'],
            description: meta['twitter:description'],
            image: meta['twitter:image'],
            alt: meta['twitter:alt'],
        };
        if (!meta.image) {
            meta.image = meta['twitter:image:src'];
        }
        yield put(globalActions.receiveMeta({ id, meta }));
    } catch (error) {
        yield put(globalActions.receiveMeta({ id, meta: { error } }));
    }
}

export function* watchFetchJsonRequests() {
    yield* takeEvery('global/FETCH_JSON', fetchJson);
}

/**
    @arg {string} id unique key for result global['fetchJson_' + id]
    @arg {string} url
    @arg {object} body (for JSON.stringify)
*/
function* fetchJson({
    payload: { id, url, body, successCallback, skipLoading = false },
}) {
    try {
        const payload = {
            method: body ? 'POST' : 'GET',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: body ? JSON.stringify(body) : undefined,
        };
        let result = yield skipLoading
            ? fetch(url, payload)
            : call(fetch, url, payload);
        result = yield result.json();
        if (successCallback) result = successCallback(result);
        yield put(globalActions.fetchJsonResult({ id, result }));
    } catch (error) {
        console.error('fetchJson', error);
        yield put(globalActions.fetchJsonResult({ id, error }));
    }
}

// Action creators
export const actions = {
    requestData: payload => ({
        type: REQUEST_DATA,
        payload,
    }),

    getContent: payload => ({
        type: GET_CONTENT,
        payload,
    }),

    fetchState: payload => ({
        type: FETCH_STATE,
        payload,
    }),
};
<commit_msg>refactor FetchDataSaga watchers<commit_after>import { takeLatest, takeEvery } from 'redux-saga';
import { call, put, select, fork } from 'redux-saga/effects';
import { loadFollows, fetchFollowCount } from 'app/redux/FollowSaga';
import { getContent } from 'app/redux/SagaShared';
import * as globalActions from './GlobalReducer';
import * as appActions from './AppReducer';
import constants from './constants';
import { fromJS, Map, Set } from 'immutable';
import { api } from '@steemit/steem-js';

const REQUEST_DATA = 'fetchDataSaga/REQUEST_DATA';
const GET_CONTENT = 'fetchDataSaga/GET_CONTENT';
const FETCH_STATE = 'fetchDataSaga/FETCH_STATE';

export const fetchDataWatches = [
    takeLatest(REQUEST_DATA, fetchData),
    takeEvery(GET_CONTENT, getContentCaller),
    takeLatest('@@router/LOCATION_CHANGE', fetchState),
    takeLatest(FETCH_STATE, fetchState),
    takeEvery('global/FETCH_JSON', fetchJson),
];

export function* getContentCaller(action) {
    yield getContent(action.payload);
}

let is_initial_state = true;
export function* fetchState(location_change_action) {
    const { pathname } = location_change_action.payload;
    const m = pathname.match(/^\/@([a-z0-9\.-]+)/);
    if (m && m.length === 2) {
        const username = m[1];
        yield fork(fetchFollowCount, username);
        yield fork(loadFollows, 'getFollowersAsync', username, 'blog');
        yield fork(loadFollows, 'getFollowingAsync', username, 'blog');
    }

    // `ignore_fetch` case should only trigger on initial page load. No need to call
    // fetchState immediately after loading fresh state from the server. Details: #593
    const server_location = yield select(state =>
        state.offchain.get('server_location')
    );
    const ignore_fetch = pathname === server_location && is_initial_state;
    is_initial_state = false;
    if (ignore_fetch) {
        // If a user's transfer page is being loaded, fetch related account data.
        yield call(getTransferUsers, pathname);

        return;
    }

    let url = `${pathname}`;
    if (url === '/') url = 'trending';
    // Replace /curation-rewards and /author-rewards with /transfers for UserProfile
    // to resolve data correctly
    if (url.indexOf('/curation-rewards') !== -1)
        url = url.replace('/curation-rewards', '/transfers');
    if (url.indexOf('/author-rewards') !== -1)
        url = url.replace('/author-rewards', '/transfers');

    yield put(appActions.fetchDataBegin());
    try {
        const state = yield call([api, api.getStateAsync], url);
        yield put(globalActions.receiveState(state));
        // If a user's transfer page is being loaded, fetch related account data.
        yield call(getTransferUsers, pathname);
    } catch (error) {
        console.error('~~ Saga fetchState error ~~>', url, error);
        yield put(appActions.steemApiError(error.message));
    }

    yield put(appActions.fetchDataEnd());
}

/**
 * Get transfer-related usernames from history and fetch their account data.
 *
 * @param {String} pathname
 */
function* getTransferUsers(pathname) {
    if (pathname.match(/^\/@([a-z0-9\.-]+)\/transfers/)) {
        const username = pathname.match(/^\/@([a-z0-9\.-]+)/)[1];

        const transferHistory = yield select(state =>
            state.global.getIn(['accounts', username, 'transfer_history'])
        );

        // Find users in the transfer history to consider sending users' reputations.
        const transferUsers = transferHistory.reduce((acc, cur) => {
            if (cur.getIn([1, 'op', 0]) === 'transfer') {
                const { from, to } = cur.getIn([1, 'op', 1]).toJS();
                return acc.add(from);
            }
            return acc;
            // Ensure current user is included in this list, even if they don't have transfer history.
            // This ensures their reputation is updated - fixes #2306
        }, new Set([username]));

        yield call(getAccounts, transferUsers);
    }
}

/**
 * Request account data for a set of usernames.
 *
 * @todo batch the put()s
 *
 * @param {Iterable} usernames
 */
function* getAccounts(usernames) {
    const accounts = yield call([api, api.getAccountsAsync], usernames);
    yield put(globalActions.receiveAccounts({ accounts }));
}

export function* fetchData(action) {
    const { order, author, permlink, accountname } = action.payload;
    let { category } = action.payload;
    if (!category) category = '';
    category = category.toLowerCase();

    yield put(globalActions.fetchingData({ order, category }));
    let call_name, args;
    if (order === 'trending') {
        call_name = 'getDiscussionsByTrendingAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'trending30') {
        call_name = 'getDiscussionsByTrending30Async';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'promoted') {
        call_name = 'getDiscussionsByPromotedAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'active') {
        call_name = 'getDiscussionsByActiveAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'cashout') {
        call_name = 'getDiscussionsByCashoutAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'payout') {
        call_name = 'getPostDiscussionsByPayout';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'payout_comments') {
        call_name = 'getCommentDiscussionsByPayout';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'updated') {
        call_name = 'getDiscussionsByActiveAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'created' || order === 'recent') {
        call_name = 'getDiscussionsByCreatedAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'by_replies') {
        call_name = 'getRepliesByLastUpdateAsync';
        args = [author, permlink, constants.FETCH_DATA_BATCH_SIZE];
    } else if (order === 'responses') {
        call_name = 'getDiscussionsByChildrenAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'votes') {
        call_name = 'getDiscussionsByVotesAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'hot') {
        call_name = 'getDiscussionsByHotAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'by_feed') {
        // https://github.com/steemit/steem/issues/249
        call_name = 'getDiscussionsByFeedAsync';
        args = [
            {
                tag: accountname,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'by_author') {
        call_name = 'getDiscussionsByBlogAsync';
        args = [
            {
                tag: accountname,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else if (order === 'by_comments') {
        call_name = 'getDiscussionsByCommentsAsync';
        args = [
            {
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    } else {
        call_name = 'getDiscussionsByActiveAsync';
        args = [
            {
                tag: category,
                limit: constants.FETCH_DATA_BATCH_SIZE,
                start_author: author,
                start_permlink: permlink,
            },
        ];
    }
    yield put(appActions.fetchDataBegin());
    try {
        const data = yield call([api, api[call_name]], ...args);
        yield put(
            globalActions.receiveData({
                data,
                order,
                category,
                author,
                permlink,
                accountname,
            })
        );
    } catch (error) {
        console.error('~~ Saga fetchData error ~~>', call_name, args, error);
        yield put(appActions.steemApiError(error.message));
    }
    yield put(appActions.fetchDataEnd());
}

// export function* watchMetaRequests() {
//     yield* takeLatest('global/REQUEST_META', fetchMeta);
// }
export function* fetchMeta({ payload: { id, link } }) {
    try {
        const metaArray = yield call(
            () =>
                new Promise((resolve, reject) => {
                    function reqListener() {
                        const resp = JSON.parse(this.responseText);
                        if (resp.error) {
                            reject(resp.error);
                            return;
                        }
                        resolve(resp);
                    }
                    const oReq = new XMLHttpRequest();
                    oReq.addEventListener('load', reqListener);
                    oReq.open('GET', '/http_metadata/' + link);
                    oReq.send();
                })
        );
        const { title, metaTags } = metaArray;
        let meta = { title };
        for (let i = 0; i < metaTags.length; i++) {
            const [name, content] = metaTags[i];
            meta[name] = content;
        }
        // http://postimg.org/image/kbefrpbe9/
        meta = {
            link,
            card: meta['twitter:card'],
            site: meta['twitter:site'], // @username tribbute
            title: meta['twitter:title'],
            description: meta['twitter:description'],
            image: meta['twitter:image'],
            alt: meta['twitter:alt'],
        };
        if (!meta.image) {
            meta.image = meta['twitter:image:src'];
        }
        yield put(globalActions.receiveMeta({ id, meta }));
    } catch (error) {
        yield put(globalActions.receiveMeta({ id, meta: { error } }));
    }
}

/**
    @arg {string} id unique key for result global['fetchJson_' + id]
    @arg {string} url
    @arg {object} body (for JSON.stringify)
*/
function* fetchJson({
    payload: { id, url, body, successCallback, skipLoading = false },
}) {
    try {
        const payload = {
            method: body ? 'POST' : 'GET',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: body ? JSON.stringify(body) : undefined,
        };
        let result = yield skipLoading
            ? fetch(url, payload)
            : call(fetch, url, payload);
        result = yield result.json();
        if (successCallback) result = successCallback(result);
        yield put(globalActions.fetchJsonResult({ id, result }));
    } catch (error) {
        console.error('fetchJson', error);
        yield put(globalActions.fetchJsonResult({ id, error }));
    }
}

// Action creators
export const actions = {
    requestData: payload => ({
        type: REQUEST_DATA,
        payload,
    }),

    getContent: payload => ({
        type: GET_CONTENT,
        payload,
    }),

    fetchState: payload => ({
        type: FETCH_STATE,
        payload,
    }),
};
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import TeamRoute from './TeamRoute';
import Can from '../components/Can';
import CheckContext from '../CheckContext';
import { teamSubdomain } from '../helpers';

class TeamMenu extends Component {
  render() {
    const { team } = this.props;
    const history = new CheckContext(this).getContextStore().history;

    return (
      <Can permissions={team.permissions} permission="update Team">

Manage team

      </Can>
    );
  }
}

TeamMenu.contextTypes = {
  store: React.PropTypes.object,
};

const TeamMenuContainer = Relay.createContainer(TeamMenu, {
  fragments: {
    team: () => Relay.QL`
      fragment on Team {
        id,
        dbid,
        name,
        permissions,
      }
    `,
  },
});

class TeamMenuRelay extends Component {
  render() {
    if (teamSubdomain()) {
      const route = new TeamRoute({ teamId: '' });
      return (<Relay.RootContainer Component={TeamMenuContainer} route={route} />);
    } else {
      return null;
    }
  }
}

export default TeamMenuRelay;
<commit_msg>Clear menu overlay before navigating to menu item<commit_after>import React, { Component, PropTypes } from 'react';
import Relay from 'react-relay';
import TeamRoute from './TeamRoute';
import Can from '../components/Can';
import CheckContext from '../CheckContext';
import { teamSubdomain } from '../helpers';

class TeamMenu extends Component {
  handleClick () {
    const overlay = document.querySelector('.header-actions__menu-overlay--active')
    if (overlay) {
      overlay.click(); // TODO: better way to clear overlay e.g. passing fn from HeaderActions
    }

    const history = new CheckContext(this).getContextStore().history;
    history.push('/members');
  }

  render() {
    const { team } = this.props;

    return (
      <Can permissions={team.permissions} permission="update Team">

Manage team

      </Can>
    );
  }
}

TeamMenu.contextTypes = {
  store: React.PropTypes.object,
};

const TeamMenuContainer = Relay.createContainer(TeamMenu, {
  fragments: {
    team: () => Relay.QL`
      fragment on Team {
        id,
        dbid,
        name,
        permissions,
      }
    `,
  },
});

class TeamMenuRelay extends Component {
  render() {
    if (teamSubdomain()) {
      const route = new TeamRoute({ teamId: '' });
      return (<Relay.RootContainer Component={TeamMenuContainer} route={route} />);
    } else {
      return null;
    }
  }
}

export default TeamMenuRelay;
<|endoftext|>


<commit_before>/**
 * This file is part of DrupalCon Mobile.
 *
 * DrupalCon Mobile is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DrupalCon Mobile is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with DrupalCon Mobile.  If not, see <http://www.gnu.org/licenses/>.
 */

(function() {

  DrupalCon.ui.createSessionDetailWindow = function(settings) {
    Drupal.setDefaults(settings, {
      title: 'title here',
      nid: '',
      tabGroup: undefined
    });
    var commonPadding = 15;
    var sessionDetailWindow = Titanium.UI.createWindow({
      id: 'sessionDetailWindow',
      title: settings.title,
      backgroundColor: '#FFF',
      barColor: '#414444',
      tabGroup: settings.tabGroup
    });

    // Build session data
    //Ti.API.debug(settings.nid);
    var sessionData = Drupal.entity.db('main', 'node').load(settings.nid);

    // Build the page:
    var tvData = [];
    var blueBg = '#FFF';

    // Structure
    var tv = Ti.UI.createTableView({
      textAlign: 'left',
      layout:'vertical'
    });
    var headerRow = Ti.UI.createTableViewRow({
      height: 'auto',
      backgroundColor: blueBg,
      left: 0,
      top: -5,
      bottom: 10,
      layout: 'vertical',
      className: 'headerRow',
      backgroundImage:'images/sessionbckgd@2x.png',
      backgroundPosition:'bottom left'
    });

    var bodyRow = Ti.UI.createTableViewRow({
      hasChild: false,
      height: 'auto',
      backgroundColor: blueBg,
      left: 0,
      top: -5,
      bottom: 10,
      layout: 'vertical',
      className: 'bodyRow'
    });

    if (sessionData.title) {
      var titleLabel = Ti.UI.createLabel({
        text: cleanSpecialChars(sessionData.title),
        font: {fontSize: 28, fontWeight: 'bold'},
        textAlign: 'left',
        color: '#000',
        left: commonPadding,
        top: 18,
        bottom: 7,
        right: commonPadding,
        height: 'auto'
      });
      headerRow.add(titleLabel);
    }
    // Some sessions have multiple presenters
    if (sessionData.instructors) {
      var presenterName = Ti.UI.createLabel({
        text: sessionData.instructors, //cleanSpecialChars(sessionData.instructors.map(DrupalCon.util.getPresenterName).join(', ')),
        font: {fontSize:18, fontWeight:'normal'},
        color: '#000',
        left: commonPadding,
        top: 'auto',
        bottom: 5,
        right: commonPadding,
        height: 'auto'
      });
      headerRow.add(presenterName);
    }

    if (sessionData.start_date) {
      //var startDate = parseISO8601(sessionData.start_date + ':00');
      var startDate = sessionData.start_date;
      var datetime = Ti.UI.createLabel({
        text: cleanDate(new Date(startDate)) + ', ' + cleanTime(sessionData.start_date),
        font: {fontSize: 18, fontWeight: 'normal'},
        textAlign: 'left',
        color: '#000',
        left: commonPadding,
        top: 'auto',
        bottom: 5,
        right: 'auto',
        height: 'auto'
      });
      headerRow.add(datetime);
    }

    // Don't show a room for Lunch and Break, since what's on the web site is
    // actually completely wrong. It's hacked in for the site display, but
    // wrong for the mobile app.  We do want to show rooms for the keynotes,
    // however, which is why we can't jus exclude schedule_items.
    var skipRoom;
    if (sessionData.title === 'Lunch' || sessionData.title === 'Break' || sessionData.title.indexOf('Party') !== -1) {
      skipRoom = true;
    }

    if (sessionData.room && !skipRoom) {
      var room = Ti.UI.createLabel({
        text: sessionData.room, //sessionData.room.map(cleanSpecialChars).join(', '),
        font: {fontSize: 18, fontWeight: 'normal'},
        textAlign: 'left',
        color: '#000',
        left: commonPadding,
        top: 'auto',
        bottom: 12,
        right: commonPadding,
        height: 'auto'
      });
      headerRow.add(room);
    }

    if (sessionData.body) {
      var body = Ti.UI.createLabel({
        text: cleanSpecialChars(sessionData.body.replace('\n','\n\n')),
        backgroundColor:'#fff',
        textAlign:'left',
        color:'#000',
        left: commonPadding,
        top: 15,
        bottom: 15,
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(body);
    }

    if (sessionData.core_problem) {
      var problemTitle = Ti.UI.createLabel({
        text:"Problem:",
        backgroundColor:'#fff',
        textAlign:'left',
        font:{fontSize:18, fontWeight:'bold'},
        color:'#000',
        left: commonPadding,
        top: 10,
        bottom: 'auto',
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(problemTitle);

      var coreProblem = Ti.UI.createLabel({
        text: cleanSpecialChars(sessionData.core_problem.replace('\n','\n\n')),
        backgroundColor:'#fff',
        textAlign:'left',
        color:'#000',
        left: commonPadding,
        top: 5,
        bottom: 10,
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(coreProblem);
    }

    if (sessionData.core_solution) {
      var solutionTitle = Ti.UI.createLabel({
        text:"Solution:",
        backgroundColor:'#fff',
        textAlign:'left',
        font:{fontSize:18, fontWeight:'bold'},
        color:'#000',
        left: commonPadding,
        top: 10,
        bottom: 'auto',
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(solutionTitle);

      var coreSolution = Ti.UI.createLabel({
        text: cleanSpecialChars(sessionData.core_solution.replace('\n','\n\n')),
        backgroundColor:'#fff',
        textAlign:'left',
        color:'#000',
        left: commonPadding,
        top: 5,
        bottom: 10,
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(coreSolution);
    }

    tvData.push(headerRow);

    if (sessionData.type === 'session') {
      var feedbackTitle = Ti.UI.createLabel({
        text:"Rate this session",
        backgroundColor:'#3782a8',
        textAlign:'left',
        font:{fontSize:18, fontWeight:'bold'},
        color:'#fff',
        left: commonPadding,
        right: commonPadding,
        height: 50
      });

      var feedbackRow = Ti.UI.createTableViewRow({
        hasChild: true,
        layout:'vertical',
        height: 50,
        className: 'feedbackRow',
        backgroundColor:'#3782A9'
      });
      feedbackRow.add(feedbackTitle);

      feedbackRow.addEventListener('click', function(e) {
        var currentTab = (Ti.Platform.name == 'android') ? currentTab = Titanium.UI.currentTab : sessionDetailWindow.tabGroup.activeTab;
        currentTab.open(DrupalCon.ui.createFeedbackWindow({
          title: settings.title,
          address: 'http://chicago2011.drupal.org/node/add/eval/' + settings.nid,
          //address: 'http://google.com',
          tabGroup: currentTab
        }), {animated:true});
      });

      tvData.push(feedbackRow);
    }

    tvData.push(bodyRow);

    if (sessionData.audience) {
      var audienceRow = Ti.UI.createTableViewRow({height: 'auto', className: 'audienceRow', borderColor: '#fff'});

      var textViewBottom = Ti.UI.createView({
        height: 'auto',
        layout: 'vertical',
        backgroundColor: '#fff',
        textAlign: 'left',
        color: '#000',
        left: commonPadding,
        right: commonPadding
      });

      var audienceTitle = Ti.UI.createLabel({
        text:"Intended Audience",
        backgroundColor:'#fff',
        textAlign:'left',
        font:{fontSize:18, fontWeight:'bold'},
        color:'#000',
        left: 0,
        top: 20,
        bottom: 0,
        right: commonPadding,
        height: 'auto'
      });
      textViewBottom.add(audienceTitle);

      var audience = Ti.UI.createLabel({
        text:sessionData.audience.replace('\n','\n\n'),
        backgroundColor:'#fff',
        textAlign:'left',
        color:'#000',
        height:'auto',
        width:'auto',
        left:0,
        right:0,
        top:10,
        bottom:15
      });

      textViewBottom.add(audience);
      audienceRow.add(textViewBottom);
      tvData.push(audienceRow);
    }

    if (sessionData.instructors && sessionData.instructors.length) {
      // Get the presenter information.
      var presenterData = Drupal.entity.db('main', 'user').loadByField('name', sessionData.instructors);

      for (var j in presenterData) {
        tvData.push(renderPresenter(presenterData[j]));
      }
    }

    tv.addEventListener('click', function(e) {
      if (e.source.presenter != undefined){
        var fullName = e.source.presenter.full_name || '';
        var currentTab = (Ti.Platform.name == 'android') ? Titanium.UI.currentTab : sessionDetailWindow.tabGroup.activeTab;
        currentTab.open(DrupalCon.ui.createPresenterDetailWindow({
          title: fullName,
          uid: e.source.presenter.uid,
          tabGroup: currentTab
        }), {animated:true});
      }
    });
    tv.setData(tvData);
    sessionDetailWindow.add(tv);

    return sessionDetailWindow;
  };

  function renderPresenter(presenter) {

    var userPict = avatarPath(presenter.uid);
	//var userPict = presenter.picture;

    var av = Ti.UI.createImageView({
      image:userPict,
      left:0,
      top:0,
      height:80,
      width:80,
      defaultImage:'images/userpict-large.png',
      backgroundColor: '#000'
    });

    var presRow = Ti.UI.createTableViewRow({
      presenter: presenter,
      height: 80,
      className: 'presenterRow',
      borderColor: '#fff',
      hasChild: true,
      backgroundColor: '#C4E2EF',
      layout:'vertical'
    });
    presRow.add(av);
    var presenterFullName2 = Ti.UI.createLabel({
      presenter: presenter,
      text: cleanSpecialChars(presenter.full_name),
      font: {fontSize:18, fontWeight:'bold'},
      left: 90,
      top: -70,
      height: 'auto',
      color: '#000'
    });
    dpm(presenter.full_name);
    var presenterName2 = Ti.UI.createLabel({
      presenter: presenter,
      text: presenter.name,
      font:{fontSize:14, fontWeight:'normal'},
      left: 90,
      top: (presenter.full_name != null) ? 5 : 0,
      height: 'auto',
      color: "#04679C"
    });

    presRow.add(presenterFullName2);
    presRow.add(presenterName2);

    return presRow;
  }

})();

<commit_msg>fixed date formating<commit_after>/**
 * This file is part of DrupalCon Mobile.
 *
 * DrupalCon Mobile is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DrupalCon Mobile is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with DrupalCon Mobile.  If not, see <http://www.gnu.org/licenses/>.
 */

(function() {

  DrupalCon.ui.createSessionDetailWindow = function(settings) {
    Drupal.setDefaults(settings, {
      title: 'title here',
      nid: '',
      tabGroup: undefined
    });
    var commonPadding = 15;
    var sessionDetailWindow = Titanium.UI.createWindow({
      id: 'sessionDetailWindow',
      title: settings.title,
      backgroundColor: '#FFF',
      barColor: '#414444',
      tabGroup: settings.tabGroup
    });

    // Build session data
    //Ti.API.debug(settings.nid);
    var sessionData = Drupal.entity.db('main', 'node').load(settings.nid);

    // Build the page:
    var tvData = [];
    var blueBg = '#FFF';

    // Structure
    var tv = Ti.UI.createTableView({
      textAlign: 'left',
      layout:'vertical'
    });
    var headerRow = Ti.UI.createTableViewRow({
      height: 'auto',
      backgroundColor: blueBg,
      left: 0,
      top: -5,
      bottom: 10,
      layout: 'vertical',
      className: 'headerRow',
      backgroundImage:'images/sessionbckgd@2x.png',
      backgroundPosition:'bottom left'
    });

    var bodyRow = Ti.UI.createTableViewRow({
      hasChild: false,
      height: 'auto',
      backgroundColor: blueBg,
      left: 0,
      top: -5,
      bottom: 10,
      layout: 'vertical',
      className: 'bodyRow'
    });

    if (sessionData.title) {
      var titleLabel = Ti.UI.createLabel({
        text: cleanSpecialChars(sessionData.title),
        font: {fontSize: 28, fontWeight: 'bold'},
        textAlign: 'left',
        color: '#000',
        left: commonPadding,
        top: 18,
        bottom: 7,
        right: commonPadding,
        height: 'auto'
      });
      headerRow.add(titleLabel);
    }
    // Some sessions have multiple presenters
    if (sessionData.instructors) {
      var presenterName = Ti.UI.createLabel({
        text: sessionData.instructors, //cleanSpecialChars(sessionData.instructors.map(DrupalCon.util.getPresenterName).join(', ')),
        font: {fontSize:18, fontWeight:'normal'},
        color: '#000',
        left: commonPadding,
        top: 'auto',
        bottom: 5,
        right: commonPadding,
        height: 'auto'
      });
      headerRow.add(presenterName);
    }

    if (sessionData.start_date) {
      //var startDate = parseISO8601(sessionData.start_date + ':00');
      var matches = /^(\d{4})\-(\d{2})\-(\d{2})/.exec(sessionData.start_date);
      Ti.API.debug(matches);
      var startDate = new Date(matches[1], matches[2]-1, matches[3]);
      Ti.API.debug(startDate);
      var datetime = Ti.UI.createLabel({
        text: cleanDate(startDate) + ', ' + cleanTime(sessionData.start_date),
        font: {fontSize: 18, fontWeight: 'normal'},
        textAlign: 'left',
        color: '#000',
        left: commonPadding,
        top: 'auto',
        bottom: 5,
        right: 'auto',
        height: 'auto'
      });
      headerRow.add(datetime);
    }

    // Don't show a room for Lunch and Break, since what's on the web site is
    // actually completely wrong. It's hacked in for the site display, but
    // wrong for the mobile app.  We do want to show rooms for the keynotes,
    // however, which is why we can't jus exclude schedule_items.
    var skipRoom;
    if (sessionData.title === 'Lunch' || sessionData.title === 'Break' || sessionData.title.indexOf('Party') !== -1) {
      skipRoom = true;
    }

    if (sessionData.room && !skipRoom) {
      var room = Ti.UI.createLabel({
        text: sessionData.room, //sessionData.room.map(cleanSpecialChars).join(', '),
        font: {fontSize: 18, fontWeight: 'normal'},
        textAlign: 'left',
        color: '#000',
        left: commonPadding,
        top: 'auto',
        bottom: 12,
        right: commonPadding,
        height: 'auto'
      });
      headerRow.add(room);
    }

    if (sessionData.body) {
      var body = Ti.UI.createLabel({
        text: cleanSpecialChars(sessionData.body.replace('\n','\n\n')),
        backgroundColor:'#fff',
        textAlign:'left',
        color:'#000',
        left: commonPadding,
        top: 15,
        bottom: 15,
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(body);
    }

    if (sessionData.core_problem) {
      var problemTitle = Ti.UI.createLabel({
        text:"Problem:",
        backgroundColor:'#fff',
        textAlign:'left',
        font:{fontSize:18, fontWeight:'bold'},
        color:'#000',
        left: commonPadding,
        top: 10,
        bottom: 'auto',
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(problemTitle);

      var coreProblem = Ti.UI.createLabel({
        text: cleanSpecialChars(sessionData.core_problem.replace('\n','\n\n')),
        backgroundColor:'#fff',
        textAlign:'left',
        color:'#000',
        left: commonPadding,
        top: 5,
        bottom: 10,
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(coreProblem);
    }

    if (sessionData.core_solution) {
      var solutionTitle = Ti.UI.createLabel({
        text:"Solution:",
        backgroundColor:'#fff',
        textAlign:'left',
        font:{fontSize:18, fontWeight:'bold'},
        color:'#000',
        left: commonPadding,
        top: 10,
        bottom: 'auto',
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(solutionTitle);

      var coreSolution = Ti.UI.createLabel({
        text: cleanSpecialChars(sessionData.core_solution.replace('\n','\n\n')),
        backgroundColor:'#fff',
        textAlign:'left',
        color:'#000',
        left: commonPadding,
        top: 5,
        bottom: 10,
        right: commonPadding,
        height: 'auto'
      });
      bodyRow.add(coreSolution);
    }

    tvData.push(headerRow);

    if (sessionData.type === 'session') {
      var feedbackTitle = Ti.UI.createLabel({
        text:"Rate this session",
        backgroundColor:'#3782a8',
        textAlign:'left',
        font:{fontSize:18, fontWeight:'bold'},
        color:'#fff',
        left: commonPadding,
        right: commonPadding,
        height: 50
      });

      var feedbackRow = Ti.UI.createTableViewRow({
        hasChild: true,
        layout:'vertical',
        height: 50,
        className: 'feedbackRow',
        backgroundColor:'#3782A9'
      });
      feedbackRow.add(feedbackTitle);

      feedbackRow.addEventListener('click', function(e) {
        var currentTab = (Ti.Platform.name == 'android') ? currentTab = Titanium.UI.currentTab : sessionDetailWindow.tabGroup.activeTab;
        currentTab.open(DrupalCon.ui.createFeedbackWindow({
          title: settings.title,
          address: 'http://chicago2011.drupal.org/node/add/eval/' + settings.nid,
          //address: 'http://google.com',
          tabGroup: currentTab
        }), {animated:true});
      });

      tvData.push(feedbackRow);
    }

    tvData.push(bodyRow);

    if (sessionData.audience) {
      var audienceRow = Ti.UI.createTableViewRow({height: 'auto', className: 'audienceRow', borderColor: '#fff'});

      var textViewBottom = Ti.UI.createView({
        height: 'auto',
        layout: 'vertical',
        backgroundColor: '#fff',
        textAlign: 'left',
        color: '#000',
        left: commonPadding,
        right: commonPadding
      });

      var audienceTitle = Ti.UI.createLabel({
        text:"Intended Audience",
        backgroundColor:'#fff',
        textAlign:'left',
        font:{fontSize:18, fontWeight:'bold'},
        color:'#000',
        left: 0,
        top: 20,
        bottom: 0,
        right: commonPadding,
        height: 'auto'
      });
      textViewBottom.add(audienceTitle);

      var audience = Ti.UI.createLabel({
        text:sessionData.audience.replace('\n','\n\n'),
        backgroundColor:'#fff',
        textAlign:'left',
        color:'#000',
        height:'auto',
        width:'auto',
        left:0,
        right:0,
        top:10,
        bottom:15
      });

      textViewBottom.add(audience);
      audienceRow.add(textViewBottom);
      tvData.push(audienceRow);
    }

    if (sessionData.instructors && sessionData.instructors.length) {
      // Get the presenter information.
      var presenterData = Drupal.entity.db('main', 'user').loadByField('name', sessionData.instructors);

      for (var j in presenterData) {
        tvData.push(renderPresenter(presenterData[j]));
      }
    }

    tv.addEventListener('click', function(e) {
      if (e.source.presenter != undefined){
        var fullName = e.source.presenter.full_name || '';
        var currentTab = (Ti.Platform.name == 'android') ? Titanium.UI.currentTab : sessionDetailWindow.tabGroup.activeTab;
        currentTab.open(DrupalCon.ui.createPresenterDetailWindow({
          title: fullName,
          uid: e.source.presenter.uid,
          tabGroup: currentTab
        }), {animated:true});
      }
    });
    tv.setData(tvData);
    sessionDetailWindow.add(tv);

    return sessionDetailWindow;
  };

  function renderPresenter(presenter) {

    var userPict = avatarPath(presenter.uid);
	//var userPict = presenter.picture;

    var av = Ti.UI.createImageView({
      image:userPict,
      left:0,
      top:0,
      height:80,
      width:80,
      defaultImage:'images/userpict-large.png',
      backgroundColor: '#000'
    });

    var presRow = Ti.UI.createTableViewRow({
      presenter: presenter,
      height: 80,
      className: 'presenterRow',
      borderColor: '#fff',
      hasChild: true,
      backgroundColor: '#C4E2EF',
      layout:'vertical'
    });
    presRow.add(av);
    var presenterFullName2 = Ti.UI.createLabel({
      presenter: presenter,
      text: cleanSpecialChars(presenter.full_name),
      font: {fontSize:18, fontWeight:'bold'},
      left: 90,
      top: -70,
      height: 'auto',
      color: '#000'
    });
    dpm(presenter.full_name);
    var presenterName2 = Ti.UI.createLabel({
      presenter: presenter,
      text: presenter.name,
      font:{fontSize:14, fontWeight:'normal'},
      left: 90,
      top: (presenter.full_name != null) ? 5 : 0,
      height: 'auto',
      color: "#04679C"
    });

    presRow.add(presenterFullName2);
    presRow.add(presenterName2);

    return presRow;
  }

})();

<|endoftext|>


<commit_before>import Mn from 'backbone.marionette';
import _ from 'underscore';

export default class DrawerToggle extends Mn.View {
    template() {
        return _.noop;
    }
    el() {
        return '.drawer-toggle';
    }
    events() {
        return {
            'click': '_onClick',
        }
    }
    /**
     * @param {Event} e
     * @private
     */
    _onClick(e) {
        const id = this.$el.attr('data-drawer-id');

        if (_.isString(id) && id.length > 0) {
            const drawer = document.getElementById(id);

            if (drawer) {
                drawer.toggle();
            }
        }
    }
}
<commit_msg>listener optimize<commit_after>import Mn from 'backbone.marionette';
import _ from 'underscore';

export default class DrawerToggle extends Mn.View {
    template() {
        return _.noop;
    }
    el() {
        return '.drawer-toggle';
    }
    events() {
        return {
            'click': '_onClick',
        }
    }
    /**
     * @param {Event} e
     * @private
     */
    _onClick(e) {
        const id = e.target.getAttribute('data-drawer-id');

        if (_.isString(id) && id.length > 0) {
            const drawer = document.getElementById(id);

            if (drawer) {
                drawer.toggle();
            }
        }
    }
}
<|endoftext|>


<commit_before>import d3 from 'd3';
import fc from 'd3fc';
import util from '../util/util';

export default function(width) {

    var dispatch = d3.dispatch('zoom');

    var zoomBehavior = d3.behavior.zoom();
    var scale;

    var allowPan = true;
    var allowZoom = true;
    var trackingLatest = true;

    function controlPan(zoomExtent) {
        // Don't pan off sides
        if (zoomExtent[0] >= 0) {
            return -zoomExtent[0];
        } else if (zoomExtent[1] <= 0) {
            return -zoomExtent[1];
        }
        return 0;
    }

    function controlZoom(zoomExtent) {
        // If zooming, and about to pan off screen, do nothing
        return (zoomExtent[0] > 0 && zoomExtent[1] < 0);
    }

    function translateXZoom(translation) {
        var tx = zoomBehavior.translate()[0];

        if (trackingLatest && tx < 0) {
            zoomBehavior.translate([0, 0]);
        } else {
            tx += translation;
            zoomBehavior.translate([tx, 0]);
        }
    }

    function resetBehaviour() {
        zoomBehavior.translate([0, 0]);
        zoomBehavior.scale(1);
    }

    function zoom(selection) {

        var xExtent = fc.util.extent()
          .fields('date')(selection.datum().data);

        zoomBehavior.x(scale)
          .on('zoom', function() {
              var min = scale(xExtent[0]);
              var max = scale(xExtent[1]);

              var maxDomainViewed = controlZoom([min, max - width]);
              var panningRestriction = controlPan([min, max - width]);
              translateXZoom(panningRestriction);

              var panned = (zoomBehavior.scale() === 1);
              var zoomed = (zoomBehavior.scale() !== 1);

              if ((panned && allowPan) || (zoomed && allowZoom)) {
                  var domain = scale.domain();
                  if (maxDomainViewed) {
                      domain = xExtent;
                  } else if (zoomed && trackingLatest) {
                      domain = util.domain.moveToLatest(domain, selection.datum().data);
                  }

                  if (domain[0].getTime() !== domain[1].getTime()) {
                      // console.log(domain);
                      dispatch.zoom(domain);
                  } else {
                      // Ensure the user can't zoom-in infinitely, causing the chart to fail to render
                      // #168, #411
                      resetBehaviour();
                  }
              } else {
                  resetBehaviour();
              }
          });

        selection.call(zoomBehavior);
    }

    zoom.allowPan = function(x) {
        if (!arguments.length) {
            return allowPan;
        }
        allowPan = x;
        return zoom;
    };

    zoom.allowZoom = function(x) {
        if (!arguments.length) {
            return allowZoom;
        }
        allowZoom = x;
        return zoom;
    };

    zoom.trackingLatest = function(x) {
        if (!arguments.length) {
            return trackingLatest;
        }
        trackingLatest = x;
        return zoom;
    };

    zoom.scale = function(x) {
        if (!arguments.length) {
            return scale;
        }
        scale = x;
        return zoom;
    };

    d3.rebind(zoom, dispatch, 'on');

    return zoom;
}
<commit_msg>Fix zoom pan extent limits for skip weekends<commit_after>import d3 from 'd3';
import fc from 'd3fc';
import util from '../util/util';

export default function(width) {

    var dispatch = d3.dispatch('zoom');

    var zoomBehavior = d3.behavior.zoom();
    var scale;

    var allowPan = true;
    var allowZoom = true;
    var trackingLatest = true;

    function controlZoom(zoomExtent) {
        // If zooming, and about to pan off screen, do nothing
        return (zoomExtent[0] > 0 && zoomExtent[1] < 0);
    }

    function resetBehaviour() {
        zoomBehavior.translate([0, 0]);
        zoomBehavior.scale(1);
    }

    function clamp(value, min, max) {
        return Math.min(Math.max(value, min), max);
    }

    function zoom(selection) {

        var xExtent = fc.util.extent()
          .fields('date')(selection.datum().data);

        var min = scale(xExtent[0]);
        var max = scale(xExtent[1]);
        var zoomPixelExtent = [min, max - width];

        zoomBehavior.x(scale)
          .on('zoom', function() {
              var t = d3.event.translate,
                  tx = t[0];

              var maxDomainViewed = controlZoom(zoomPixelExtent);

              tx = clamp(tx, -zoomPixelExtent[1], -zoomPixelExtent[0]);
              zoomBehavior.translate([tx, 0]);

              var panned = (zoomBehavior.scale() === 1);
              var zoomed = (zoomBehavior.scale() !== 1);

              if ((panned && allowPan) || (zoomed && allowZoom)) {
                  var domain = scale.domain();
                  if (maxDomainViewed) {
                      domain = xExtent;
                  } else if (zoomed && trackingLatest) {
                      domain = util.domain.moveToLatest(domain, selection.datum().data);
                  }

                  if (domain[0].getTime() !== domain[1].getTime()) {
                      dispatch.zoom(domain);
                  } else {
                      // Ensure the user can't zoom-in infinitely, causing the chart to fail to render
                      // #168, #411
                      resetBehaviour();
                  }
              } else {
                  resetBehaviour();
              }
          });

        selection.call(zoomBehavior);
    }

    zoom.allowPan = function(x) {
        if (!arguments.length) {
            return allowPan;
        }
        allowPan = x;
        return zoom;
    };

    zoom.allowZoom = function(x) {
        if (!arguments.length) {
            return allowZoom;
        }
        allowZoom = x;
        return zoom;
    };

    zoom.trackingLatest = function(x) {
        if (!arguments.length) {
            return trackingLatest;
        }
        trackingLatest = x;
        return zoom;
    };

    zoom.scale = function(x) {
        if (!arguments.length) {
            return scale;
        }
        scale = x;
        return zoom;
    };

    d3.rebind(zoom, dispatch, 'on');

    return zoom;
}
<|endoftext|>


<commit_before>import d3 from 'd3';
import fc from 'd3fc';
import util from '../util/util';

export default function(width) {

    var dispatch = d3.dispatch('zoom');

    var zoomBehavior = d3.behavior.zoom();
    var scale;

    var allowPan = true;
    var allowZoom = true;
    var trackingLatest = true;

    function controlZoom(zoomExtent) {
        // If zooming, and about to pan off screen, do nothing
        return (zoomExtent[0] > 0 && zoomExtent[1] < 0);
    }

    function resetBehaviour() {
        zoomBehavior.translate([0, 0]);
        zoomBehavior.scale(1);
    }

    function clamp(value, min, max) {
        return Math.min(Math.max(value, min), max);
    }

    function clampDomain(domain, data, totalXExtent) {
        var clampedDomain = domain;

        if (scale(data[0].date) > 0) {
            clampedDomain[1] = scale.invert(scale(domain[1]) + scale(data[0].date));
        }

        clampedDomain[0] = d3.max([totalXExtent[0], clampedDomain[0]]);
        clampedDomain[1] = d3.min([totalXExtent[1], clampedDomain[1]]);

        return clampedDomain;
    }

    function zoom(selection) {

        var xExtent = fc.util.extent()
          .fields('date')(selection.datum().data);

        var min = scale(xExtent[0]);
        var max = scale(xExtent[1]);
        var zoomPixelExtent = [min, max - width];

        zoomBehavior.x(scale)
          .on('zoom', function() {
              var t = d3.event.translate,
                  tx = t[0];

              var maxDomainViewed = controlZoom(zoomPixelExtent);

              tx = clamp(tx, -zoomPixelExtent[1], -zoomPixelExtent[0]);
              zoomBehavior.translate([tx, 0]);

              var panned = (zoomBehavior.scale() === 1);
              var zoomed = (zoomBehavior.scale() !== 1);

              if ((panned && allowPan) || (zoomed && allowZoom)) {
                  var domain = scale.domain();
                  if (maxDomainViewed) {
                      domain = xExtent;
                  } else if (zoomed && trackingLatest) {
                      domain = util.domain.moveToLatest(
                          selection.datum().discontinuityProvider,
                          domain,
                          selection.datum().data);
                  }

                  domain = clampDomain(domain, selection.datum().data, xExtent);

                  if (domain[0].getTime() !== domain[1].getTime()) {
                      dispatch.zoom(domain);
                  } else {
                      // Ensure the user can't zoom-in infinitely, causing the chart to fail to render
                      // #168, #411
                      resetBehaviour();
                  }
              } else {
                  resetBehaviour();
              }
          });

        selection.call(zoomBehavior);
    }

    zoom.allowPan = function(x) {
        if (!arguments.length) {
            return allowPan;
        }
        allowPan = x;
        return zoom;
    };

    zoom.allowZoom = function(x) {
        if (!arguments.length) {
            return allowZoom;
        }
        allowZoom = x;
        return zoom;
    };

    zoom.trackingLatest = function(x) {
        if (!arguments.length) {
            return trackingLatest;
        }
        trackingLatest = x;
        return zoom;
    };

    zoom.scale = function(x) {
        if (!arguments.length) {
            return scale;
        }
        scale = x;
        return zoom;
    };

    d3.rebind(zoom, dispatch, 'on');

    return zoom;
}
<commit_msg>Disable double click zooming behaviour<commit_after>import d3 from 'd3';
import fc from 'd3fc';
import util from '../util/util';

export default function(width) {

    var dispatch = d3.dispatch('zoom');

    var zoomBehavior = d3.behavior.zoom();
    var scale;

    var allowPan = true;
    var allowZoom = true;
    var trackingLatest = true;

    function controlZoom(zoomExtent) {
        // If zooming, and about to pan off screen, do nothing
        return (zoomExtent[0] > 0 && zoomExtent[1] < 0);
    }

    function resetBehaviour() {
        zoomBehavior.translate([0, 0]);
        zoomBehavior.scale(1);
    }

    function clamp(value, min, max) {
        return Math.min(Math.max(value, min), max);
    }

    function clampDomain(domain, data, totalXExtent) {
        var clampedDomain = domain;

        if (scale(data[0].date) > 0) {
            clampedDomain[1] = scale.invert(scale(domain[1]) + scale(data[0].date));
        }

        clampedDomain[0] = d3.max([totalXExtent[0], clampedDomain[0]]);
        clampedDomain[1] = d3.min([totalXExtent[1], clampedDomain[1]]);

        return clampedDomain;
    }

    function zoom(selection) {

        var xExtent = fc.util.extent()
          .fields('date')(selection.datum().data);

        var min = scale(xExtent[0]);
        var max = scale(xExtent[1]);
        var zoomPixelExtent = [min, max - width];

        zoomBehavior.x(scale)
          .on('zoom', function() {
              var t = d3.event.translate,
                  tx = t[0];

              var maxDomainViewed = controlZoom(zoomPixelExtent);

              tx = clamp(tx, -zoomPixelExtent[1], -zoomPixelExtent[0]);
              zoomBehavior.translate([tx, 0]);

              var panned = (zoomBehavior.scale() === 1);
              var zoomed = (zoomBehavior.scale() !== 1);

              if ((panned && allowPan) || (zoomed && allowZoom)) {
                  var domain = scale.domain();
                  if (maxDomainViewed) {
                      domain = xExtent;
                  } else if (zoomed && trackingLatest) {
                      domain = util.domain.moveToLatest(
                          selection.datum().discontinuityProvider,
                          domain,
                          selection.datum().data);
                  }

                  domain = clampDomain(domain, selection.datum().data, xExtent);

                  if (domain[0].getTime() !== domain[1].getTime()) {
                      dispatch.zoom(domain);
                  } else {
                      // Ensure the user can't zoom-in infinitely, causing the chart to fail to render
                      // #168, #411
                      resetBehaviour();
                  }
              } else {
                  resetBehaviour();
              }
          });

        selection.call(zoomBehavior)
            .on('dblclick.zoom', null);
    }

    zoom.allowPan = function(x) {
        if (!arguments.length) {
            return allowPan;
        }
        allowPan = x;
        return zoom;
    };

    zoom.allowZoom = function(x) {
        if (!arguments.length) {
            return allowZoom;
        }
        allowZoom = x;
        return zoom;
    };

    zoom.trackingLatest = function(x) {
        if (!arguments.length) {
            return trackingLatest;
        }
        trackingLatest = x;
        return zoom;
    };

    zoom.scale = function(x) {
        if (!arguments.length) {
            return scale;
        }
        scale = x;
        return zoom;
    };

    d3.rebind(zoom, dispatch, 'on');

    return zoom;
}
<|endoftext|>


<commit_before>import "../../polyfill";
import sourceMapSupport from "source-map-support";
import * as registerCache from "./cache";
import resolveRc from "./resolve-rc";
import extend from "lodash/object/extend";
import * as babel from "../node";
import each from "lodash/collection/each";
import * as util from  "../../util";
import fs from "fs";

sourceMapSupport.install({
  handleUncaughtExceptions: false,
  retrieveSourceMap(source) {
    var map = maps && maps[source];
    if (map) {
      return {
        url: null,
        map: map
      };
    } else {
      return null;
    }
  }
});

//

registerCache.load();
var cache = registerCache.get();

//

var transformOpts = {};
var ignoreRegex   = /node_modules/;
var onlyRegex;
var oldHandlers   = {};
var maps          = {};

var mtime = function (filename) {
  return +fs.statSync(filename).mtime;
};

var compile = function (filename) {
  var result;

  var opts = extend({}, transformOpts);
  resolveRc(filename, opts);

  var cacheKey = `${filename}:${JSON.stringify(opts)}`;

  if (cache) {
    var cached = cache[cacheKey];
    if (cached && cached.mtime === mtime(filename)) {
      result = cached;
    }
  }

  if (!result) {
    result = babel.transformFileSync(filename, extend(opts, {
      sourceMap: true,
      ast:       false
    }));
  }

  if (cache) {
    result.mtime = mtime(filename);
    cache[cacheKey] = result;
  }

  maps[filename] = result.map;

  return result.code;
};

var shouldIgnore = function (filename) {
  return (ignoreRegex && ignoreRegex.test(filename)) || (onlyRegex && !onlyRegex.test(filename));
};

var istanbulMonkey = {};

if (process.env.running_under_istanbul) { // jshint ignore:line
  // we need to monkey patch fs.readFileSync so we can hook into
  // what istanbul gets, it's extremely dirty but it's the only way
  var _readFileSync = fs.readFileSync;

  fs.readFileSync = function (filename) {
    if (istanbulMonkey[filename]) {
      delete istanbulMonkey[filename];
      var code = compile(filename);
      istanbulMonkey[filename] = true;
      return code;
    } else {
      return _readFileSync.apply(this, arguments);
    }
  };
}

var istanbulLoader = function (m, filename, old) {
  istanbulMonkey[filename] = true;
  old(m, filename);
};

var normalLoader = function (m, filename) {
  m._compile(compile(filename), filename);
};

var registerExtension = function (ext) {
  var old = oldHandlers[ext] || oldHandlers[".js"];

  var loader = normalLoader;
  if (process.env.running_under_istanbul) loader = istanbulLoader; // jshint ignore:line

  require.extensions[ext] = function (m, filename) {
    if (shouldIgnore(filename)) {
      old(m, filename);
    } else {
      loader(m, filename, old);
    }
  };
};

var hookExtensions = function (_exts) {
  each(oldHandlers, function (old, ext) {
    if (old === undefined) {
      delete require.extensions[ext];
    } else {
      require.extensions[ext] = old;
    }
  });

  oldHandlers = {};

  each(_exts, function (ext) {
    oldHandlers[ext] = require.extensions[ext];
    registerExtension(ext);
  });
};

hookExtensions(util.canCompile.EXTENSIONS);

export default function (opts = {}) {
  if (opts.only != null) onlyRegex = util.regexify(opts.only);
  if (opts.ignore != null) ignoreRegex = util.regexify(opts.ignore);

  if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));

  if (opts.cache === false) cache = null;

  delete opts.extensions;
  delete opts.ignore;
  delete opts.cache;
  delete opts.only;

  extend(transformOpts, opts);
};

//

try {
  var runtimePackage = require("babel-runtime/package");
  var version = require("../../package").version;
  if (runtimePackage.version !== version) {
    throw new ReferenceError(`The verison of babel-runtime of ${runtimePackage.runtime} that you have installed does not match the babel verison of ${version}`);
  }
} catch (err) {
  console.log(err.code);
  if (err.code !== "MODULE_NOT_FOUND") throw err;
}

<commit_msg>remove rogue console.log<commit_after>import "../../polyfill";
import sourceMapSupport from "source-map-support";
import * as registerCache from "./cache";
import resolveRc from "./resolve-rc";
import extend from "lodash/object/extend";
import * as babel from "../node";
import each from "lodash/collection/each";
import * as util from  "../../util";
import fs from "fs";

sourceMapSupport.install({
  handleUncaughtExceptions: false,
  retrieveSourceMap(source) {
    var map = maps && maps[source];
    if (map) {
      return {
        url: null,
        map: map
      };
    } else {
      return null;
    }
  }
});

//

registerCache.load();
var cache = registerCache.get();

//

var transformOpts = {};
var ignoreRegex   = /node_modules/;
var onlyRegex;
var oldHandlers   = {};
var maps          = {};

var mtime = function (filename) {
  return +fs.statSync(filename).mtime;
};

var compile = function (filename) {
  var result;

  var opts = extend({}, transformOpts);
  resolveRc(filename, opts);

  var cacheKey = `${filename}:${JSON.stringify(opts)}`;

  if (cache) {
    var cached = cache[cacheKey];
    if (cached && cached.mtime === mtime(filename)) {
      result = cached;
    }
  }

  if (!result) {
    result = babel.transformFileSync(filename, extend(opts, {
      sourceMap: true,
      ast:       false
    }));
  }

  if (cache) {
    result.mtime = mtime(filename);
    cache[cacheKey] = result;
  }

  maps[filename] = result.map;

  return result.code;
};

var shouldIgnore = function (filename) {
  return (ignoreRegex && ignoreRegex.test(filename)) || (onlyRegex && !onlyRegex.test(filename));
};

var istanbulMonkey = {};

if (process.env.running_under_istanbul) { // jshint ignore:line
  // we need to monkey patch fs.readFileSync so we can hook into
  // what istanbul gets, it's extremely dirty but it's the only way
  var _readFileSync = fs.readFileSync;

  fs.readFileSync = function (filename) {
    if (istanbulMonkey[filename]) {
      delete istanbulMonkey[filename];
      var code = compile(filename);
      istanbulMonkey[filename] = true;
      return code;
    } else {
      return _readFileSync.apply(this, arguments);
    }
  };
}

var istanbulLoader = function (m, filename, old) {
  istanbulMonkey[filename] = true;
  old(m, filename);
};

var normalLoader = function (m, filename) {
  m._compile(compile(filename), filename);
};

var registerExtension = function (ext) {
  var old = oldHandlers[ext] || oldHandlers[".js"];

  var loader = normalLoader;
  if (process.env.running_under_istanbul) loader = istanbulLoader; // jshint ignore:line

  require.extensions[ext] = function (m, filename) {
    if (shouldIgnore(filename)) {
      old(m, filename);
    } else {
      loader(m, filename, old);
    }
  };
};

var hookExtensions = function (_exts) {
  each(oldHandlers, function (old, ext) {
    if (old === undefined) {
      delete require.extensions[ext];
    } else {
      require.extensions[ext] = old;
    }
  });

  oldHandlers = {};

  each(_exts, function (ext) {
    oldHandlers[ext] = require.extensions[ext];
    registerExtension(ext);
  });
};

hookExtensions(util.canCompile.EXTENSIONS);

export default function (opts = {}) {
  if (opts.only != null) onlyRegex = util.regexify(opts.only);
  if (opts.ignore != null) ignoreRegex = util.regexify(opts.ignore);

  if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));

  if (opts.cache === false) cache = null;

  delete opts.extensions;
  delete opts.ignore;
  delete opts.cache;
  delete opts.only;

  extend(transformOpts, opts);
};

//

try {
  var runtimePackage = require("babel-runtime/package");
  var version = require("../../package").version;
  if (runtimePackage.version !== version) {
    throw new ReferenceError(`The verison of babel-runtime of ${runtimePackage.runtime} that you have installed does not match the babel verison of ${version}`);
  }
} catch (err) {
  if (err.code !== "MODULE_NOT_FOUND") throw err;
}

<|endoftext|>


<commit_before>module("css");

test("css(String|Hash)", function() {
	expect(34);

	equals( jQuery('#main').css("display"), 'block', 'Check for css property "display"');

	ok( jQuery('#nothiddendiv').is(':visible'), 'Modifying CSS display: Assert element is visible');
	jQuery('#nothiddendiv').css({display: 'none'});
	ok( !jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is hidden');
	jQuery('#nothiddendiv').css({display: 'block'});
	ok( jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is visible');

	// handle negative numbers by ignoring #1599, #4216
	jQuery('#nothiddendiv').css({ 'width': 1, 'height': 1 });

	var width = parseFloat(jQuery('#nothiddendiv').css('width')), height = parseFloat(jQuery('#nothiddendiv').css('height'));
	jQuery('#nothiddendiv').css({ width: -1, height: -1 });
	equals( parseFloat(jQuery('#nothiddendiv').css('width')), width, 'Test negative width ignored')
	equals( parseFloat(jQuery('#nothiddendiv').css('height')), height, 'Test negative height ignored')

	equals( jQuery('
').css('display'), 'none', 'Styles on disconnected nodes');

	jQuery('#floatTest').css({'float': 'right'});
	equals( jQuery('#floatTest').css('float'), 'right', 'Modified CSS float using "float": Assert float is right');
	jQuery('#floatTest').css({'font-size': '30px'});
	equals( jQuery('#floatTest').css('font-size'), '30px', 'Modified CSS font-size: Assert font-size is 30px');

	jQuery.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
		jQuery('#foo').css({opacity: n});
		equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
		jQuery('#foo').css({opacity: parseFloat(n)});
		equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
	});
	jQuery('#foo').css({opacity: ''});
	equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when set to an empty String" );

	equals( jQuery('#empty').css('opacity'), '0', "Assert opacity is accessible via filter property set in stylesheet in IE" );
	jQuery('#empty').css({ opacity: '1' });
	equals( jQuery('#empty').css('opacity'), '1', "Assert opacity is taken from style attribute when set vs stylesheet in IE with filters" );

	var div = jQuery('#nothiddendiv'), child = jQuery('#nothiddendivchild');

	equals( parseInt(div.css("fontSize")), 16, "Verify fontSize px set." );
	equals( parseInt(div.css("font-size")), 16, "Verify fontSize px set." );
	equals( parseInt(child.css("fontSize")), 16, "Verify fontSize px set." );
	equals( parseInt(child.css("font-size")), 16, "Verify fontSize px set." );

	child.css("height", "100%");
	equals( child[0].style.height, "100%", "Make sure the height is being set correctly." );

	child.attr("class", "em");
	equals( parseInt(child.css("fontSize")), 32, "Verify fontSize em set." );

	// Have to verify this as the result depends upon the browser's CSS
	// support for font-size percentages
	child.attr("class", "prct");
	var prctval = parseInt(child.css("fontSize")), checkval = 0;
	if ( prctval === 16 || prctval === 24 ) {
		checkval = prctval;
	}

	equals( prctval, checkval, "Verify fontSize % set." );

	equals( typeof child.css("width"), "string", "Make sure that a string width is returned from css('width')." );

	var old = child[0].style.height;

	// Test NaN
	child.css("height", parseFloat("zoo"));
	equals( child[0].style.height, old, "Make sure height isn't changed on NaN." );

	// Test null
	child.css("height", null);
	equals( child[0].style.height, old, "Make sure height isn't changed on null." );

	old = child[0].style.fontSize;

	// Test NaN
	child.css("font-size", parseFloat("zoo"));
	equals( child[0].style.fontSize, old, "Make sure font-size isn't changed on NaN." );

	// Test null
	child.css("font-size", null);
	equals( child[0].style.fontSize, old, "Make sure font-size isn't changed on null." );
});

test("css(String, Object)", function() {
	expect(22);

	ok( jQuery('#nothiddendiv').is(':visible'), 'Modifying CSS display: Assert element is visible');
	jQuery('#nothiddendiv').css("display", 'none');
	ok( !jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is hidden');
	jQuery('#nothiddendiv').css("display", 'block');
	ok( jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is visible');

	jQuery("#nothiddendiv").css("top", "-1em");
	ok( jQuery("#nothiddendiv").css("top"), -16, "Check negative number in EMs." );

	jQuery('#floatTest').css('float', 'left');
	equals( jQuery('#floatTest').css('float'), 'left', 'Modified CSS float using "float": Assert float is left');
	jQuery('#floatTest').css('font-size', '20px');
	equals( jQuery('#floatTest').css('font-size'), '20px', 'Modified CSS font-size: Assert font-size is 20px');

	jQuery.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
		jQuery('#foo').css('opacity', n);
		equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
		jQuery('#foo').css('opacity', parseFloat(n));
		equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
	});
	jQuery('#foo').css('opacity', '');
	equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when set to an empty String" );

	// using contents will get comments regular, text, and comment nodes
	var j = jQuery("#nonnodes").contents();
	j.css("fontSize", "1px");
	equals( j.css("fontSize"), "1px", "Check node,textnode,comment css works" );

	// opera sometimes doesn't update 'display' correctly, see #2037
	jQuery("#t2037")[0].innerHTML = jQuery("#t2037")[0].innerHTML
	equals( jQuery("#t2037 .hidden").css("display"), "none", "Make sure browser thinks it is hidden" );

	var div = jQuery("#nothiddendiv"),
		display = div.css("display"),
		ret = div.css("display", undefined);

	equals( ret, div, "Make sure setting undefined returns the original set." );
	equals( div.css("display"), display, "Make sure that the display wasn't changed." );

	// Test for Bug #5509
	var success = true;
	try {
		jQuery('#foo').css("backgroundColor", "rgba(0, 0, 0, 0.1)");
	}
	catch (e) {
		success = false;
	}
	ok( success, "Setting RGBA values does not throw Error" );
});

if(jQuery.browser.msie) {
  test("css(String, Object) for MSIE", function() {
    // for #1438, IE throws JS error when filter exists but doesn't have opacity in it
		jQuery('#foo').css("filter", "progid:DXImageTransform.Microsoft.Chroma(color='red');");
  	equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when a different filter is set in IE, #1438" );

    var filterVal = "progid:DXImageTransform.Microsoft.Alpha(opacity=30) progid:DXImageTransform.Microsoft.Blur(pixelradius=5)";
    var filterVal2 = "progid:DXImageTransform.Microsoft.Alpha(opacity=100) progid:DXImageTransform.Microsoft.Blur(pixelradius=5)";
    var filterVal3 = "progid:DXImageTransform.Microsoft.Blur(pixelradius=5)";
    jQuery('#foo').css("filter", filterVal);
    equals( jQuery('#foo').css("filter"), filterVal, "css('filter', val) works" );
    jQuery('#foo').css("opacity", 1);
    equals( jQuery('#foo').css("filter"), filterVal2, "Setting opacity in IE doesn't duplicate opacity filter" );
    equals( jQuery('#foo').css("opacity"), 1, "Setting opacity in IE with other filters works" );
    jQuery('#foo').css("filter", filterVal3).css("opacity", 1);
    ok( jQuery('#foo').css("filter").indexOf(filterVal3) !== -1, "Setting opacity in IE doesn't clobber other filters" );
  });
}

test("css(String, Function)", function() {
	expect(3);

	var sizes = ["10px", "20px", "30px"];

	jQuery("

" +
				 "

" +
				 "

")
		.appendTo("body");

	var index = 0;

	jQuery("#cssFunctionTest div").css("font-size", function() {
		var size = sizes[index];
		index++;
		return size;
	});

	index = 0;

	jQuery("#cssFunctionTest div").each(function() {
		var computedSize = jQuery(this).css("font-size")
		var expectedSize = sizes[index]
		equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
		index++;
	});

	jQuery("#cssFunctionTest").remove();
});

test("css(String, Function) with incoming value", function() {
	expect(3);

	var sizes = ["10px", "20px", "30px"];

	jQuery("

" +
				 "

" +
				 "

")
		.appendTo("body");

	var index = 0;

	jQuery("#cssFunctionTest div").css("font-size", function() {
		var size = sizes[index];
		index++;
		return size;
	});

	index = 0;

	jQuery("#cssFunctionTest div").css("font-size", function(i, computedSize) {
		var expectedSize = sizes[index]
		equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
		index++;
		return computedSize;
	});

	jQuery("#cssFunctionTest").remove();
});

test("css(Object) where values are Functions", function() {
	expect(3);

	var sizes = ["10px", "20px", "30px"];

	jQuery("

" +
				 "

" +
				 "

")
		.appendTo("body");

	var index = 0;

	jQuery("#cssFunctionTest div").css({fontSize: function() {
		var size = sizes[index];
		index++;
		return size;
	}});

	index = 0;

	jQuery("#cssFunctionTest div").each(function() {
		var computedSize = jQuery(this).css("font-size")
		var expectedSize = sizes[index]
		equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
		index++;
	});

	jQuery("#cssFunctionTest").remove();
});

test("css(Object) where values are Functions with incoming values", function() {
	expect(3);

	var sizes = ["10px", "20px", "30px"];

	jQuery("

" +
				 "

" +
				 "

")
		.appendTo("body");

	var index = 0;

	jQuery("#cssFunctionTest div").css({fontSize: function() {
		var size = sizes[index];
		index++;
		return size;
	}});

	index = 0;

	jQuery("#cssFunctionTest div").css({"font-size": function(i, computedSize) {
		var expectedSize = sizes[index]
		equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
		index++;
		return computedSize;
	}});

	jQuery("#cssFunctionTest").remove();
});

test("jQuery.css(elem, 'height') doesn't clear radio buttons (bug #1095)", function () {
	expect(4);

	var $checkedtest = jQuery("#checkedtest");
	// IE6 was clearing "checked" in jQuery.css(elem, "height");
	jQuery.css($checkedtest[0], "height");
	ok( !! jQuery(":radio:first", $checkedtest).attr("checked"), "Check first radio still checked." );
	ok( ! jQuery(":radio:last", $checkedtest).attr("checked"), "Check last radio still NOT checked." );
	ok( !! jQuery(":checkbox:first", $checkedtest).attr("checked"), "Check first checkbox still checked." );
	ok( ! jQuery(":checkbox:last", $checkedtest).attr("checked"), "Check last checkbox still NOT checked." );
});

test(":visible selector works properly on table elements (bug #4512)", function () {
	expect(1);

	jQuery('#table').html('
cell	cell
');
	equals(jQuery('#table td:visible').length, 1, "hidden cell is not perceived as visible");
});

test(":visible selector works properly on children with a hidden parent (bug #4512)", function () {
	expect(1);
	jQuery('#table').css('display', 'none').html('
cell	cell
');
	equals(jQuery('#table td:visible').length, 0, "hidden cell children not perceived as visible");
});
<commit_msg>We want to make sure that we only run the MSIE-specific filter tests if opacity is explicitly not supported.<commit_after>module("css");

test("css(String|Hash)", function() {
	expect(34);

	equals( jQuery('#main').css("display"), 'block', 'Check for css property "display"');

	ok( jQuery('#nothiddendiv').is(':visible'), 'Modifying CSS display: Assert element is visible');
	jQuery('#nothiddendiv').css({display: 'none'});
	ok( !jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is hidden');
	jQuery('#nothiddendiv').css({display: 'block'});
	ok( jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is visible');

	// handle negative numbers by ignoring #1599, #4216
	jQuery('#nothiddendiv').css({ 'width': 1, 'height': 1 });

	var width = parseFloat(jQuery('#nothiddendiv').css('width')), height = parseFloat(jQuery('#nothiddendiv').css('height'));
	jQuery('#nothiddendiv').css({ width: -1, height: -1 });
	equals( parseFloat(jQuery('#nothiddendiv').css('width')), width, 'Test negative width ignored')
	equals( parseFloat(jQuery('#nothiddendiv').css('height')), height, 'Test negative height ignored')

	equals( jQuery('
').css('display'), 'none', 'Styles on disconnected nodes');

	jQuery('#floatTest').css({'float': 'right'});
	equals( jQuery('#floatTest').css('float'), 'right', 'Modified CSS float using "float": Assert float is right');
	jQuery('#floatTest').css({'font-size': '30px'});
	equals( jQuery('#floatTest').css('font-size'), '30px', 'Modified CSS font-size: Assert font-size is 30px');

	jQuery.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
		jQuery('#foo').css({opacity: n});
		equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
		jQuery('#foo').css({opacity: parseFloat(n)});
		equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
	});
	jQuery('#foo').css({opacity: ''});
	equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when set to an empty String" );

	equals( jQuery('#empty').css('opacity'), '0', "Assert opacity is accessible via filter property set in stylesheet in IE" );
	jQuery('#empty').css({ opacity: '1' });
	equals( jQuery('#empty').css('opacity'), '1', "Assert opacity is taken from style attribute when set vs stylesheet in IE with filters" );

	var div = jQuery('#nothiddendiv'), child = jQuery('#nothiddendivchild');

	equals( parseInt(div.css("fontSize")), 16, "Verify fontSize px set." );
	equals( parseInt(div.css("font-size")), 16, "Verify fontSize px set." );
	equals( parseInt(child.css("fontSize")), 16, "Verify fontSize px set." );
	equals( parseInt(child.css("font-size")), 16, "Verify fontSize px set." );

	child.css("height", "100%");
	equals( child[0].style.height, "100%", "Make sure the height is being set correctly." );

	child.attr("class", "em");
	equals( parseInt(child.css("fontSize")), 32, "Verify fontSize em set." );

	// Have to verify this as the result depends upon the browser's CSS
	// support for font-size percentages
	child.attr("class", "prct");
	var prctval = parseInt(child.css("fontSize")), checkval = 0;
	if ( prctval === 16 || prctval === 24 ) {
		checkval = prctval;
	}

	equals( prctval, checkval, "Verify fontSize % set." );

	equals( typeof child.css("width"), "string", "Make sure that a string width is returned from css('width')." );

	var old = child[0].style.height;

	// Test NaN
	child.css("height", parseFloat("zoo"));
	equals( child[0].style.height, old, "Make sure height isn't changed on NaN." );

	// Test null
	child.css("height", null);
	equals( child[0].style.height, old, "Make sure height isn't changed on null." );

	old = child[0].style.fontSize;

	// Test NaN
	child.css("font-size", parseFloat("zoo"));
	equals( child[0].style.fontSize, old, "Make sure font-size isn't changed on NaN." );

	// Test null
	child.css("font-size", null);
	equals( child[0].style.fontSize, old, "Make sure font-size isn't changed on null." );
});

test("css(String, Object)", function() {
	expect(22);

	ok( jQuery('#nothiddendiv').is(':visible'), 'Modifying CSS display: Assert element is visible');
	jQuery('#nothiddendiv').css("display", 'none');
	ok( !jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is hidden');
	jQuery('#nothiddendiv').css("display", 'block');
	ok( jQuery('#nothiddendiv').is(':visible'), 'Modified CSS display: Assert element is visible');

	jQuery("#nothiddendiv").css("top", "-1em");
	ok( jQuery("#nothiddendiv").css("top"), -16, "Check negative number in EMs." );

	jQuery('#floatTest').css('float', 'left');
	equals( jQuery('#floatTest').css('float'), 'left', 'Modified CSS float using "float": Assert float is left');
	jQuery('#floatTest').css('font-size', '20px');
	equals( jQuery('#floatTest').css('font-size'), '20px', 'Modified CSS font-size: Assert font-size is 20px');

	jQuery.each("0,0.25,0.5,0.75,1".split(','), function(i, n) {
		jQuery('#foo').css('opacity', n);
		equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a String" );
		jQuery('#foo').css('opacity', parseFloat(n));
		equals( jQuery('#foo').css('opacity'), parseFloat(n), "Assert opacity is " + parseFloat(n) + " as a Number" );
	});
	jQuery('#foo').css('opacity', '');
	equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when set to an empty String" );

	// using contents will get comments regular, text, and comment nodes
	var j = jQuery("#nonnodes").contents();
	j.css("fontSize", "1px");
	equals( j.css("fontSize"), "1px", "Check node,textnode,comment css works" );

	// opera sometimes doesn't update 'display' correctly, see #2037
	jQuery("#t2037")[0].innerHTML = jQuery("#t2037")[0].innerHTML
	equals( jQuery("#t2037 .hidden").css("display"), "none", "Make sure browser thinks it is hidden" );

	var div = jQuery("#nothiddendiv"),
		display = div.css("display"),
		ret = div.css("display", undefined);

	equals( ret, div, "Make sure setting undefined returns the original set." );
	equals( div.css("display"), display, "Make sure that the display wasn't changed." );

	// Test for Bug #5509
	var success = true;
	try {
		jQuery('#foo').css("backgroundColor", "rgba(0, 0, 0, 0.1)");
	}
	catch (e) {
		success = false;
	}
	ok( success, "Setting RGBA values does not throw Error" );
});

if ( !jQuery.support.opacity ) {
  test("css(String, Object) for MSIE", function() {
    // for #1438, IE throws JS error when filter exists but doesn't have opacity in it
		jQuery('#foo').css("filter", "progid:DXImageTransform.Microsoft.Chroma(color='red');");
  	equals( jQuery('#foo').css('opacity'), '1', "Assert opacity is 1 when a different filter is set in IE, #1438" );

    var filterVal = "progid:DXImageTransform.Microsoft.Alpha(opacity=30) progid:DXImageTransform.Microsoft.Blur(pixelradius=5)";
    var filterVal2 = "progid:DXImageTransform.Microsoft.alpha(opacity=100) progid:DXImageTransform.Microsoft.Blur(pixelradius=5)";
    var filterVal3 = "progid:DXImageTransform.Microsoft.Blur(pixelradius=5)";
    jQuery('#foo').css("filter", filterVal);
    equals( jQuery('#foo').css("filter"), filterVal, "css('filter', val) works" );
    jQuery('#foo').css("opacity", 1);
    equals( jQuery('#foo').css("filter"), filterVal2, "Setting opacity in IE doesn't duplicate opacity filter" );
    equals( jQuery('#foo').css("opacity"), 1, "Setting opacity in IE with other filters works" );
    jQuery('#foo').css("filter", filterVal3).css("opacity", 1);
    ok( jQuery('#foo').css("filter").indexOf(filterVal3) !== -1, "Setting opacity in IE doesn't clobber other filters" );
  });
}

test("css(String, Function)", function() {
	expect(3);

	var sizes = ["10px", "20px", "30px"];

	jQuery("

" +
				 "

" +
				 "

")
		.appendTo("body");

	var index = 0;

	jQuery("#cssFunctionTest div").css("font-size", function() {
		var size = sizes[index];
		index++;
		return size;
	});

	index = 0;

	jQuery("#cssFunctionTest div").each(function() {
		var computedSize = jQuery(this).css("font-size")
		var expectedSize = sizes[index]
		equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
		index++;
	});

	jQuery("#cssFunctionTest").remove();
});

test("css(String, Function) with incoming value", function() {
	expect(3);

	var sizes = ["10px", "20px", "30px"];

	jQuery("

" +
				 "

" +
				 "

")
		.appendTo("body");

	var index = 0;

	jQuery("#cssFunctionTest div").css("font-size", function() {
		var size = sizes[index];
		index++;
		return size;
	});

	index = 0;

	jQuery("#cssFunctionTest div").css("font-size", function(i, computedSize) {
		var expectedSize = sizes[index]
		equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
		index++;
		return computedSize;
	});

	jQuery("#cssFunctionTest").remove();
});

test("css(Object) where values are Functions", function() {
	expect(3);

	var sizes = ["10px", "20px", "30px"];

	jQuery("

" +
				 "

" +
				 "

")
		.appendTo("body");

	var index = 0;

	jQuery("#cssFunctionTest div").css({fontSize: function() {
		var size = sizes[index];
		index++;
		return size;
	}});

	index = 0;

	jQuery("#cssFunctionTest div").each(function() {
		var computedSize = jQuery(this).css("font-size")
		var expectedSize = sizes[index]
		equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
		index++;
	});

	jQuery("#cssFunctionTest").remove();
});

test("css(Object) where values are Functions with incoming values", function() {
	expect(3);

	var sizes = ["10px", "20px", "30px"];

	jQuery("

" +
				 "

" +
				 "

")
		.appendTo("body");

	var index = 0;

	jQuery("#cssFunctionTest div").css({fontSize: function() {
		var size = sizes[index];
		index++;
		return size;
	}});

	index = 0;

	jQuery("#cssFunctionTest div").css({"font-size": function(i, computedSize) {
		var expectedSize = sizes[index]
		equals( computedSize, expectedSize, "Div #" + index + " should be " + expectedSize );
		index++;
		return computedSize;
	}});

	jQuery("#cssFunctionTest").remove();
});

test("jQuery.css(elem, 'height') doesn't clear radio buttons (bug #1095)", function () {
	expect(4);

	var $checkedtest = jQuery("#checkedtest");
	// IE6 was clearing "checked" in jQuery.css(elem, "height");
	jQuery.css($checkedtest[0], "height");
	ok( !! jQuery(":radio:first", $checkedtest).attr("checked"), "Check first radio still checked." );
	ok( ! jQuery(":radio:last", $checkedtest).attr("checked"), "Check last radio still NOT checked." );
	ok( !! jQuery(":checkbox:first", $checkedtest).attr("checked"), "Check first checkbox still checked." );
	ok( ! jQuery(":checkbox:last", $checkedtest).attr("checked"), "Check last checkbox still NOT checked." );
});

test(":visible selector works properly on table elements (bug #4512)", function () {
	expect(1);

	jQuery('#table').html('
cell	cell
');
	equals(jQuery('#table td:visible').length, 1, "hidden cell is not perceived as visible");
});

test(":visible selector works properly on children with a hidden parent (bug #4512)", function () {
	expect(1);
	jQuery('#table').css('display', 'none').html('
cell	cell
');
	equals(jQuery('#table td:visible').length, 0, "hidden cell children not perceived as visible");
});
<|endoftext|>


<commit_before>const test = require('ava')
const vfile = require('vfile')
const weh = require('../lib/weh')

test('works correctly', async t => {
  const plugin = () => {
    return files => files.map(file => {
      file.contents = 'haha test'
      return file
    })
  }

  const res = await weh(site => {
    site.config({
      source: 'test/sample',
      no_write: true
    })

    site.use(plugin)
    return site
  })

  t.log(res.files)
  t.log(res.files.map(f => f.basename))
  t.is(res.files.find(f => f.basename === 'test.md').contents, 'haha test')
})

test('correctly runs in integration mode', async t => {
  const plugin = () => {
    return files => {
      return files.map(file => Object.assign(file, {contents: 'test2'}))
    }
  }

  const files = [
    vfile({ path: 'a', contents: 'aaa' })
  ]

  const res = await weh.integration(site => {
    site.use(plugin)
    return site
  }, files)

  t.is(res.files[0].contents, 'test2')
})
<commit_msg>remove some debug logs<commit_after>const test = require('ava')
const vfile = require('vfile')
const weh = require('../lib/weh')

test('works correctly', async t => {
  const plugin = () => {
    return files => files.map(file => {
      file.contents = 'haha test'
      return file
    })
  }

  const res = await weh(site => {
    site.config({
      source: 'test/sample',
      no_write: true
    })

    site.use(plugin)
    return site
  })

  t.is(res.files.find(f => f.basename === 'test.md').contents, 'haha test')
})

test('correctly runs in integration mode', async t => {
  const plugin = () => {
    return files => {
      return files.map(file => Object.assign(file, {contents: 'test2'}))
    }
  }

  const files = [
    vfile({ path: 'a', contents: 'aaa' })
  ]

  const res = await weh.integration(site => {
    site.use(plugin)
    return site
  }, files)

  t.is(res.files[0].contents, 'test2')
})
<|endoftext|>