<commit_before>// for Google Publisher Tag ads
//
// required props:
//    - adId: eg, '/6355419/Travel/Europe/France/Paris'
//    - height: a css size in pixels
//    - width: ditto
//
// optional props:
//    - placement: only useful if the same `adId` is used more than once on a
//      page, use this to distinguish between them: call one "1" and the other
//      "2", or call them "top-left" and "bottom-right", etc
//    - refresh: number of seconds between refreshes
//    - shouldWatchViewport: turn off checks for ad in view
//    - tracing: verbose messages in console.log via Ember.Logger.log
//    - backgroundRefresh: refresh ads when tabs in are backgrounded

import Ember from 'ember';
import {task, timeout} from 'ember-concurrency';
import InViewportMixin from 'ember-in-viewport';
import getViewportTolerance from '../utils/get-viewport-tolerance';

const {
    Component, assert, get, set, getProperties, setProperties, run,
    String: { htmlSafe },
    Logger: { log },
    run: { scheduleOnce }
} = Ember;

export default Component.extend(InViewportMixin, {
    classNames: ['google-publisher-tag'],
    attributeBindings: ['style'],

    placement: 0,
    refresh: 0,
    refreshCount: 0,
    refreshLimit: 0,
    tracing: false,
    shouldWatchViewport: true,

    didReceiveAttrs() {
        this._super(...arguments);

        let {adId, width, height, placement} = getProperties(this, 'adId', 'width', 'height', 'placement');

        // width and height are also passed into .defineSlot(), which will
        // silently fail unless they are actually numbers
        assert(`google-publisher-tag "${adId} (${placement})": width and height must be numbers`, typeof width === 'number' && typeof height === 'number');

        let style = `width:${width}px; height:${height}px;`;
        set(this, 'style', htmlSafe(style));
    },
    didInsertElement() {
        let {
            shouldWatchViewport,
            width,
            height
        } = getProperties(this,
            'shouldWatchViewport',
            'width',
            'height'
        );

        setProperties(this, {
            viewportEnabled: shouldWatchViewport,
            viewportSpy: true,
            viewportTolerance: getViewportTolerance(width, height, 0.5)
        });

        // we must set the properties above first before calling super
        // where the mixin consumes the properties
        this._super(...arguments);

        if (!shouldWatchViewport) {
            scheduleOnce('afterRender', () => {
                this.initAd();
            });
        } else {
            // watch via this.didEnterViewport(), below
            this.trace('watching viewport, waiting for event...');
        }

        if (!get(this, 'backgroundRefresh')) {
            if (document && document.addEventListener) {
                document.addEventListener('visibilitychange', () => {
                    this.trace('visibilitychange: document.hidden: ', document.hidden);
                    if (!document.hidden) {
                        this.didEnterViewport();
                    }
                }, false);
            }
        }
    },

    initAd() {
        if (!get(this, 'isAdInitialized')) {
            this.trace('initializing');
            set(this, 'isAdInitialized', true);
        }

        let duration = get(this, 'refresh');
            if (duration > 0) {
            this.waitForRefresh();
        }
    },

    addTargeting(/* slot */) {
        // override this in child components, if needed, but an example is:
        // slot.setTargeting('placement', get(this, 'placement'));
        // slot.setTargeting('refresh_count', get(this, 'refreshCount'));
        // slot.setTargeting('planet', 'Earth');
    },
    waitForRefresh() {
        let {refreshLimit, refreshCount} = getProperties(this, 'refreshLimit', 'refreshCount');
        if (refreshLimit > 0 && refreshCount >= refreshLimit) {
            this.trace(`refreshCount has met refreshLimit: ${refreshLimit}`);
          return;
        }

        // give the tests a moment to release wait handlers
        setTimeout(() => {
            run(() => {
                get(this, 'refreshWaitTask').perform();
            });
        });
    },
    trace() {
        if (get(this, 'tracing')) {
            let {adId, placement} = getProperties(this, 'adId', 'placement');
            log(`${adId} (${placement}):`, ...arguments);
        }
    },

    refreshWaitTask: task(function * () {
        let duration = get(this, 'refresh');

        this.trace(`will refresh in ${duration} seconds`);

        yield timeout(duration * 1000);

        let {
            shouldWatchViewport,
            viewportEntered
        } = getProperties(this,
            'shouldWatchViewport',
            'viewportEntered'
        );

        if (shouldWatchViewport && !viewportEntered) {
            this.trace('ad not in view, delaying refresh');
            set(this, 'isRefreshOverdue', true);
            return;
        }

        if (!get(this, 'backgroundRefresh') && document.hidden) {
            this.trace('ad is in background, delaying refresh');
            set(this, 'isRefreshOverdue', true);
            return;
        }

        this.doRefresh();
    }).drop(), // don't reset the timer if you scroll out and back in view before it finishes

    doRefresh() {
        let googletag = window.googletag;
        googletag.cmd.push( () => {
            this.incrementProperty('refreshCount');
            this.traceRefresh();

            let slot = get(this, 'slot');
            this.addTargeting(slot);
            googletag.pubads().refresh([slot]);

            this.waitForRefresh();
        });
    },

    traceRefresh() {
        let { refreshCount, refreshLimit } = getProperties(this, 'refreshCount', 'refreshLimit');

        let text = `refreshing now: ${refreshCount}`;
        if (refreshLimit > 0) {
            text += ` of ${refreshLimit}`;
        }

        this.trace(text);
    },

    didEnterViewport() {
        this.trace('entered viewport');

        this.initAd();
        if (get(this, 'isRefreshOverdue')) {
            this.doRefresh();
            set(this, 'isRefreshOverdue', false);
        }
    }
});
<commit_msg>fix background-vs-viewport initialization<commit_after>// for Google Publisher Tag ads
//
// required props:
//    - adId: eg, '/6355419/Travel/Europe/France/Paris'
//    - height: a css size in pixels
//    - width: ditto
//
// optional props:
//    - placement: only useful if the same `adId` is used more than once on a
//      page, use this to distinguish between them: call one "1" and the other
//      "2", or call them "top-left" and "bottom-right", etc
//    - refresh: number of seconds between refreshes
//    - shouldWatchViewport: turn off checks for ad in view
//    - tracing: verbose messages in console.log via Ember.Logger.log
//    - backgroundRefresh: refresh ads when tabs in are backgrounded

import Ember from 'ember';
import {task, timeout} from 'ember-concurrency';
import InViewportMixin from 'ember-in-viewport';
import getViewportTolerance from '../utils/get-viewport-tolerance';

const {
    Component, assert, get, set, getProperties, setProperties, run,
    String: { htmlSafe },
    Logger: { log },
    run: { scheduleOnce }
} = Ember;

export default Component.extend(InViewportMixin, {
    classNames: ['google-publisher-tag'],
    attributeBindings: ['style'],

    placement: 0,
    refresh: 0,
    refreshCount: 0,
    refreshLimit: 0,
    tracing: false,
    shouldWatchViewport: true,

    didReceiveAttrs() {
        this._super(...arguments);

        let {adId, width, height, placement} = getProperties(this, 'adId', 'width', 'height', 'placement');

        // width and height are also passed into .defineSlot(), which will
        // silently fail unless they are actually numbers
        assert(`google-publisher-tag "${adId} (${placement})": width and height must be numbers`, typeof width === 'number' && typeof height === 'number');

        let style = `width:${width}px; height:${height}px;`;
        set(this, 'style', htmlSafe(style));
    },
    didInsertElement() {
        let {
            shouldWatchViewport,
            width,
            height
        } = getProperties(this,
            'shouldWatchViewport',
            'width',
            'height'
        );

        setProperties(this, {
            viewportEnabled: shouldWatchViewport,
            viewportSpy: true,
            viewportTolerance: getViewportTolerance(width, height, 0.5)
        });

        // we must set the properties above first before calling super
        // where the mixin consumes the properties
        this._super(...arguments);

        if (!shouldWatchViewport) {
            scheduleOnce('afterRender', () => {
                this.initAd();
            });
        } else {
            // watch via this.didEnterViewport(), below
            this.trace('watching viewport, waiting for event...');
        }

        if (!get(this, 'backgroundRefresh')) {
            if (document && document.addEventListener) {
                document.addEventListener('visibilitychange', () => {
                    this.trace('visibilitychange: document.hidden: ', document.hidden);
                    if (!document.hidden) {
                        if (shouldWatchViewport) {
                            this.trace('visibilitychange: watching viewport instead, skipping init');
                        }
                        else {
                            this.initAd();
                        }
                    }
                }, false);
            }
        }
    },

    initAd() {
        if (!get(this, 'isAdInitialized')) {
            this.trace('initializing');
            set(this, 'isAdInitialized', true);
        }

        let duration = get(this, 'refresh');
            if (duration > 0) {
            this.waitForRefresh();
        }
    },

    addTargeting(/* slot */) {
        // override this in child components, if needed, but an example is:
        // slot.setTargeting('placement', get(this, 'placement'));
        // slot.setTargeting('refresh_count', get(this, 'refreshCount'));
        // slot.setTargeting('planet', 'Earth');
    },
    waitForRefresh() {
        let {refreshLimit, refreshCount} = getProperties(this, 'refreshLimit', 'refreshCount');
        if (refreshLimit > 0 && refreshCount >= refreshLimit) {
            this.trace(`refreshCount has met refreshLimit: ${refreshLimit}`);
          return;
        }

        // give the tests a moment to release wait handlers
        setTimeout(() => {
            run(() => {
                get(this, 'refreshWaitTask').perform();
            });
        });
    },
    trace() {
        if (get(this, 'tracing')) {
            let {adId, placement} = getProperties(this, 'adId', 'placement');
            log(`${adId} (${placement}):`, ...arguments);
        }
    },

    refreshWaitTask: task(function * () {
        let duration = get(this, 'refresh');

        this.trace(`will refresh in ${duration} seconds`);

        yield timeout(duration * 1000);

        let {
            shouldWatchViewport,
            viewportEntered
        } = getProperties(this,
            'shouldWatchViewport',
            'viewportEntered'
        );

        if (shouldWatchViewport && !viewportEntered) {
            this.trace('ad not in view, delaying refresh');
            set(this, 'isRefreshOverdue', true);
            return;
        }

        if (!get(this, 'backgroundRefresh') && document.hidden) {
            this.trace('ad is in background, delaying refresh');
            set(this, 'isRefreshOverdue', true);
            return;
        }

        this.doRefresh();
    }).drop(), // don't reset the timer if you scroll out and back in view before it finishes

    doRefresh() {
        let googletag = window.googletag;
        googletag.cmd.push( () => {
            this.incrementProperty('refreshCount');
            this.traceRefresh();

            let slot = get(this, 'slot');
            this.addTargeting(slot);
            googletag.pubads().refresh([slot]);

            this.waitForRefresh();
        });
    },

    traceRefresh() {
        let { refreshCount, refreshLimit } = getProperties(this, 'refreshCount', 'refreshLimit');

        let text = `refreshing now: ${refreshCount}`;
        if (refreshLimit > 0) {
            text += ` of ${refreshLimit}`;
        }

        this.trace(text);
    },

    didEnterViewport() {
        this.trace('entered viewport');

        this.initAd();
        if (get(this, 'isRefreshOverdue')) {
            this.doRefresh();
            set(this, 'isRefreshOverdue', false);
        }
    }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import { default as CalendarEvent } from 'el-calendar/components/calendar-event';
import layout from '../templates/components/ilios-calendar-event';
import moment from 'moment';

const { computed, Handlebars, isBlank, isArray } = Ember;
const { SafeString } = Handlebars;
const { notEmpty, any } = computed;

export default CalendarEvent.extend({
  layout,
  event: null,
  timeFormat: 'h:mma',
  isDay: false,
  classNameBindings: [':event', ':event-pos', ':ilios-calendar-event', 'isDay:day', 'event.eventClass', 'clickable:clickable'],
  taughtByPhrase: 'Taught by',
  courseTitlePhrase: 'Course',
  etAlPhrase: 'et al.',
  tooltipContent: computed('event', function() {
    if (this.get('event') == null) {
      return '';
    }

    let addLocationToContents = function(contents, location) {
      if (! isBlank(location)) {
        contents = contents + `${location}<br />`;
      }
      return contents;
    };

    let addInstructorsToContents = function(contents, instructors, taughtByPhrase, etAlPhrase) {
      if (! instructors.length) {
        return contents;
      }

      if (3 > instructors.length) {
        contents = contents + `<br />${taughtByPhrase} ` + instructors.join(', ');
      } else {
        contents = contents + `<br />${taughtByPhrase} ` + instructors.slice(0, 2).join(', ') + ` ${etAlPhrase}`;
      }
      return contents;
    };

    let addCourseTitleToContents = function(contents, courseTitle, courseTitlePhrase) {
      if (courseTitle) {
        contents = contents + `<br />${courseTitlePhrase}: ${courseTitle}`;
      }
      return contents;
    };

    const location = this.get('event.location') || '';
    const name = this.get('event.name');
    const startTime = moment(this.get('event.startDate')).format(this.get('timeFormat'));
    const endTime = moment(this.get('event.endDate')).format(this.get('timeFormat'));
    const dueThisDay = this.get('dueThisDay');
    const instructors = this.get('event.instructors') || [];
    const courseTitle = this.get('event.courseTitle');
    const taughtByPhrase = this.get('taughtByPhrase');
    const courseTitlePhrase = this.get('courseTitlePhrase');
    const etAlPhrase = this.get('etAlPhrase');
    let contents = '';

    if (this.get('isIlm')) {
      contents = addLocationToContents(contents, location);
      contents = contents + `${dueThisDay}<br />${name}`;
      contents = addInstructorsToContents(contents, instructors, taughtByPhrase, etAlPhrase);
      contents = addCourseTitleToContents(contents, courseTitle, courseTitlePhrase);
    } else if (this.get('isOffering')) {
      contents = addLocationToContents(contents, location);
      contents = contents + `${startTime} - ${endTime}<br />${name}`;
      contents = addInstructorsToContents(contents, instructors, taughtByPhrase, etAlPhrase);
      contents = addCourseTitleToContents(contents, courseTitle, courseTitlePhrase);
    } else { // 'TBD' event
      contents = `TBD<br />${startTime} - ${endTime}<br />${name}`;
    }

    return contents;
  }),
  isIlm: notEmpty('event.ilmSession'),
  isOffering: notEmpty('event.offering'),
  clickable: any('isIlm', 'isOffering'),

  formattedInstructors: computed(function() {
    let instructors = this.get('event.instructors');
    if (! isArray(instructors) || ! instructors.length) {
      return '';
    }
    if (3 > instructors.length) {
      return instructors.join(', ');
    } else {
      return instructors.slice(0, 2).join(', ') + ' ' + this.get('etAlPhrase');
    }
  }),

  style: computed(function() {
    if (this.get('event') == null) {
      return new SafeString('');
    }

    let escape = Handlebars.Utils.escapeExpression;

    return new SafeString(
      `top: ${escape(this.calculateTop())}%;
       height: ${escape(this.calculateHeight())}%;
       left: ${escape(this.calculateLeft())}%;
       width: ${escape(this.calculateWidth())}%;`
    );
  }),

  click(){
    if(this.get('clickable')){
      this.sendAction('action', this.get('event'));
    }
  }
});
<commit_msg>added 'is-ilm' class to event component.<commit_after>import Ember from 'ember';
import { default as CalendarEvent } from 'el-calendar/components/calendar-event';
import layout from '../templates/components/ilios-calendar-event';
import moment from 'moment';

const { computed, Handlebars, isBlank, isArray } = Ember;
const { SafeString } = Handlebars;
const { notEmpty, any } = computed;

export default CalendarEvent.extend({
  layout,
  event: null,
  timeFormat: 'h:mma',
  isDay: false,
  classNameBindings: [
    ':event',
    ':event-pos',
    ':ilios-calendar-event',
    'isDay:day',
    'event.eventClass',
    'clickable:clickable',
    'isIlm'
  ],
  taughtByPhrase: 'Taught by',
  courseTitlePhrase: 'Course',
  etAlPhrase: 'et al.',
  tooltipContent: computed('event', function() {
    if (this.get('event') == null) {
      return '';
    }

    let addLocationToContents = function(contents, location) {
      if (! isBlank(location)) {
        contents = contents + `${location}<br />`;
      }
      return contents;
    };

    let addInstructorsToContents = function(contents, instructors, taughtByPhrase, etAlPhrase) {
      if (! instructors.length) {
        return contents;
      }

      if (3 > instructors.length) {
        contents = contents + `<br />${taughtByPhrase} ` + instructors.join(', ');
      } else {
        contents = contents + `<br />${taughtByPhrase} ` + instructors.slice(0, 2).join(', ') + ` ${etAlPhrase}`;
      }
      return contents;
    };

    let addCourseTitleToContents = function(contents, courseTitle, courseTitlePhrase) {
      if (courseTitle) {
        contents = contents + `<br />${courseTitlePhrase}: ${courseTitle}`;
      }
      return contents;
    };

    const location = this.get('event.location') || '';
    const name = this.get('event.name');
    const startTime = moment(this.get('event.startDate')).format(this.get('timeFormat'));
    const endTime = moment(this.get('event.endDate')).format(this.get('timeFormat'));
    const dueThisDay = this.get('dueThisDay');
    const instructors = this.get('event.instructors') || [];
    const courseTitle = this.get('event.courseTitle');
    const taughtByPhrase = this.get('taughtByPhrase');
    const courseTitlePhrase = this.get('courseTitlePhrase');
    const etAlPhrase = this.get('etAlPhrase');
    let contents = '';

    if (this.get('isIlm')) {
      contents = addLocationToContents(contents, location);
      contents = contents + `${dueThisDay}<br />${name}`;
      contents = addInstructorsToContents(contents, instructors, taughtByPhrase, etAlPhrase);
      contents = addCourseTitleToContents(contents, courseTitle, courseTitlePhrase);
    } else if (this.get('isOffering')) {
      contents = addLocationToContents(contents, location);
      contents = contents + `${startTime} - ${endTime}<br />${name}`;
      contents = addInstructorsToContents(contents, instructors, taughtByPhrase, etAlPhrase);
      contents = addCourseTitleToContents(contents, courseTitle, courseTitlePhrase);
    } else { // 'TBD' event
      contents = `TBD<br />${startTime} - ${endTime}<br />${name}`;
    }

    return contents;
  }),
  isIlm: notEmpty('event.ilmSession'),
  isOffering: notEmpty('event.offering'),
  clickable: any('isIlm', 'isOffering'),

  formattedInstructors: computed(function() {
    let instructors = this.get('event.instructors');
    if (! isArray(instructors) || ! instructors.length) {
      return '';
    }
    if (3 > instructors.length) {
      return instructors.join(', ');
    } else {
      return instructors.slice(0, 2).join(', ') + ' ' + this.get('etAlPhrase');
    }
  }),

  style: computed(function() {
    if (this.get('event') == null) {
      return new SafeString('');
    }

    let escape = Handlebars.Utils.escapeExpression;

    return new SafeString(
      `top: ${escape(this.calculateTop())}%;
       height: ${escape(this.calculateHeight())}%;
       left: ${escape(this.calculateLeft())}%;
       width: ${escape(this.calculateWidth())}%;`
    );
  }),

  click(){
    if(this.get('clickable')){
      this.sendAction('action', this.get('event'));
    }
  }
});
<|endoftext|>


<commit_before>export const BENEFICIARY_ACCOUNT = 'busy.org';
export const BENEFICIARY_PERCENT = 1000;
export const REFERRAL_PERCENT = 1000;
export const MAX_TAG = 12; // to support SCOT tokens. but some Steem API may not work properly for more than 5 tags.
export const USER_METADATA_KEY = 'user_metadata'; // key for localStorage

// to support total past payout including beneficiaires: https://github.com/busyorg/busy/issues/2220
// Expected HF21 time: https://github.com/steemit/steem/blob/master/libraries/protocol/hardfork.d/0_21.hf
export const HF21_TIME = '2019-08-27T15:00:00';
export const DEFAULT_CURATION_REWARD_PERCENT = 25;
export const HF21_CURATION_REWARD_PERCENT = 50;

export const knownDomains = [
  'busy.org',
  'staging.busy.org',
  'steemit.com',
  'steem.io',
  'd.tube',
  'dlive.io',
  'utopian.io',
  'coinmarketcap.com',
  'youtube.com',
];

export const people = [
  'steemsports',
  'knozaki2015',
  'gavvet',
  'krnel',
  'papa-pepper',
  'ozchartart',
  'craig-grant',
  'ericvancewalton',
  'curie',
  'stellabelle',
  'doitvoluntarily',
  'sirwinchester',
  'sweetsssj',
  'kevinwong',
  'jrcornel',
  'thecryptofiend',
  'steemcleaners',
  'kingscrown',
  'opheliafu',
  'officialfuzzy',
  'steemtrail',
  'good-karma',
  'dollarvigilante',
  'sauravrungta',
  'chinadaily',
  'calaber24p',
  'kaylinart',
  'dantheman',
  'tuck-fheman',
  'mynameisbrian',
  'macksby',
  'hanshotfirst',
  'hilarski',
  'ats-david',
  'fyrstikken',
  'alexbeyman',
  'gringalicious',
  'donkeypong',
  'steempower',
  'marius19',
  'mindhunter',
  'the-alien',
  'kafkanarchy84',
  'dwinblood',
  'stephenkendal',
  'luzcypher',
  'pfunk',
  'oflyhigh',
  'dana-edwards',
  'cryptoctopus',
  'steemvoter',
  'myfirst',
  'elfkitchen',
  'barrydutton',
  'dragosroua',
  'jlufer',
  'acidyo',
  'timsaid',
  'timcliff',
  'lukestokes',
  'lily-da-vine',
  'meesterboom',
  'infovore',
  'klye',
  'charlieshrem',
  'rok-sivante',
  'ausbitbank',
  'everittdmickey',
  'homeartpictures',
  'birds90',
  'michelle.gent',
  'tamim',
  'clayop',
  'terrycraft',
  'b0y2k',
  'dragonslayer109',
  'heiditravels',
  'joseph',
  'ace108',
  'kus-knee',
  'gardenofeden',
  'cryptogee',
  'deanliu',
  'anwenbaumeister',
  'jamtaylor',
  'daveks',
  'masteryoda',
  'onceuponatime',
  'halo',
  'ash',
  'englishtchrivy',
  'penguinpablo',
  'yoonjang0707',
  'jerrybanfield',
  'cheetah',
  'bridgetbunchy',
  'gargon',
  'ocrdu',
  'nanzo-scoop',
  'surfermarly',
  'blockchainstudio',
];
<commit_msg>Update constants.js<commit_after>export const BENEFICIARY_ACCOUNT = 'busy.org';
export const BENEFICIARY_PERCENT = 1000;
export const REFERRAL_PERCENT = 1000;
export const MAX_TAG = 12; // to support SCOT tokens. but some Steem API may not work properly for more than 5 tags.
export const USER_METADATA_KEY = 'user_metadata'; // key for localStorage

// to support total past payout including beneficiaires: https://github.com/busyorg/busy/issues/2220
// Expected HF21 time: https://github.com/steemit/steem/blob/master/libraries/protocol/hardfork.d/0_21.hf
export const HF21_TIME = '2019-08-27T15:00:00';
export const DEFAULT_CURATION_REWARD_PERCENT = 25;
export const HF21_CURATION_REWARD_PERCENT = 50;

export const knownDomains = [
  'busy.org',
  'staging.busy.org',
  'steemit.com',
  'steem.io',
  'd.tube',
  'coinmarketcap.com',
  'youtube.com',
];

export const people = [
  'steemsports',
  'knozaki2015',
  'gavvet',
  'krnel',
  'papa-pepper',
  'ozchartart',
  'craig-grant',
  'ericvancewalton',
  'curie',
  'stellabelle',
  'doitvoluntarily',
  'sirwinchester',
  'sweetsssj',
  'kevinwong',
  'jrcornel',
  'thecryptofiend',
  'steemcleaners',
  'kingscrown',
  'opheliafu',
  'officialfuzzy',
  'steemtrail',
  'good-karma',
  'dollarvigilante',
  'sauravrungta',
  'chinadaily',
  'calaber24p',
  'kaylinart',
  'dantheman',
  'tuck-fheman',
  'mynameisbrian',
  'macksby',
  'hanshotfirst',
  'hilarski',
  'ats-david',
  'fyrstikken',
  'alexbeyman',
  'gringalicious',
  'donkeypong',
  'steempower',
  'marius19',
  'mindhunter',
  'the-alien',
  'kafkanarchy84',
  'dwinblood',
  'stephenkendal',
  'luzcypher',
  'pfunk',
  'oflyhigh',
  'dana-edwards',
  'cryptoctopus',
  'steemvoter',
  'myfirst',
  'elfkitchen',
  'barrydutton',
  'dragosroua',
  'jlufer',
  'acidyo',
  'timsaid',
  'timcliff',
  'lukestokes',
  'lily-da-vine',
  'meesterboom',
  'infovore',
  'klye',
  'charlieshrem',
  'rok-sivante',
  'ausbitbank',
  'everittdmickey',
  'homeartpictures',
  'birds90',
  'michelle.gent',
  'tamim',
  'clayop',
  'terrycraft',
  'b0y2k',
  'dragonslayer109',
  'heiditravels',
  'joseph',
  'ace108',
  'kus-knee',
  'gardenofeden',
  'cryptogee',
  'deanliu',
  'anwenbaumeister',
  'jamtaylor',
  'daveks',
  'masteryoda',
  'onceuponatime',
  'halo',
  'ash',
  'englishtchrivy',
  'penguinpablo',
  'yoonjang0707',
  'jerrybanfield',
  'cheetah',
  'bridgetbunchy',
  'gargon',
  'ocrdu',
  'nanzo-scoop',
  'surfermarly',
  'blockchainstudio',
  'steemfinex'
];
<|endoftext|>


<commit_before>import blacklist from 'blacklist';
import classnames from 'classnames';
import React from 'react';
import { Container } from 'elemental';
const Transition = React.addons.CSSTransitionGroup;

var MobileListItem = React.createClass({
	displayName: 'MobileListItem',
	propTypes: {
		className: React.PropTypes.string,
		children: React.PropTypes.node.isRequired,
		href: React.PropTypes.string.isRequired,
	},
	render () {
		return (

				{this.props.children}

		);
	},
});

var MobileSectionItem = React.createClass({
	displayName: 'MobileSectionItem',
	propTypes: {
		className: React.PropTypes.string,
		children: React.PropTypes.node.isRequired,
		href: React.PropTypes.string.isRequired,
		lists: React.PropTypes.array,
	},
	renderLists () {
		if (!this.props.lists || this.props.lists.length <= 1) return null;

		let navLists = this.props.lists.map((item) => {
			let href = item.external ? item.path : ('/keystone/' + item.path);
			let className = (this.props.currentListKey && this.props.currentListKey === item.path) ? 'MobileNavigation__list-item is-active' : 'MobileNavigation__list-item';

			return (
				<MobileListItem href={href} className={className}>
					{item.label}
				</MobileListItem>
			);
		});

		return (

				{navLists}

		);
	},
	render () {
		return (

					{this.props.children}

				{this.renderLists()}

		);
	},
});

var MobileNavigation = React.createClass({
	displayName: 'MobileNavigation',
	propTypes: {
		brand: React.PropTypes.string,
		currentSectionKey: React.PropTypes.string,
		currentListKey: React.PropTypes.string,
		sections: React.PropTypes.array.isRequired,
		signoutUrl: React.PropTypes.string,
	},
	getInitialState() {
		return {
			barIsVisible: false,
		};
	},
	componentDidMount: function() {
		this.handleResize();
		window.addEventListener('resize', this.handleResize);
	},
	componentWillUnmount: function() {
		window.removeEventListener('resize', this.handleResize);
	},
	handleResize: function() {
		this.setState({
			barIsVisible: window.innerWidth < 768
		});
	},
	toggleMenu () {
		this.setState({
			menuIsVisible: !this.state.menuIsVisible
		}, () => {
			let body = document.getElementsByTagName('body')[0];

			if (this.state.menuIsVisible) {
				body.style.overflow = 'hidden';
			} else {
				body.style.overflow = null;
			}
		});
	},
	renderNavigation () {
		if (!this.props.sections || !this.props.sections.length) return null;

		return this.props.sections.map((section) => {
			let href = section.lists[0].external ? section.lists[0].path : ('/keystone/' + section.lists[0].path);
			let className = (this.props.currentSectionKey && this.props.currentSectionKey === section.key) ? 'MobileNavigation__section is-active' : 'MobileNavigation__section';

			return (
				<MobileSectionItem className={className} href={href} lists={section.lists} currentListKey={this.props.currentListKey}>
					{section.label}
				</MobileSectionItem>
			);
		});
	},
	renderBlockout () {
		if (!this.state.menuIsVisible) return null;

		return
;
	},
	renderMenu () {
		if (!this.state.menuIsVisible) return null;

		return (

					{this.renderNavigation()}

		);
	},
	render () {
		if (!this.state.barIsVisible) return null;

		let componentClassname = this.state.menuIsVisible ? 'MobileNavigation is-open' : 'MobileNavigation';

		return (

					<button type="button" onClick={this.toggleMenu} className="MobileNavigation__bar__button MobileNavigation__bar__button--menu">

					</button>
					{this.props.brand}

				<Transition transitionName="MobileNavigation__menu">
					{this.renderMenu()}
				</Transition>
				<Transition transitionName="react-transitiongroup-fade">
					{this.renderBlockout()}
				</Transition>

		);
	}
});

module.exports = MobileNavigation;
<commit_msg>fixing react warnings<commit_after>import blacklist from 'blacklist';
import classnames from 'classnames';
import React from 'react';
import { Container } from 'elemental';
const Transition = React.addons.CSSTransitionGroup;

var MobileListItem = React.createClass({
	displayName: 'MobileListItem',
	propTypes: {
		className: React.PropTypes.string,
		children: React.PropTypes.node.isRequired,
		href: React.PropTypes.string.isRequired,
	},
	render () {
		return (

				{this.props.children}

		);
	},
});

var MobileSectionItem = React.createClass({
	displayName: 'MobileSectionItem',
	propTypes: {
		className: React.PropTypes.string,
		children: React.PropTypes.node.isRequired,
		href: React.PropTypes.string.isRequired,
		lists: React.PropTypes.array,
	},
	renderLists () {
		if (!this.props.lists || this.props.lists.length <= 1) return null;

		let navLists = this.props.lists.map((item) => {
			let href = item.external ? item.path : ('/keystone/' + item.path);
			let className = (this.props.currentListKey && this.props.currentListKey === item.path) ? 'MobileNavigation__list-item is-active' : 'MobileNavigation__list-item';

			return (
				<MobileListItem key={item.path} href={href} className={className}>
					{item.label}
				</MobileListItem>
			);
		});

		return (

				{navLists}

		);
	},
	render () {
		return (

					{this.props.children}

				{this.renderLists()}

		);
	},
});

var MobileNavigation = React.createClass({
	displayName: 'MobileNavigation',
	propTypes: {
		brand: React.PropTypes.string,
		currentSectionKey: React.PropTypes.string,
		currentListKey: React.PropTypes.string,
		sections: React.PropTypes.array.isRequired,
		signoutUrl: React.PropTypes.string,
	},
	getInitialState() {
		return {
			barIsVisible: false,
		};
	},
	componentDidMount: function() {
		this.handleResize();
		window.addEventListener('resize', this.handleResize);
	},
	componentWillUnmount: function() {
		window.removeEventListener('resize', this.handleResize);
	},
	handleResize: function() {
		this.setState({
			barIsVisible: window.innerWidth < 768
		});
	},
	toggleMenu () {
		this.setState({
			menuIsVisible: !this.state.menuIsVisible
		}, () => {
			let body = document.getElementsByTagName('body')[0];

			if (this.state.menuIsVisible) {
				body.style.overflow = 'hidden';
			} else {
				body.style.overflow = null;
			}
		});
	},
	renderNavigation () {
		if (!this.props.sections || !this.props.sections.length) return null;

		return this.props.sections.map((section) => {
			let href = section.lists[0].external ? section.lists[0].path : ('/keystone/' + section.lists[0].path);
			let className = (this.props.currentSectionKey && this.props.currentSectionKey === section.key) ? 'MobileNavigation__section is-active' : 'MobileNavigation__section';

			return (
				<MobileSectionItem key={section.key} className={className} href={href} lists={section.lists} currentListKey={this.props.currentListKey}>
					{section.label}
				</MobileSectionItem>
			);
		});
	},
	renderBlockout () {
		if (!this.state.menuIsVisible) return null;

		return
;
	},
	renderMenu () {
		if (!this.state.menuIsVisible) return null;

		return (

					{this.renderNavigation()}

		);
	},
	render () {
		if (!this.state.barIsVisible) return null;

		let componentClassname = this.state.menuIsVisible ? 'MobileNavigation is-open' : 'MobileNavigation';

		return (

					<button type="button" onClick={this.toggleMenu} className="MobileNavigation__bar__button MobileNavigation__bar__button--menu">

					</button>
					{this.props.brand}

				<Transition transitionName="MobileNavigation__menu">
					{this.renderMenu()}
				</Transition>
				<Transition transitionName="react-transitiongroup-fade">
					{this.renderBlockout()}
				</Transition>

		);
	}
});

module.exports = MobileNavigation;
<|endoftext|>


<commit_before>import {h, Component}					from 'preact/preact';

import SidebarCountdown					from 'com/sidebar/countdown/countdown';
import SidebarCalendar					from 'com/sidebar/calendar/calendar';
import SidebarUpcoming					from 'com/sidebar/upcoming/upcoming';
import SidebarTV						from 'com/sidebar/tv/tv';
import SidebarTrending					from 'com/sidebar/trending/trending';
import SidebarSponsor					from 'com/sidebar/sponsor/sponsor';
import SidebarSupport					from 'com/sidebar/support/support';

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

	render( props ) {
		// TODO: cleanup
		let ldStartDate = new Date(Date.UTC(2017, 11, 2, 2, 0, 0));

		let compoEndDate = new Date(Date.UTC(2017, 11, 4, 2, 0, 0));
		let compoEndDate2 = new Date(Date.UTC(2017, 11, 4, 3, 0, 0));

		let jamEndDate = new Date(Date.UTC(2017, 11, 5, 2, 0, 0));
		let jamEndDate2 = new Date(Date.UTC(2017, 11, 5, 3, 0, 0));

		let gradeEndDate = new Date(Date.UTC(2017, 11, 27, 16, 0, 0));
		let resultsDate = new Date(Date.UTC(2017, 11, 29, 16, 0, 0));

		let now = new Date();

		let ShowCountdown = [];
		if ( now < ldStartDate ) {
			ShowCountdown.push(<SidebarCountdown date={ ldStartDate } nc="ld" tt="Starts" />); /*to="Ludum Dare"*/
		}
		else {
			if ( now < compoEndDate ) {
				ShowCountdown.push(<SidebarCountdown date={ compoEndDate } nc="compo" to="Compo" tt="Ends" />);
			}
			else if ( now < compoEndDate2 ) {
				ShowCountdown.push(<SidebarCountdown date={ compoEndDate2 } nc="compo" to="Submission Hour" tt="Ends" />);
			}

			if ( now < jamEndDate ) {
				ShowCountdown.push(<SidebarCountdown date={ jamEndDate } nc="jam" to="Jam" tt="Ends" />);
			}
			else if ( now < jamEndDate2 ) {
				ShowCountdown.push(<SidebarCountdown date={ jamEndDate2 } nc="jam" to="Submission Hour+" tt="Ends" />);
			}

//			if ( now < compoEndDate2 || now < jamEndDate2 || now < gradeEndDate ) {
//				ShowCountdown.push(<SidebarCountdown date={ gradeEndDate } nc="jam" to="Play+Rate games" tt="Ends" />);
//			}
//
//			// TODO: make this only appear a few hours before grading ends
//			if ( now < resultsDate ) {
//				ShowCountdown.push(<SidebarCountdown date={ resultsDate } nc="jam" to="Results" tt="live" />);
//			}
		}

		return (

				{ShowCountdown}
				<SidebarCalendar rows={ShowCountdown.length ? 2 : 3} />
				<SidebarUpcoming />
				<SidebarTV />
				<SidebarSponsor />
				<SidebarSupport />

		);
	}
}
<commit_msg>now showing the rate clock when grading is enabled<commit_after>import {h, Component}					from 'preact/preact';

import SidebarCountdown					from 'com/sidebar/countdown/countdown';
import SidebarCalendar					from 'com/sidebar/calendar/calendar';
import SidebarUpcoming					from 'com/sidebar/upcoming/upcoming';
import SidebarTV						from 'com/sidebar/tv/tv';
import SidebarTrending					from 'com/sidebar/trending/trending';
import SidebarSponsor					from 'com/sidebar/sponsor/sponsor';
import SidebarSupport					from 'com/sidebar/support/support';

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

	render( props ) {
		// TODO: cleanup
		let ldStartDate = new Date(Date.UTC(2017, 11, 2, 2, 0, 0));

		let compoEndDate = new Date(Date.UTC(2017, 11, 4, 2, 0, 0));
		let compoEndDate2 = new Date(Date.UTC(2017, 11, 4, 3, 0, 0));

		let jamEndDate = new Date(Date.UTC(2017, 11, 5, 2, 0, 0));
		let jamEndDate2 = new Date(Date.UTC(2017, 11, 5, 3, 0, 0));

		let gradeEndDate = new Date(Date.UTC(2017, 11, 27, 16, 0, 0));
		let resultsDate = new Date(Date.UTC(2017, 11, 29, 16, 0, 0));

		let now = new Date();

		let ShowCountdown = [];
		if ( now < ldStartDate ) {
			ShowCountdown.push(<SidebarCountdown date={ ldStartDate } nc="ld" tt="Starts" />); /*to="Ludum Dare"*/
		}
		else {
			if ( now < compoEndDate ) {
				ShowCountdown.push(<SidebarCountdown date={ compoEndDate } nc="compo" to="Compo" tt="Ends" />);
			}
			else if ( now < compoEndDate2 ) {
				ShowCountdown.push(<SidebarCountdown date={ compoEndDate2 } nc="compo" to="Submission Hour" tt="Ends" />);
			}

			if ( now < jamEndDate ) {
				ShowCountdown.push(<SidebarCountdown date={ jamEndDate } nc="jam" to="Jam" tt="Ends" />);
			}
			else if ( now < jamEndDate2 ) {
				ShowCountdown.push(<SidebarCountdown date={ jamEndDate2 } nc="jam" to="Submission Hour+" tt="Ends" />);
			}

			if ( props.featured && props.featured.meta && props.featured.meta['can-grade'] ) { //now < compoEndDate2 || now < jamEndDate2 || now < gradeEndDate ) {
				ShowCountdown.push(<SidebarCountdown date={ gradeEndDate } nc="jam" to="Play+Rate games" tt="Ends" />);
			}

//			// TODO: make this only appear a few hours before grading ends
//			if ( now < resultsDate ) {
//				ShowCountdown.push(<SidebarCountdown date={ resultsDate } nc="jam" to="Results" tt="live" />);
//			}
		}

		return (

				{ShowCountdown}
				<SidebarCalendar rows={ShowCountdown.length ? 2 : 3} />
				<SidebarUpcoming />
				<SidebarTV />
				<SidebarSponsor />
				<SidebarSupport />

		);
	}
}
<|endoftext|>


<commit_before>const logger = require('winston')
const { Command } = require('../../core')

class Lang extends Command {
  constructor (...args) {
    super(...args, {
      name: 'lang',
      description: 'Allows moderators to set a guild\'s language',
      aliases: ['setlang'],
      usage: [{
        name: 'lang',
        type: 'string',
        optional: false,
        choices: [
          'en', 'pt'
        ]
      }],
      options: { guildOnly: true, localeKey: 'settings' }
    })
  }

  async handle ({ msg, args, data }, responder) {
    const lang = args.lang
    try {
      let guild = await data.Guild.fetch(msg.guild.id)
      guild.lang = lang
      await guild.save()
      return responder.success(lang, {
        lang: `**\`${lang}\`**`
      })
    } catch (err) {
      logger.error(`Could not change language for ${msg.guild.name} (${msg.guild.id}) - ${err}`)
      return responder.error()
    }
  }
}

module.exports = Lang
<commit_msg>:bug: Fix incorrect response for lang<commit_after>const logger = require('winston')
const { Command } = require('../../core')

class Lang extends Command {
  constructor (...args) {
    super(...args, {
      name: 'lang',
      description: 'Allows moderators to set a guild\'s language',
      aliases: ['setlang'],
      usage: [{
        name: 'lang',
        type: 'string',
        optional: false,
        choices: [
          'en', 'pt'
        ]
      }],
      options: { guildOnly: true, localeKey: 'settings' }
    })
  }

  async handle ({ msg, args, data }, responder) {
    const lang = args.lang
    try {
      let guild = await data.Guild.fetch(msg.guild.id)
      guild.lang = lang
      await guild.save()
      return responder.success('{{lang.success}}', {
        lang: `**\`${lang}\`**`
      })
    } catch (err) {
      logger.error(`Could not change language for ${msg.guild.name} (${msg.guild.id}) - ${err}`)
      return responder.error()
    }
  }
}

module.exports = Lang
<|endoftext|>


<commit_before>const logger = require('winston')
const { Command } = require('../../core')

class Lang extends Command {
  constructor (...args) {
    super(...args, {
      name: 'lang',
      description: 'Allows moderators to set a guild\'s language',
      aliases: ['setlang'],
      usage: [{
        name: 'lang',
        type: 'string',
        optional: false,
        choices: [
          'en'
        ]
      }],
      options: { guildOnly: true, localeKey: 'settings' }
    })
  }

  async handle ({ msg, args, data }, responder) {
    const lang = args.lang
    try {
      let guild = await data.Guild.fetch(msg.guild.id)
      guild.lang = lang
      await guild.save()
      return responder.success(lang, {
        lang: `**\`${lang}\`**`
      })
    } catch (err) {
      logger.error(`Could not change language for ${msg.guild.name} (${msg.guild.id}) - ${err}`)
      return responder.error()
    }
  }
}

module.exports = Lang
<commit_msg>:rocket: Add pt to lang command<commit_after>const logger = require('winston')
const { Command } = require('../../core')

class Lang extends Command {
  constructor (...args) {
    super(...args, {
      name: 'lang',
      description: 'Allows moderators to set a guild\'s language',
      aliases: ['setlang'],
      usage: [{
        name: 'lang',
        type: 'string',
        optional: false,
        choices: [
          'en', 'pt'
        ]
      }],
      options: { guildOnly: true, localeKey: 'settings' }
    })
  }

  async handle ({ msg, args, data }, responder) {
    const lang = args.lang
    try {
      let guild = await data.Guild.fetch(msg.guild.id)
      guild.lang = lang
      await guild.save()
      return responder.success(lang, {
        lang: `**\`${lang}\`**`
      })
    } catch (err) {
      logger.error(`Could not change language for ${msg.guild.name} (${msg.guild.id}) - ${err}`)
      return responder.error()
    }
  }
}

module.exports = Lang
<|endoftext|>


<commit_before>// Redux stuff
import thunk from 'redux-thunk'
import {createStore, applyMiddleware, compose} from 'redux'
import {routerMiddleware} from 'react-router-redux'
// Application
import rootReducer from 'reducers'
import {routes, history} from 'routing'

/**
 * Configure application store with middlewares.
 * @param  {Object} initialState - preloadedState
 * @return {Object} - configured store
 */
const configureStore = initialState => {
	const thunkApplied = applyMiddleware(thunk)
	const routerMiddlewareApplied = applyMiddleware(routerMiddleware(history))
	let enhancers

	if (process.env.NODE_ENV === 'development') {
		const {composeWithDevTools} = require('redux-devtools-extension')
		enhancers = composeWithDevTools(thunkApplied, routerMiddlewareApplied)
	} else {
		enhancers = compose(thunkApplied, routerMiddlewareApplied)
	}

	return createStore(rootReducer, initialState, enhancers)
}

/**
 * Return configured history, routes and store for the app
 * @param  {Object} initialState
 * @return {Object} Object containting configured store, routes, history
 */
export default ({initialState}) => {
	const store = configureStore(initialState)
	return {
		store,
		routes,
		history
	}
}
<commit_msg>fix(app/configure_app): add flow, fix arg<commit_after>// @flow
// Redux stuff
import thunk from 'redux-thunk'
import {createStore, applyMiddleware, compose} from 'redux'
import {routerMiddleware} from 'react-router-redux'
// Application
import rootReducer from 'reducers'
import {routes, history} from 'routing'

/**
 * Configure application store with middlewares.
 * @param  {Object} initialState - preloadedState
 * @return {Object} - configured store
 */
const configureStore = (initialState: Object) => {
	const thunkApplied = applyMiddleware(thunk)
	const routerMiddlewareApplied = applyMiddleware(routerMiddleware(history))
	let enhancers

	if (process.env.NODE_ENV === 'development') {
		const {composeWithDevTools} = require('redux-devtools-extension')
		enhancers = composeWithDevTools(thunkApplied, routerMiddlewareApplied)
	} else {
		enhancers = compose(thunkApplied, routerMiddlewareApplied)
	}

	return createStore(rootReducer, initialState, enhancers)
}

/**
 * Return configured history, routes and store for the app
 * @param  {Object} initialState
 * @return {Object} Object containting configured store, routes, history
 */
export default (initialState: Object) => {
	const store = configureStore(initialState)
	return {
		store,
		routes,
		history
	}
}
<|endoftext|>


<commit_before>//>>includeStart('strict', pragmas.strict);
/*jslint sloppy:true*/
/*global define*/

define(['./hasDefineProperty'], function (hasDefineProperty) {

    /**
     * Sets the key of object with the specified value.
     * The property is obfuscated, by not being enumerable, configurable and writable.
     *
     * @param {Object}  obj                  The object
     * @param {String}  key                  The key
     * @param {Mixin}   value                The value
     * @param {Boolean} [isWritable="false"] True to be writable, false otherwise
     */
    function obfuscateProperty(obj, key, value, isWritable) {

        if (hasDefineProperty) {
            if (obj.hasOwnProperty(key)) {
                console.log(obj);
                console.trace();
            }
            Object.defineProperty(obj, key, {
                value: value,
                configurable: false,
                writable: isWritable || false,
                enumerable: false
            });
        } else {
            obj[key] = value;
        }
    }

    return obfuscateProperty;
});
//>>includeEnd('strict');
<commit_msg>Remove console.log.<commit_after>//>>includeStart('strict', pragmas.strict);
/*jslint sloppy:true*/
/*global define*/

define(['./hasDefineProperty'], function (hasDefineProperty) {

    /**
     * Sets the key of object with the specified value.
     * The property is obfuscated, by not being enumerable, configurable and writable.
     *
     * @param {Object}  obj                  The object
     * @param {String}  key                  The key
     * @param {Mixin}   value                The value
     * @param {Boolean} [isWritable="false"] True to be writable, false otherwise
     */
    function obfuscateProperty(obj, key, value, isWritable) {

        if (hasDefineProperty) {
            Object.defineProperty(obj, key, {
                value: value,
                configurable: false,
                writable: isWritable || false,
                enumerable: false
            });
        } else {
            obj[key] = value;
        }
    }

    return obfuscateProperty;
});
//>>includeEnd('strict');
<|endoftext|>


<commit_before>import BaseLfo from '../../core/BaseLfo';

const definitions = {
  separateArrays: {
    type: 'boolean',
    default: false,
    constant: true,
  },
  callback: {
    type: 'any',
    default: null,
    nullable: true,
    metas: { kind: 'dynamic' },
  },
};

/**
 * Record input frames from a graph. This sink can handle `signal`, `vector`
 * or `scalar` inputs.
 *
 * When the recording is stopped (either by calling `stop` on the node or when
 * the stream is finalized), the callback given as parameter is executed with
 * the recorder data as argument.
 *
 *
 * @param {Object} options - Override default parameters.
 * @param {Boolean} [options.separateArrays=false] - Format of the retrieved
 *  values:
 *  - when `false`, format is [{ time, data }, { time, data }, ...]
 *  - when `true`, format is { time: [...], data: [...] }
 * @param {Function} [options.callback] - Callback to execute when a new record
 *  is ended. This can happen when: `stop` is called on the recorder, or `stop`
 *  is called on the source.
 *
 * @todo - Add auto record param.
 *
 * @memberof module:common.sink
 *
 * @example
 * import * as lfo from 'waves-lfo/common';
 *
 * const eventIn = new lfo.source.EventIn({
 *  frameType: 'vector',
 *  frameSize: 2,
 *  frameRate: 0,
 * });
 *
 * const recorder = new lfo.sink.DataRecorder({
 *   callback: (data) => console.log(data),
 * });
 *
 * eventIn.connect(recorder);
 * eventIn.start();
 * recorder.start();
 *
 * eventIn.process(0, [0, 1]);
 * eventIn.process(1, [1, 2]);
 *
 * recorder.stop();
 * > [{ time: 0, data: [0, 1] }, { time: 1, data: [1, 2] }];
 */
class DataRecorder extends BaseLfo {
  constructor(options = {}) {
    super(definitions, options);

    /**
     * Define if the node is currently recording.
     *
     * @type {Boolean}
     * @name isRecording
     * @instance
     * @memberof module:sink.SignalRecorder
     */
    this.isRecording = false;
  }

  /** @private */
  _initStore() {
    const separateArrays = this.params.get('separateArrays');

    if (separateArrays)
      this._store = { time: [], data: [] };
    else
      this._store = [];
  }

  /** @private */
  processStreamParams(prevStreamParams) {
    this.prepareStreamParams(prevStreamParams);
    this._initStore();
    this.propagateStreamParams();
  }

  /**
   * Start recording.
   *
   * @see {@link module:client.sink.DataRecorder#stop}
   */
  start() {
    this.isRecording = true;
  }

  /**
   * Stop recording and execute the callback defined in parameters.
   *
   * @see {@link module:client.sink.DataRecorder#start}
   */
  stop() {
    if (this.isRecording) {
      this.isRecording = false;
      const callback = this.params.get('callback');

      if (callback !== null)
        callback(this._store);

      this._initStore();
    }
  }

  /** @private */
  finalizeStream() {
    this.stop();
  }

  // handle any input types
  /** @private */
  processScalar(frame) {}
  /** @private */
  processSignal(frame) {}
  /** @private */
  processVector(frame) {}

  processFrame(frame) {
    if (this.isRecording) {
      this.prepareFrame(frame);

      const separateArrays = this.params.get('separateArrays');
      const entry = {
        time: frame.time,
        data: new Float32Array(frame.data),
      };

      if (!separateArrays) {
        this._store.push(entry);
      } else {
        this._store.time.push(entry.time);
        this._store.data.push(entry.data);
      }
    }
  }
}

export default DataRecorder;

<commit_msg>doc cosmetics<commit_after>import BaseLfo from '../../core/BaseLfo';

const definitions = {
  separateArrays: {
    type: 'boolean',
    default: false,
    constant: true,
  },
  callback: {
    type: 'any',
    default: null,
    nullable: true,
    metas: { kind: 'dynamic' },
  },
};

/**
 * Record input frames from a graph. This sink can handle `signal`, `vector`
 * or `scalar` inputs.
 *
 * When the recording is stopped (either by calling `stop` on the node or when
 * the stream is finalized), the callback given as parameter is executed with
 * the recorder data as argument.
 *
 *
 * @param {Object} options - Override default parameters.
 * @param {Boolean} [options.separateArrays=false] - Format of the retrieved
 *  values:
 *  - when `false`, format is [{ time, data }, { time, data }, ...]
 *  - when `true`, format is { time: [...], data: [...] }
 * @param {Function} [options.callback] - Callback to execute when a new record
 *  is ended. This can happen when:
 *  - `stop` is called on the recorder
 *  - `stop` is called on the source.
 *
 * @todo - Add auto record param.
 *
 * @memberof module:common.sink
 *
 * @example
 * import * as lfo from 'waves-lfo/common';
 *
 * const eventIn = new lfo.source.EventIn({
 *  frameType: 'vector',
 *  frameSize: 2,
 *  frameRate: 0,
 * });
 *
 * const recorder = new lfo.sink.DataRecorder({
 *   callback: (data) => console.log(data),
 * });
 *
 * eventIn.connect(recorder);
 * eventIn.start();
 * recorder.start();
 *
 * eventIn.process(0, [0, 1]);
 * eventIn.process(1, [1, 2]);
 *
 * recorder.stop();
 * > [{ time: 0, data: [0, 1] }, { time: 1, data: [1, 2] }];
 */
class DataRecorder extends BaseLfo {
  constructor(options = {}) {
    super(definitions, options);

    /**
     * Define if the node is currently recording.
     *
     * @type {Boolean}
     * @name isRecording
     * @instance
     * @memberof module:sink.SignalRecorder
     */
    this.isRecording = false;
  }

  /** @private */
  _initStore() {
    const separateArrays = this.params.get('separateArrays');

    if (separateArrays)
      this._store = { time: [], data: [] };
    else
      this._store = [];
  }

  /** @private */
  processStreamParams(prevStreamParams) {
    this.prepareStreamParams(prevStreamParams);
    this._initStore();
    this.propagateStreamParams();
  }

  /**
   * Start recording.
   *
   * @see {@link module:client.sink.DataRecorder#stop}
   */
  start() {
    this.isRecording = true;
  }

  /**
   * Stop recording and execute the callback defined in parameters.
   *
   * @see {@link module:client.sink.DataRecorder#start}
   */
  stop() {
    if (this.isRecording) {
      this.isRecording = false;
      const callback = this.params.get('callback');

      if (callback !== null)
        callback(this._store);

      this._initStore();
    }
  }

  /** @private */
  finalizeStream() {
    this.stop();
  }

  // handle any input types
  /** @private */
  processScalar(frame) {}
  /** @private */
  processSignal(frame) {}
  /** @private */
  processVector(frame) {}

  processFrame(frame) {
    if (this.isRecording) {
      this.prepareFrame(frame);

      const separateArrays = this.params.get('separateArrays');
      const entry = {
        time: frame.time,
        data: new Float32Array(frame.data),
      };

      if (!separateArrays) {
        this._store.push(entry);
      } else {
        this._store.time.push(entry.time);
        this._store.data.push(entry.data);
      }
    }
  }
}

export default DataRecorder;

<|endoftext|>


<commit_before>var colorPicker = {

    start: function() {
        $("#main-canvas").css("cursor", "crosshair");
    },

    mouseDown: function($scope) {
        var x = $scope.config.mouse.current.x;
        var y = $scope.config.mouse.current.x;

        var value = $scope.renderEngine.getPixelColor(x, y);

        /* Write color to config. */
        $scope.config.tools.colors.primary.r = value[0];
        $scope.config.tools.colors.primary.g = value[1];
        $scope.config.tools.colors.primary.b = value[2];
    },

    mouseUp: function($scope) {
    },

    mouseMove: function($scope) {
        // TODO call mouseDown
    },
}<commit_msg>fixed colorpicker in canvas-test<commit_after>var colorPicker = {

    start: function() {
        $("#main-canvas").css("cursor", "crosshair");
    },

    mouseDown: function($scope) {
        var x = $scope.config.mouse.current.x - canvasLocationX;
        var y = $scope.config.mouse.current.y - canvasLocationY;

        var value = $scope.renderEngine.getPixelColor(x, y);

        /* Write color to config. */
        $scope.config.tools.colors.primary.r = value[0];
        $scope.config.tools.colors.primary.g = value[1];
        $scope.config.tools.colors.primary.b = value[2];
    },

    mouseUp: function($scope) {
    },

    mouseMove: function($scope) {
        // TODO call mouseDown
    },
}<|endoftext|>


<commit_before>app.factory('DomainsFactory', ['$resource', function($resource) {
    return $resource('/domain/:id', { id: '@id' }, {
        update: {
            method: 'PUT'
        }
    });
}]);

app.service('Domains', ['$rootScope', '$log', '$q', 'DomainsFactory',
    function($rootScope, $log, $q, DomainsFactory) {
        var service = {};

        service.query = function(ret_func) {
                service.domains = DomainsFactory.query(ret_func);
                return service.domains;
            }
        };

        return service;
    }
]);
<commit_msg>We want to cache the domain information<commit_after>app.factory('DomainsFactory', ['$resource', function($resource) {
    return $resource('/domain/:id', { id: '@id' }, {
        update: {
            method: 'PUT'
        }
    });
}]);

app.service('Domains', ['$rootScope', '$log', '$q', 'DomainsFactory',
    function($rootScope, $log, $q, DomainsFactory) {
        var service = {};

        service.all = [];
        service.query = function(ret_func) {
            if (service.all.length == 0) {
                $log.debug("Fetching list of domains.");
                service.all = DomainsFactory.query(ret_func);

                return service.all;
            }
            else {
                ret_func();
                return service.all;
            }
        };

        return service;
    }
]);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { PromiseState } from 'react-refetch';
import redux from './reflorpRedux';
import refetch from './reflorpRefetch';
import debounce from '../utils/debounce.js';

@refetch((props) => {
  const mapping = {};
  const entityList = props.entities || {};
  if (props.entity) {
    entityList[props.entity] = { id: props.id, parentId: props.parentId, load: props.load, edit: props.edit, extra: props.extra };
  }

  Object.keys(entityList).forEach((entity) => {
    const entityData = entityList[entity];
    if (entityData.load) {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
    }
  });

  return mapping;
})
@redux((state, props) => {
  const mapping = {};
  const entityList = props.entities || {};
  if (props.entity) {
    entityList[props.entity] = { id: props.id, parentId: props.parentId, edit: props.edit, create: props.create, extra: props.extra };
  }

  Object.keys(entityList).forEach((entity) => {
    const entityData = entityList[entity];

    if (entityData.create) {
      entityData.id = '0';
    }

    if (entityData.edit !== false) {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, edit: true, extra: entityData.extra };
      mapping[`${entity}Original`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
      mapping[`${entity}Create`] = true;
      mapping[`${entity}CreateResponse`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}Edit`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}EditDraft`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}EditResponse`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}Delete`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}DeleteResponse`] = { id: entityData.id, parentId: entityData.parentId };
    } else {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, then: entityData.then, extra: entityData.extra };
      mapping[`${entity}Original`] = { id: entityData.id, parentId: entityData.parentId, then: entityData.then, extra: entityData.extra };
    }
    if (entityData.parentId && !entityData.id) {
      mapping[`${entity}LoadMore`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
      mapping[`${entity}LoadMoreResponse`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
    }
  });

  return mapping;
})
class EntityWrapper extends Component {
  static propTypes = {
    onEdit: PropTypes.func,
    onDelete: PropTypes.func,
    onCreate: PropTypes.func,
    children: PropTypes.node,
    parentId: PropTypes.any,
    id: PropTypes.any,
    entity: PropTypes.string,
    entities: PropTypes.object,
    hideUntilLoaded: PropTypes.bool,
  };

  static defaultProps = {
    hideUntilLoaded: false,
  };

  constructor() {
    super();

    this.state = {
      created: {},
      edited: {},
      deleted: {},
    };
  }

  componentWillReceiveProps(nextProps) {
    const { onCreate, onEdit, onDelete, entity, entities, id, parentId } = nextProps;
    const { edited, deleted, created } = this.state;

    const entityList = entities || {};
    if (entity) {
      entityList[entity] = { id, parentId };
    }

    Object.keys(entityList).forEach((entityKey) => {
      const createResponse = nextProps[`${entityKey}CreateResponse`];
      const editResponse = nextProps[`${entityKey}EditResponse`];
      const deleteResponse = nextProps[`${entityKey}DeleteResponse`];

      if (createResponse) {
        if (createResponse.fulfilled) {
          if (onCreate && !created[entityKey]) {
            const newCreated = { ...created };
            const value = createResponse.value;
            newCreated[entityKey] = true;
            this.setState({
              created: newCreated,
            }, () => onCreate(value));
          }
        } else {
          const newCreated = { ...created };
          delete newCreated[entityKey];
          this.setState({
            created: newCreated,
          });
        }
      }

      if (editResponse) {
        if (editResponse.fulfilled) {
          if (onEdit && !edited[entityKey]) {
            const newEdited = { ...edited };
            const value = editResponse.value;
            newEdited[entityKey] = true;
            this.setState({
              edited: newEdited,
            }, () => onEdit(value));
          }
        } else {
          const newEdited = { ...edited };
          delete newEdited[entityKey];
          this.setState({
            edited: newEdited,
          });
        }
      }

      if (deleteResponse) {
        if (deleteResponse.fulfilled) {
          if (onDelete && !deleted[entityKey]) {
            const newDeleted = { ...deleted };
            const value = entityList[entityKey];
            newDeleted[entityKey] = true;
            this.setState({
              deleted: newDeleted,
            }, () => onDelete(value));
          }
        } else {
          const newDeleted = { ...deleted };
          delete newDeleted[entityKey];
          this.setState({
            deleted: newDeleted,
          });
        }
      }
    });
  }

  render() {
    const { children, entity, entities, id, parentId, className, hideUntilLoaded } = this.props;

    const entityList = entities || {};
    if (entity) {
      entityList[entity] = { id, parentId };
    }

    const datas = {};
    const saved = {};
    const loadMores = {};
    const loadMoreResponses = {};
    const edits = {};
    const editDrafts = {};
    const deletes = {};
    const responses = [];
    const dataResponses = [];
    const createResponses = [];
    const deleteResponses = [];
    const editResponses = [];
    Object.keys(entityList).forEach((entityKey) => {
      const createResponse = this.props[`${entityKey}CreateResponse`];
      const editResponse = this.props[`${entityKey}EditResponse`];
      const deleteResponse = this.props[`${entityKey}DeleteResponse`];
      const data = this.props[entityKey];

      if (data) {
        datas[entityKey] = data.value;
        saved[entityKey] = data.saved;
        responses.push(data);
        dataResponses.push(data);
      }

      if (this.props[`${entityKey}LoadMore`]) {
        loadMores[entityKey] = this.props[`${entityKey}LoadMore`];
        const loadMoreResponse = this.props[`${entityKey}LoadMoreResponse`];
        if (loadMoreResponse) {
          loadMoreResponses[entityKey] = loadMoreResponse;
          responses.push(loadMoreResponse);
        }
      }
      if (this.props[`${entityKey}Edit`]) {
        if (this.props[`${entityKey}Original`]) {
          datas[`${entityKey}Original`] = this.props[`${entityKey}Original`].value;
        }
        edits[entityKey] = this.props[`${entityKey}Edit`];
        editDrafts[entityKey] = this.props[`${entityKey}EditDraft`];
        deletes[entityKey] = this.props[`${entityKey}Delete`];
      }
      if (createResponse) {
        createResponses.push(createResponse);
        responses.push(createResponse);
      }
      if (editResponse) {
        editResponses.push(editResponse);
        responses.push(editResponse);
      }
      if (deleteResponse) {
        deleteResponses.push(deleteResponse);
        responses.push(deleteResponse);
      }
    });

    const allResponses = PromiseState.all(responses);
    const dataResponsesPs = PromiseState.all(dataResponses);
    const error = (allResponses && allResponses.rejected ? allResponses.reason.message : '');

    if (!children) {
      return null;
    }

    const childProps = {
      data: (entity ? datas[entity] : datas),
      saved: (entity ? saved[entity] : saved),
      error,
      loading: (allResponses && (allResponses.pending || allResponses.refreshing) ? true : false),
      hasData: (dataResponsesPs && dataResponsesPs.fulfilled ? true : false),
    };

    if (entity) {
      childProps.doLoadMore = loadMores[entity];
      childProps.doEdit = edits[entity];
      childProps.doEditDraft = editDrafts[entity];
      childProps.doDelete = deletes[entity];
    } else {
      childProps.doLoadMore = loadMores;
      childProps.doEdit = edits;
      childProps.doEditDraft = editDrafts;
      childProps.doDelete = deletes;
    }
    childProps.loadMoreResponse = (loadMoreResponses ? PromiseState.all(loadMoreResponses) : false);
    childProps.deleteResponse = (deleteResponses ? PromiseState.all(deleteResponses) : false);
    childProps.editResponse = (editResponses ? PromiseState.all(editResponses) : false);

    childProps.saveAll = () => {
      Object.keys(edits).forEach((entityKey) => {
        edits[entityKey](datas[entityKey]);
      });
    };

    childProps.handleChange = (e) => {
      const name = e.target.name;

      let value;

      if (e.target.type === 'checkbox') {
        value = !!e.target.checked;
      } else {
        value = e.target.value;
      }

      if (name) {
        if (name.indexOf('.') !== -1) {
          const [ myEntity, field ] = name.split('.');
          const newData = { ...datas[myEntity] };
          newData[field] = value;
          editDrafts[myEntity](newData);
        } else {
          const newData = { ...datas[entity] };
          newData[e.target.name] = value;
          editDrafts[entity](newData);
        }
      }
    };

    childProps.handleChangeDebounced = (wait = 50) => {
      const debouncedChange = debounce(childProps.handleChange, wait);

      return (e) => {
        if (e.persist) {
          e.persist();
        }

        debouncedChange(e);
      }
    };

    return (
      <div className={[ (className ? className : ''), 'reflorp-loader', (allResponses && (allResponses.pending || allResponses.refreshing) ? 'reflorp-loader-loading' : '') ].join(' ')}>
        {(childProps.hasData || !hideUntilLoaded ? React.cloneElement(React.Children.only(children), childProps) : <noscript />)}
      </div>
    );
  }
}

export default EntityWrapper;
<commit_msg>only send create and create response when create option is active<commit_after>import React, { Component, PropTypes } from 'react';
import { PromiseState } from 'react-refetch';
import redux from './reflorpRedux';
import refetch from './reflorpRefetch';
import debounce from '../utils/debounce.js';

@refetch((props) => {
  const mapping = {};
  const entityList = props.entities || {};
  if (props.entity) {
    entityList[props.entity] = { id: props.id, parentId: props.parentId, load: props.load, edit: props.edit, extra: props.extra };
  }

  Object.keys(entityList).forEach((entity) => {
    const entityData = entityList[entity];
    if (entityData.load) {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
    }
  });

  return mapping;
})
@redux((state, props) => {
  const mapping = {};
  const entityList = props.entities || {};
  if (props.entity) {
    entityList[props.entity] = { id: props.id, parentId: props.parentId, edit: props.edit, create: props.create, extra: props.extra };
  }

  Object.keys(entityList).forEach((entity) => {
    const entityData = entityList[entity];

    if (entityData.create) {
      entityData.id = '0';
    }

    if (entityData.edit !== false) {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, edit: true, extra: entityData.extra };
      mapping[`${entity}Original`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
      mapping[`${entity}Edit`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}EditDraft`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}EditResponse`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}Delete`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}DeleteResponse`] = { id: entityData.id, parentId: entityData.parentId };
    } else {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, then: entityData.then, extra: entityData.extra };
      mapping[`${entity}Original`] = { id: entityData.id, parentId: entityData.parentId, then: entityData.then, extra: entityData.extra };
    }
    if (entityData.create) {
      mapping[`${entity}Create`] = true;
      mapping[`${entity}CreateResponse`] = { id: entityData.id, parentId: entityData.parentId };
    }
    if (entityData.parentId && !entityData.id) {
      mapping[`${entity}LoadMore`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
      mapping[`${entity}LoadMoreResponse`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
    }
  });

  return mapping;
})
class EntityWrapper extends Component {
  static propTypes = {
    onEdit: PropTypes.func,
    onDelete: PropTypes.func,
    onCreate: PropTypes.func,
    children: PropTypes.node,
    parentId: PropTypes.any,
    id: PropTypes.any,
    entity: PropTypes.string,
    entities: PropTypes.object,
    hideUntilLoaded: PropTypes.bool,
  };

  static defaultProps = {
    hideUntilLoaded: false,
  };

  constructor() {
    super();

    this.state = {
      created: {},
      edited: {},
      deleted: {},
    };
  }

  componentWillReceiveProps(nextProps) {
    const { onCreate, onEdit, onDelete, entity, entities, id, parentId } = nextProps;
    const { edited, deleted, created } = this.state;

    const entityList = entities || {};
    if (entity) {
      entityList[entity] = { id, parentId };
    }

    Object.keys(entityList).forEach((entityKey) => {
      const createResponse = nextProps[`${entityKey}CreateResponse`];
      const editResponse = nextProps[`${entityKey}EditResponse`];
      const deleteResponse = nextProps[`${entityKey}DeleteResponse`];

      if (createResponse) {
        if (createResponse.fulfilled) {
          if (onCreate && !created[entityKey]) {
            const newCreated = { ...created };
            const value = createResponse.value;
            newCreated[entityKey] = true;
            this.setState({
              created: newCreated,
            }, () => onCreate(value));
          }
        } else {
          const newCreated = { ...created };
          delete newCreated[entityKey];
          this.setState({
            created: newCreated,
          });
        }
      }

      if (editResponse) {
        if (editResponse.fulfilled) {
          if (onEdit && !edited[entityKey]) {
            const newEdited = { ...edited };
            const value = editResponse.value;
            newEdited[entityKey] = true;
            this.setState({
              edited: newEdited,
            }, () => onEdit(value));
          }
        } else {
          const newEdited = { ...edited };
          delete newEdited[entityKey];
          this.setState({
            edited: newEdited,
          });
        }
      }

      if (deleteResponse) {
        if (deleteResponse.fulfilled) {
          if (onDelete && !deleted[entityKey]) {
            const newDeleted = { ...deleted };
            const value = entityList[entityKey];
            newDeleted[entityKey] = true;
            this.setState({
              deleted: newDeleted,
            }, () => onDelete(value));
          }
        } else {
          const newDeleted = { ...deleted };
          delete newDeleted[entityKey];
          this.setState({
            deleted: newDeleted,
          });
        }
      }
    });
  }

  render() {
    const { children, entity, entities, id, parentId, className, hideUntilLoaded } = this.props;

    const entityList = entities || {};
    if (entity) {
      entityList[entity] = { id, parentId };
    }

    const datas = {};
    const saved = {};
    const loadMores = {};
    const loadMoreResponses = {};
    const edits = {};
    const editDrafts = {};
    const deletes = {};
    const responses = [];
    const dataResponses = [];
    const createResponses = [];
    const deleteResponses = [];
    const editResponses = [];
    Object.keys(entityList).forEach((entityKey) => {
      const createResponse = this.props[`${entityKey}CreateResponse`];
      const editResponse = this.props[`${entityKey}EditResponse`];
      const deleteResponse = this.props[`${entityKey}DeleteResponse`];
      const data = this.props[entityKey];

      if (data) {
        datas[entityKey] = data.value;
        saved[entityKey] = data.saved;
        responses.push(data);
        dataResponses.push(data);
      }

      if (this.props[`${entityKey}LoadMore`]) {
        loadMores[entityKey] = this.props[`${entityKey}LoadMore`];
        const loadMoreResponse = this.props[`${entityKey}LoadMoreResponse`];
        if (loadMoreResponse) {
          loadMoreResponses[entityKey] = loadMoreResponse;
          responses.push(loadMoreResponse);
        }
      }
      if (this.props[`${entityKey}Edit`]) {
        if (this.props[`${entityKey}Original`]) {
          datas[`${entityKey}Original`] = this.props[`${entityKey}Original`].value;
        }
        edits[entityKey] = this.props[`${entityKey}Edit`];
        editDrafts[entityKey] = this.props[`${entityKey}EditDraft`];
        deletes[entityKey] = this.props[`${entityKey}Delete`];
      }
      if (createResponse) {
        createResponses.push(createResponse);
        responses.push(createResponse);
      }
      if (editResponse) {
        editResponses.push(editResponse);
        responses.push(editResponse);
      }
      if (deleteResponse) {
        deleteResponses.push(deleteResponse);
        responses.push(deleteResponse);
      }
    });

    const allResponses = PromiseState.all(responses);
    const dataResponsesPs = PromiseState.all(dataResponses);
    const error = (allResponses && allResponses.rejected ? allResponses.reason.message : '');

    if (!children) {
      return null;
    }

    const childProps = {
      data: (entity ? datas[entity] : datas),
      saved: (entity ? saved[entity] : saved),
      error,
      loading: (allResponses && (allResponses.pending || allResponses.refreshing) ? true : false),
      hasData: (dataResponsesPs && dataResponsesPs.fulfilled ? true : false),
    };

    if (entity) {
      childProps.doLoadMore = loadMores[entity];
      childProps.doEdit = edits[entity];
      childProps.doEditDraft = editDrafts[entity];
      childProps.doDelete = deletes[entity];
    } else {
      childProps.doLoadMore = loadMores;
      childProps.doEdit = edits;
      childProps.doEditDraft = editDrafts;
      childProps.doDelete = deletes;
    }
    childProps.loadMoreResponse = (loadMoreResponses ? PromiseState.all(loadMoreResponses) : false);
    childProps.deleteResponse = (deleteResponses ? PromiseState.all(deleteResponses) : false);
    childProps.editResponse = (editResponses ? PromiseState.all(editResponses) : false);

    childProps.saveAll = () => {
      Object.keys(edits).forEach((entityKey) => {
        edits[entityKey](datas[entityKey]);
      });
    };

    childProps.handleChange = (e) => {
      const name = e.target.name;

      let value;

      if (e.target.type === 'checkbox') {
        value = !!e.target.checked;
      } else {
        value = e.target.value;
      }

      if (name) {
        if (name.indexOf('.') !== -1) {
          const [ myEntity, field ] = name.split('.');
          const newData = { ...datas[myEntity] };
          newData[field] = value;
          editDrafts[myEntity](newData);
        } else {
          const newData = { ...datas[entity] };
          newData[e.target.name] = value;
          editDrafts[entity](newData);
        }
      }
    };

    childProps.handleChangeDebounced = (wait = 50) => {
      const debouncedChange = debounce(childProps.handleChange, wait);

      return (e) => {
        if (e.persist) {
          e.persist();
        }

        debouncedChange(e);
      }
    };

    return (
      <div className={[ (className ? className : ''), 'reflorp-loader', (allResponses && (allResponses.pending || allResponses.refreshing) ? 'reflorp-loader-loading' : '') ].join(' ')}>
        {(childProps.hasData || !hideUntilLoaded ? React.cloneElement(React.Children.only(children), childProps) : <noscript />)}
      </div>
    );
  }
}

export default EntityWrapper;
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { PromiseState } from 'react-refetch';
import redux from './reflorpRedux';
import refetch from './reflorpRefetch';

@refetch((props) => {
  const mapping = {};
  const entityList = props.entities || {};
  if (props.entity) {
    entityList[props.entity] = { id: props.id, parentId: props.parentId, load: props.load, edit: props.edit, extra: props.extra };
  }

  Object.keys(entityList).forEach((entity) => {
    const entityData = entityList[entity];
    if (entityData.load) {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
    }
  });

  return mapping;
})
@redux((state, props) => {
  const mapping = {};
  const entityList = props.entities || {};
  if (props.entity) {
    entityList[props.entity] = { id: props.id, parentId: props.parentId };
  }

  Object.keys(entityList).forEach((entity) => {
    const entityData = entityList[entity];
    if (entityData.edit !== false) {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, edit: true };
      mapping[`${entity}Edit`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}EditDraft`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}EditResponse`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}Delete`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}DeleteResponse`] = { id: entityData.id, parentId: entityData.parentId };
    } else {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId };
    }
    mapping[`${entity}LoadMore`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
    mapping[`${entity}LoadMoreResponse`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
  });

  return mapping;
})
class EntityWrapper extends Component {
  static propTypes = {
    onEdit: PropTypes.func,
    onDelete: PropTypes.func,
    children: PropTypes.node,
    parentId: PropTypes.any,
    id: PropTypes.any,
    entity: PropTypes.string,
    entities: PropTypes.object,
  };

  constructor() {
    super();

    this.state = {
      edited: false,
      deleted: false,
    };
  }

  componentWillReceiveProps(nextProps) {
    const { onEdit, onDelete, entity, entities, id, parentId } = nextProps;
    const { edited, deleted } = this.state;

    const entityList = entities || {};
    if (entity) {
      entityList[entity] = { id, parentId };
    }

    Object.keys(entityList).forEach((entityKey) => {
      const editResponse = nextProps[`${entityKey}EditResponse`];
      const deleteResponse = nextProps[`${entityKey}DeleteResponse`];

      if (editResponse) {
        if (editResponse.fulfilled) {
          if (onEdit && !edited) {
            this.setState({
              edited: true,
            }, onEdit);
          }
        } else {
          this.setState({
            edited: false,
          });
        }
      }

      if (deleteResponse) {
        if (deleteResponse.fulfilled) {
          if (onDelete && !deleted) {
            this.setState({
              deleted: true,
            }, onDelete);
          }
        } else {
          this.setState({
            deleted: false,
          });
        }
      }
    });
  }

  render() {
    const { children, entity, entities, id, parentId, className } = this.props;

    const entityList = entities || {};
    if (entity) {
      entityList[entity] = { id, parentId };
    }

    const datas = {};
    const loadMores = {};
    const loadMoreResponses = {};
    const edits = {};
    const editDrafts = {};
    const deletes = {};
    const responses = [];
    const dataResponses = [];
    const deleteResponses = [];
    const editResponses = [];
    Object.keys(entityList).forEach((entityKey) => {
      const editResponse = this.props[`${entityKey}EditResponse`];
      const deleteResponse = this.props[`${entityKey}DeleteResponse`];
      const data = this.props[entityKey];

      if (data) {
        datas[entityKey] = data.value;
        responses.push(data);
        dataResponses.push(data);
      }

      if (this.props[`${entityKey}LoadMore`]) {
        loadMores[entityKey] = this.props[`${entityKey}LoadMore`];
        const loadMoreResponse = this.props[`${entityKey}LoadMoreResponse`];
        if (loadMoreResponse) {
          loadMoreResponses[entityKey] = loadMoreResponse;
          responses.push(loadMoreResponse);
        }
      }
      if (this.props[`${entityKey}Edit`]) {
        edits[entityKey] = this.props[`${entityKey}Edit`];
        editDrafts[entityKey] = this.props[`${entityKey}EditDraft`];
        deletes[entityKey] = this.props[`${entityKey}Delete`];
      }
      if (editResponse) {
        editResponses.push(editResponse);
        responses.push(editResponse);
      }
      if (deleteResponse) {
        deleteResponses.push(deleteResponse);
        responses.push(deleteResponse);
      }
    });

    const allResponses = PromiseState.all(responses);
    const dataResponsesPs = PromiseState.all(dataResponses);
    const error = (allResponses && allResponses.rejected ? allResponses.reason.message : '');

    if (!children) {
      return null;
    }

    const childProps = {
      data: (entity ? datas[entity] : datas),
      error,
      loading: (allResponses && allResponses.pending ? true : false),
      hasData: (dataResponsesPs && dataResponsesPs.fulfilled ? true : false),
    };

    if (entity) {
      childProps.doLoadMore = loadMores[entity];
      childProps.doEdit = edits[entity];
      childProps.doEditDraft = editDrafts[entity];
      childProps.doDelete = deletes[entity];
    } else {
      childProps.doLoadMore = loadMores;
      childProps.doEdit = edits;
      childProps.doEditDraft = editDrafts;
      childProps.doDelete = deletes;
    }
    childProps.loadMoreResponse = (loadMoreResponses ? PromiseState.all(loadMoreResponses) : false);
    childProps.deleteResponse = (deleteResponses ? PromiseState.all(deleteResponses) : false);
    childProps.editResponse = (editResponses ? PromiseState.all(editResponses) : false);

    childProps.saveAll = () => {
      Object.keys(edits).forEach((entityKey) => {
        edits[entityKey](datas[entityKey]);
      });
    };

    childProps.handleChange = (e) => {
      const name = e.target.name;

      let value;

      if (e.target.type === 'checkbox') {
        value = !!e.target.checked;
      } else {
        value = e.target.value;
      }

      if (name) {
        if (name.indexOf('.') !== -1) {
          const [ myEntity, field ] = name.split('.');
          const newData = { ...datas[myEntity] };
          newData[field] = value;
          editDrafts[myEntity](newData);
        } else {
          const newData = { ...datas[entity] };
          newData[e.target.name] = value;
          editDrafts[entity](newData);
        }
      }
    };

    const element = React.cloneElement(React.Children.only(children), childProps);

    return (

        {element}

    );
  }
}

export default EntityWrapper;
<commit_msg>only inject LoadMore stuff if we're fetching a list<commit_after>import React, { Component, PropTypes } from 'react';
import { PromiseState } from 'react-refetch';
import redux from './reflorpRedux';
import refetch from './reflorpRefetch';

@refetch((props) => {
  const mapping = {};
  const entityList = props.entities || {};
  if (props.entity) {
    entityList[props.entity] = { id: props.id, parentId: props.parentId, load: props.load, edit: props.edit, extra: props.extra };
  }

  Object.keys(entityList).forEach((entity) => {
    const entityData = entityList[entity];
    if (entityData.load) {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
    }
  });

  return mapping;
})
@redux((state, props) => {
  const mapping = {};
  const entityList = props.entities || {};
  if (props.entity) {
    entityList[props.entity] = { id: props.id, parentId: props.parentId };
  }

  Object.keys(entityList).forEach((entity) => {
    const entityData = entityList[entity];
    if (entityData.edit !== false) {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId, edit: true };
      mapping[`${entity}Edit`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}EditDraft`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}EditResponse`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}Delete`] = { id: entityData.id, parentId: entityData.parentId };
      mapping[`${entity}DeleteResponse`] = { id: entityData.id, parentId: entityData.parentId };
    } else {
      mapping[entity] = { id: entityData.id, parentId: entityData.parentId };
    }
    if (entityData.parentId && !entityData.id) {
      mapping[`${entity}LoadMore`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
      mapping[`${entity}LoadMoreResponse`] = { id: entityData.id, parentId: entityData.parentId, extra: entityData.extra };
    }
  });

  return mapping;
})
class EntityWrapper extends Component {
  static propTypes = {
    onEdit: PropTypes.func,
    onDelete: PropTypes.func,
    children: PropTypes.node,
    parentId: PropTypes.any,
    id: PropTypes.any,
    entity: PropTypes.string,
    entities: PropTypes.object,
  };

  constructor() {
    super();

    this.state = {
      edited: false,
      deleted: false,
    };
  }

  componentWillReceiveProps(nextProps) {
    const { onEdit, onDelete, entity, entities, id, parentId } = nextProps;
    const { edited, deleted } = this.state;

    const entityList = entities || {};
    if (entity) {
      entityList[entity] = { id, parentId };
    }

    Object.keys(entityList).forEach((entityKey) => {
      const editResponse = nextProps[`${entityKey}EditResponse`];
      const deleteResponse = nextProps[`${entityKey}DeleteResponse`];

      if (editResponse) {
        if (editResponse.fulfilled) {
          if (onEdit && !edited) {
            this.setState({
              edited: true,
            }, onEdit);
          }
        } else {
          this.setState({
            edited: false,
          });
        }
      }

      if (deleteResponse) {
        if (deleteResponse.fulfilled) {
          if (onDelete && !deleted) {
            this.setState({
              deleted: true,
            }, onDelete);
          }
        } else {
          this.setState({
            deleted: false,
          });
        }
      }
    });
  }

  render() {
    const { children, entity, entities, id, parentId, className } = this.props;

    const entityList = entities || {};
    if (entity) {
      entityList[entity] = { id, parentId };
    }

    const datas = {};
    const loadMores = {};
    const loadMoreResponses = {};
    const edits = {};
    const editDrafts = {};
    const deletes = {};
    const responses = [];
    const dataResponses = [];
    const deleteResponses = [];
    const editResponses = [];
    Object.keys(entityList).forEach((entityKey) => {
      const editResponse = this.props[`${entityKey}EditResponse`];
      const deleteResponse = this.props[`${entityKey}DeleteResponse`];
      const data = this.props[entityKey];

      if (data) {
        datas[entityKey] = data.value;
        responses.push(data);
        dataResponses.push(data);
      }

      if (this.props[`${entityKey}LoadMore`]) {
        loadMores[entityKey] = this.props[`${entityKey}LoadMore`];
        const loadMoreResponse = this.props[`${entityKey}LoadMoreResponse`];
        if (loadMoreResponse) {
          loadMoreResponses[entityKey] = loadMoreResponse;
          responses.push(loadMoreResponse);
        }
      }
      if (this.props[`${entityKey}Edit`]) {
        edits[entityKey] = this.props[`${entityKey}Edit`];
        editDrafts[entityKey] = this.props[`${entityKey}EditDraft`];
        deletes[entityKey] = this.props[`${entityKey}Delete`];
      }
      if (editResponse) {
        editResponses.push(editResponse);
        responses.push(editResponse);
      }
      if (deleteResponse) {
        deleteResponses.push(deleteResponse);
        responses.push(deleteResponse);
      }
    });

    const allResponses = PromiseState.all(responses);
    const dataResponsesPs = PromiseState.all(dataResponses);
    const error = (allResponses && allResponses.rejected ? allResponses.reason.message : '');

    if (!children) {
      return null;
    }

    const childProps = {
      data: (entity ? datas[entity] : datas),
      error,
      loading: (allResponses && allResponses.pending ? true : false),
      hasData: (dataResponsesPs && dataResponsesPs.fulfilled ? true : false),
    };

    if (entity) {
      childProps.doLoadMore = loadMores[entity];
      childProps.doEdit = edits[entity];
      childProps.doEditDraft = editDrafts[entity];
      childProps.doDelete = deletes[entity];
    } else {
      childProps.doLoadMore = loadMores;
      childProps.doEdit = edits;
      childProps.doEditDraft = editDrafts;
      childProps.doDelete = deletes;
    }
    childProps.loadMoreResponse = (loadMoreResponses ? PromiseState.all(loadMoreResponses) : false);
    childProps.deleteResponse = (deleteResponses ? PromiseState.all(deleteResponses) : false);
    childProps.editResponse = (editResponses ? PromiseState.all(editResponses) : false);

    childProps.saveAll = () => {
      Object.keys(edits).forEach((entityKey) => {
        edits[entityKey](datas[entityKey]);
      });
    };

    childProps.handleChange = (e) => {
      const name = e.target.name;

      let value;

      if (e.target.type === 'checkbox') {
        value = !!e.target.checked;
      } else {
        value = e.target.value;
      }

      if (name) {
        if (name.indexOf('.') !== -1) {
          const [ myEntity, field ] = name.split('.');
          const newData = { ...datas[myEntity] };
          newData[field] = value;
          editDrafts[myEntity](newData);
        } else {
          const newData = { ...datas[entity] };
          newData[e.target.name] = value;
          editDrafts[entity](newData);
        }
      }
    };

    const element = React.cloneElement(React.Children.only(children), childProps);

    return (

        {element}

    );
  }
}

export default EntityWrapper;
<|endoftext|>