<commit_before>let listenAction

export default {
  bind(el, binding) {
    const params = binding.value || {}

    const stickyTop = params.stickyTop || 0
    const zIndex = params.zIndex || 1000

    el.style.position = '-webkit-sticky'
    el.style.position = 'sticky'

    // if the browser support css sticky（Currently Safari, Firefox and Chrome Canary）
    if (~el.style.position.indexOf('sticky')) {
      el.style.top = `${stickyTop}px`
      el.style.zIndex = zIndex
      return
    }

    const elementChild = el.firstElementChild
    elementChild.style.cssText = `left: 0; right: 0; top: ${stickyTop}px; index: ${zIndex}`

    let active = false

    const sticky = () => {
      if (active) {
        return
      }
      if (!el.style.height) {
        el.style.height = el.offsetHeight + 'px'
      }
      elementChild.style.position = 'fixed'
      active = true
    }

    const reset = () => {
      if (!active) {
        return
      }
      elementChild.style.position = ''
      active = false
    }

    const check = () => {
      const offsetTop = el.getBoundingClientRect().top
      if (offsetTop <= stickyTop) {
        sticky()
      } else {
        reset()
      }
    }

    let scrollerTimer // for bad user experience scroll in mobile
    let scrollEndTimer // for clear scrollerTimer when scroll end
    listenAction = () => {
      clearTimeout(scrollEndTimer)
      scrollEndTimer = setTimeout(() => {
        clearInterval(scrollerTimer)
        scrollerTimer = null
      }, 1000)

      if (!scrollerTimer) {
        scrollerTimer = setInterval(check, 30)
      }
    }

    window.addEventListener('scroll', listenAction)
  },

  unbind() {
    window.removeEventListener('scroll', listenAction)
  },
}
<commit_msg>code enhancements (#4)<commit_after>let listenAction

export default {
  bind(el, binding) {
    const params = binding.value || {},
      stickyTop = params.stickyTop || 0,
      zIndex = params.zIndex || 1000,
      elStyle = el.style

    elStyle.position = '-webkit-sticky'
    elStyle.position = 'sticky'

    // if the browser support css sticky（Currently Safari, Firefox and Chrome Canary）
    if (~elStyle.position.indexOf('sticky')) {
      elStyle.top = `${stickyTop}px`
      elStyle.zIndex = zIndex
      return
    }

    const elementChild = el.firstElementChild.style
    elementChild.cssText = `left: 0; right: 0; top: ${stickyTop}px; index: ${zIndex}`

    let active = false

    const sticky = () => {
      if (active) {
        return
      }
      if (!elStyle.height) {
        elStyle.height = `${el.offsetHeight}px`
      }
      elementChild.position = 'fixed'
      active = true
    }

    const reset = () => {
      if (!active) {
        return
      }
      elementChild.position = ''
      active = false
    }

    const check = () => {
      const offsetTop = el.getBoundingClientRect().top
      if (offsetTop <= stickyTop) {
        sticky()
        return
      }
      reset()
    }

    listenAction = () => {
      setTimeout(check, 300);
    }

    window.addEventListener('scroll', listenAction)
  },

  unbind() {
    window.removeEventListener('scroll', listenAction)
  },
}
<|endoftext|>


<commit_before>/**
*
* ReportList
*
*/

import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import styled from 'styled-components';
import format from 'date-fns/format';

import { grey500 as unitColor } from 'material-ui/styles/colors';

import {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHeaderColumn,
  TableRowColumn,
} from 'material-ui/Table';

import ListPlaceholder from 'components/ListPlaceholder';

import messages from './messages';

const Unit = styled.span`
  color: ${unitColor};
`;

class ReportList extends React.Component { // eslint-disable-line react/prefer-stateless-function
  TableHeader = () => (
    <TableHeader
      displaySelectAll={false}
      adjustForCheckbox={false}
    >
      <TableRow>
        <TableHeaderColumn colSpan="4">
          <FormattedMessage {...messages.header} />
        </TableHeaderColumn>
      </TableRow>
      <TableRow>
        <TableHeaderColumn>
          <FormattedMessage {...messages.createdAt} />
        </TableHeaderColumn>
        <TableHeaderColumn>
          <FormattedMessage {...messages.hotWater} />
        </TableHeaderColumn>
        <TableHeaderColumn>
          <FormattedMessage {...messages.coldWater} />
        </TableHeaderColumn>
        <TableHeaderColumn>
          <FormattedMessage {...messages.heat} />
        </TableHeaderColumn>
      </TableRow>
    </TableHeader>
  )

  TableBody = (reports) => (
    <TableBody displayRowCheckbox={false}>
      {reports.map((report) => (
        <TableRow key={report.id}>
          {this.TableRowColumn(format(report.createdAt, 'YYYY MMM D'))}
          {this.TableRowColumn(report.hotWater, (m3))}
          {this.TableRowColumn(report.coldWater, (m3))}
          {this.TableRowColumn(report.heat, 'kWh')}
        </TableRow>
      ))}
    </TableBody>
  )

  TableRowColumn = (label, unit) => (
    <TableRowColumn>
      {label}{unit ? (<Unit> {unit}</Unit>) : null}
    </TableRowColumn>
  )

  render() {
    if (!this.props.reports.length && this.props.placeholder) {
      return (
        <ListPlaceholder>
          {this.props.placeholder}
        </ListPlaceholder>
      );
    }

    return (

        {this.TableHeader()}
        {this.TableBody(this.props.reports)}

    );
  }
}

ReportList.propTypes = {
  reports: PropTypes.array.isRequired,
  placeholder: PropTypes.node,
};

export default ReportList;
<commit_msg>use CubicMeter component in report table<commit_after>/**
*
* ReportList
*
*/

import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import styled from 'styled-components';
import format from 'date-fns/format';

import { grey500 as unitColor } from 'material-ui/styles/colors';

import {
  Table,
  TableHeader,
  TableBody,
  TableRow,
  TableHeaderColumn,
  TableRowColumn,
} from 'material-ui/Table';

import ListPlaceholder from 'components/ListPlaceholder';
import CubicMeter from 'components/CubicMeter';

import messages from './messages';

const Unit = styled.span`
  color: ${unitColor};
`;

class ReportList extends React.Component { // eslint-disable-line react/prefer-stateless-function
  TableHeader = () => (
    <TableHeader
      displaySelectAll={false}
      adjustForCheckbox={false}
    >
      <TableRow>
        <TableHeaderColumn colSpan="4">
          <FormattedMessage {...messages.header} />
        </TableHeaderColumn>
      </TableRow>
      <TableRow>
        <TableHeaderColumn>
          <FormattedMessage {...messages.createdAt} />
        </TableHeaderColumn>
        <TableHeaderColumn>
          <FormattedMessage {...messages.hotWater} />
        </TableHeaderColumn>
        <TableHeaderColumn>
          <FormattedMessage {...messages.coldWater} />
        </TableHeaderColumn>
        <TableHeaderColumn>
          <FormattedMessage {...messages.heat} />
        </TableHeaderColumn>
      </TableRow>
    </TableHeader>
  )

  TableBody = (reports) => (
    <TableBody displayRowCheckbox={false}>
      {reports.map((report) => (
        <TableRow key={report.id}>
          {this.TableRowColumn(format(report.createdAt, 'YYYY MMM D'))}
          {this.TableRowColumn(report.hotWater, <CubicMeter />)}
          {this.TableRowColumn(report.coldWater, <CubicMeter />)}
          {this.TableRowColumn(report.heat, 'kWh')}
        </TableRow>
      ))}
    </TableBody>
  )

  TableRowColumn = (label, unit) => (
    <TableRowColumn>
      {label}{unit ? (<Unit> {unit}</Unit>) : null}
    </TableRowColumn>
  )

  render() {
    if (!this.props.reports.length && this.props.placeholder) {
      return (
        <ListPlaceholder>
          {this.props.placeholder}
        </ListPlaceholder>
      );
    }

    return (

        {this.TableHeader()}
        {this.TableBody(this.props.reports)}

    );
  }
}

ReportList.propTypes = {
  reports: PropTypes.array.isRequired,
  placeholder: PropTypes.node,
};

export default ReportList;
<|endoftext|>


<commit_before>// @flow

type Cancel = () => void
type Handler<-T> = (x: T) => void
type Handlers<-S, -F> = {
  success: Handler<S>,
  failure: Handler<F>,
  catch?: Handler<any>,
}
type LooseHandlers<-S, -F> = Handler<S> | {
  success?: Handler<S>,
  failure?: Handler<F>,
  catch?: Handler<any>,
}
type Computation<+S, +F> = (handleSucc: Handler<S>, handleFail: Handler<F>) => ?Cancel

const defaultFailureHandler: Handler<mixed> = failure => {
  if (failure instanceof Error) {
    throw failure
  } else {
    throw new Error(`Unhandled task failure: ${String(failure)}`)
  }
}
const noop = () => {}

type RunHelperBody<S, F> = (s: Handler<S>, f: Handler<F>, c?: Handler<any>) => {
  onCancel?: Cancel, // called only when user cancels
  onClose?: Cancel, // called when user cancels plus when succ/fail/catch are called
}
const runHelper = <S, F>(body: RunHelperBody<S, F>, handlers: Handlers<S, F>): Cancel => {
  let {success, failure, catch: catch_} = handlers
  let onCancel = noop
  let onClose = noop
  let close = () => {
    onClose()
    // The idea here is to kill links to all stuff that we exposed from runHelper closure.
    // We expose via the return value (cancelation function) and by passing callbacks to the body.
    // We reason from an assumption that outer code may keep links to values that we exposed forever.
    // So we look at all things that referenced in the exposed callbacks and kill them.
    success = noop
    failure = noop
    catch_ = noop
    onCancel = noop
    close = noop
  }
  const bodyReturn = body(
    x => {
      const s = success
      close()
      s(x)
    },
    x => {
      const f = failure
      close()
      f(x)
    },
    catch_ && (x => {
      const c = (catch_: any)
      close()
      c(x)
    })
  )
  onCancel = bodyReturn.onCancel || noop
  onClose = bodyReturn.onClose || noop
  if (close === noop) {
    onCancel = noop
    onClose()
  }
  return () => { onCancel(); close() }
}

export default class Task<+S, +F> {

  constructor() {
    if (this.constructor === Task) {
      throw new Error('Don\'t call `new Task()`, call `Task.create()` instead')
    }
  }

  // Creates a task with an arbitrary computation
  static create<S, F>(computation: Computation<S, F>): Task<S, F> {
    return new FromComputation(computation)
  }

  // Creates a task that resolves with a given value
  static of<S, F>(value: S): Task<S, F> {
    return new Of(value)
  }
  // instance alias for Fantasy Land
  of<S, F>(value: S): Task<S, F> {
    return Task.of(value)
  }

  // Creates a task that fails with a given error
  static rejected<S, F>(error: F): Task<S, F> {
    return new Rejected(error)
  }

  // Creates a task that never completes
  static empty(): Task<any, any> {
    return new Empty()
  }
  // instance alias for Fantasy Land
  empty(): Task<any, any> {
    return Task.empty()
  }

  // Given array of tasks creates a task of array
  static parallel<S, F>(tasks: Array<Task<S, F>>): Task<S[], F> {
    return new Parallel(tasks)
  }

  // Given array of tasks creates a task that completes with the earliest value or error
  static race<S, F>(task: Array<Task<S, F>>): Task<S, F> {
    return new Race(task)
  }

  // Transforms a task by applying `fn` to the successful value
  map<S1>(fn: (x: S) => S1): Task<S1, F> {
    return new Map(this, fn)
  }

  // Transforms a task by applying `fn` to the failure value
  mapRejected<F1>(fn: (x: F) => F1): Task<S, F1> {
    return new MapRejected(this, fn)
  }

  // Transforms a task by applying `sf` to the successful value or `ff` to the failure value
  bimap<S1,F1>(sf: (x: S) => S1, ff: (x: F) => F1): Task<S1, F1> {
    return this.map(sf).mapRejected(ff)
  }

  // Transforms a task by applying `fn` to the successful value, where `fn` returns a Task
  chain<S1, F1>(fn: (x: S) => Task<S1, F1>): Task<S1, F | F1> {
    return new Chain(this, fn)
  }

  // Transforms a task by applying `fn` to the failure value, where `fn` returns a Task
  orElse<S1, F1>(fn: (x: F) => Task<S1, F1>): Task<S | S1, F1> {
    return new OrElse(this, fn)
  }

  // Applies the successful value of task `this` to to the successful value of task `otherTask`
  ap<F1>(otherTask: Task<any, F1>): Task<any, F | F1> {
    return Task.parallel([(this: Task<any, F>), otherTask]).map(([f, x]) => f(x))
  }

  // Selects the earlier of the two tasks
  concat<S1, F1>(otherTask: Task<S1, F1>): Task<S | S1, F | F1> {
    return Task.race([this, otherTask])
  }

  _run(handlers: Handlers<S, F>): Cancel { // eslint-disable-line
    throw new Error('Method run() is not implemented in basic Task class.')
  }

  run(h: LooseHandlers<S, F>): Cancel {
    const handlers = typeof h === 'function'
      ? {success: h, failure: defaultFailureHandler}
      : {success: h.success || noop, failure: h.failure || defaultFailureHandler, catch: h.catch}
    return this._run(handlers)
  }

  runAndLog(): void {
    this.run({
      success(x) { console.log('Success:', x) }, // eslint-disable-line
      failure(x) { console.log('Failure:', x) }, // eslint-disable-line
    })
  }

}

class FromComputation<S, F> extends Task<S, F> {

  _computation: Computation<S, F>;

  constructor(computation: Computation<S, F>) {
    super()
    this._computation = computation
  }

  _run(handlers: Handlers<S, F>) {
    const {_computation} = this
    return runHelper((s, f, c) => {
      let cancel
      if (c) {
        try {
          cancel = _computation(s, f)
        } catch (e) { c(e) }
      } else {
        cancel = _computation(s, f)
      }
      return {onCancel: cancel || noop}
    }, handlers)
  }

}

class Of<S> extends Task<S, any> {

  _value: S;

  constructor(value: S) {
    super()
    this._value = value
  }

  _run(handlers: Handlers<S, any>): Cancel {
    const {success} = handlers
    success(this._value)
    return noop
  }

}

class Rejected<F> extends Task<any, F> {

  _error: F;

  constructor(error: F) {
    super()
    this._error = error
  }

  _run(handlers: Handlers<any, F>): Cancel {
    const {failure} = handlers
    failure(this._error)
    return noop
  }

}

class Empty<S, F> extends Task<S, F> {

  run(): Cancel {
    return noop
  }

}

class Parallel<S, F> extends Task<S[], F> {

  _tasks: Array<Task<S, F>>;

  constructor(tasks: Array<Task<S, F>>) {
    super()
    this._tasks = tasks
  }

  _run(handlers: Handlers<S[], F>): Cancel {
    return runHelper((s, f, c) => {
      const length = this._tasks.length
      const values: Array<?S> = Array(length)
      let completedCount = 0
      const runTask = (task, index) => task.run({
        success(x) {
          values[index] = x
          completedCount++
          if (completedCount === length) {
            s((values: any))
          }
        },
        failure: f,
        catch: c,
      })
      const cancels = this._tasks.map(runTask)
      return {onClose() { cancels.forEach(cancel => cancel()) }}
    }, handlers)
  }

}

class Race<S, F> extends Task<S, F> {

  _tasks: Array<Task<S, F>>;

  constructor(tasks: Array<Task<S, F>>) {
    super()
    this._tasks = tasks
  }

  _run(handlers: Handlers<S, F>): Cancel {
    return runHelper((success, failure) => {
      const handlers = {success, failure}
      const cancels = this._tasks.map(task => task.run(handlers))
      return {onClose() { cancels.forEach(cancel => cancel()) }}
    }, handlers)
  }

}

class Map<SIn, SOut, F> extends Task<SOut, F> {

  _task: Task<SIn, F>;
  _fn: (x: SIn) => SOut;

  constructor(task: Task<SIn, F>, fn: (x: SIn) => SOut) {
    super()
    this._task = task
    this._fn = fn
  }

  _run(handlers: Handlers<SOut, F>): Cancel {
    const {_fn} = this
    const {success, failure, catch: catch_} = handlers
    return this._task.run({
      success(x) {
        let value
        if (catch_) {
          try {
            value = _fn(x)
          } catch (e) {
            catch_(e)
            return
          }
        } else {
          value = _fn(x)
        }
        success(value)
      },
      failure,
      catch: catch_,
    })
  }
}

class MapRejected<S, FIn, FOut> extends Task<S, FOut> {

  _task: Task<S, FIn>;
  _fn: (x: FIn) => FOut;

  constructor(task: Task<S, FIn>, fn: (x: FIn) => FOut) {
    super()
    this._task = task
    this._fn = fn
  }

  _run(handlers: Handlers<S, FOut>): Cancel {
    const {_fn} = this
    const {success, failure, catch: catch_} = handlers
    return this._task.run({
      success,
      failure(x) {
        let value
        if (catch_) {
          try {
            value = _fn(x)
          } catch (e) {
            catch_(e)
            return
          }
        } else {
          value = _fn(x)
        }
        failure(value)
      },
      catch: catch_,
    })
  }
}

class Chain<SIn, SOut, F, F1> extends Task<SOut, F1 | F> {

  _task: Task<SIn, F>;
  _fn: (x: SIn) => Task<SOut, F1>;

  constructor(task: Task<SIn, F>, fn: (x: SIn) => Task<SOut, F1>) {
    super()
    this._task = task
    this._fn = fn
  }

  _run(handlers: Handlers<SOut, F | F1>): Cancel {
    const {_fn} = this
    return runHelper((success, failure, catch_) => {
      let cancel2 = noop
      const cancel1 = this._task.run({
        success(x) {
          let spawned
          if (catch_) {
            try {
              spawned = _fn(x)
            } catch (e) { catch_(e) }
          } else {
            spawned = _fn(x)
          }
          if (spawned) {
            cancel2 = spawned.run({success, failure, catch: catch_})
          }
        },
        failure,
        catch: catch_,
      })
      return {onCancel() { cancel1(); cancel2() }}
    }, handlers)
  }
}

class OrElse<S, S1, FIn, FOut> extends Task<S | S1, FOut> {

  _task: Task<S, FIn>;
  _fn: (x: FIn) => Task<S1, FOut>;

  constructor(task: Task<S, FIn>, fn: (x: FIn) => Task<S1, FOut>) {
    super()
    this._task = task
    this._fn = fn
  }

  _run(handlers: Handlers<S | S1, FOut>): Cancel {
    const {_fn} = this
    return runHelper((success, failure, catch_) => {
      let cancel2 = noop
      const cancel1 = this._task.run({
        success,
        failure(x) {
          let spawned
          if (catch_) {
            try {
              spawned = _fn(x)
            } catch (e) { catch_(e) }
          } else {
            spawned = _fn(x)
          }
          if (spawned) {
            cancel2 = spawned.run({success, failure, catch: catch_})
          }
        },
        catch: catch_,
      })
      return {onCancel() { cancel1(); cancel2() }}
    }, handlers)

  }
}
<commit_msg>make `ap` compatible with `chain`<commit_after>// @flow

type Cancel = () => void
type Handler<-T> = (x: T) => void
type Handlers<-S, -F> = {
  success: Handler<S>,
  failure: Handler<F>,
  catch?: Handler<any>,
}
type LooseHandlers<-S, -F> = Handler<S> | {
  success?: Handler<S>,
  failure?: Handler<F>,
  catch?: Handler<any>,
}
type Computation<+S, +F> = (handleSucc: Handler<S>, handleFail: Handler<F>) => ?Cancel

const defaultFailureHandler: Handler<mixed> = failure => {
  if (failure instanceof Error) {
    throw failure
  } else {
    throw new Error(`Unhandled task failure: ${String(failure)}`)
  }
}
const noop = () => {}

type RunHelperBody<S, F> = (s: Handler<S>, f: Handler<F>, c?: Handler<any>) => {
  onCancel?: Cancel, // called only when user cancels
  onClose?: Cancel, // called when user cancels plus when succ/fail/catch are called
}
const runHelper = <S, F>(body: RunHelperBody<S, F>, handlers: Handlers<S, F>): Cancel => {
  let {success, failure, catch: catch_} = handlers
  let onCancel = noop
  let onClose = noop
  let close = () => {
    onClose()
    // The idea here is to kill links to all stuff that we exposed from runHelper closure.
    // We expose via the return value (cancelation function) and by passing callbacks to the body.
    // We reason from an assumption that outer code may keep links to values that we exposed forever.
    // So we look at all things that referenced in the exposed callbacks and kill them.
    success = noop
    failure = noop
    catch_ = noop
    onCancel = noop
    close = noop
  }
  const bodyReturn = body(
    x => {
      const s = success
      close()
      s(x)
    },
    x => {
      const f = failure
      close()
      f(x)
    },
    catch_ && (x => {
      const c = (catch_: any)
      close()
      c(x)
    })
  )
  onCancel = bodyReturn.onCancel || noop
  onClose = bodyReturn.onClose || noop
  if (close === noop) {
    onCancel = noop
    onClose()
  }
  return () => { onCancel(); close() }
}

export default class Task<+S, +F> {

  constructor() {
    if (this.constructor === Task) {
      throw new Error('Don\'t call `new Task()`, call `Task.create()` instead')
    }
  }

  // Creates a task with an arbitrary computation
  static create<S, F>(computation: Computation<S, F>): Task<S, F> {
    return new FromComputation(computation)
  }

  // Creates a task that resolves with a given value
  static of<S, F>(value: S): Task<S, F> {
    return new Of(value)
  }
  // instance alias for Fantasy Land
  of<S, F>(value: S): Task<S, F> {
    return Task.of(value)
  }

  // Creates a task that fails with a given error
  static rejected<S, F>(error: F): Task<S, F> {
    return new Rejected(error)
  }

  // Creates a task that never completes
  static empty(): Task<any, any> {
    return new Empty()
  }
  // instance alias for Fantasy Land
  empty(): Task<any, any> {
    return Task.empty()
  }

  // Given array of tasks creates a task of array
  static parallel<S, F>(tasks: Array<Task<S, F>>): Task<S[], F> {
    return new Parallel(tasks)
  }

  // Given array of tasks creates a task that completes with the earliest value or error
  static race<S, F>(task: Array<Task<S, F>>): Task<S, F> {
    return new Race(task)
  }

  // Transforms a task by applying `fn` to the successful value
  map<S1>(fn: (x: S) => S1): Task<S1, F> {
    return new Map(this, fn)
  }

  // Transforms a task by applying `fn` to the failure value
  mapRejected<F1>(fn: (x: F) => F1): Task<S, F1> {
    return new MapRejected(this, fn)
  }

  // Transforms a task by applying `sf` to the successful value or `ff` to the failure value
  bimap<S1,F1>(sf: (x: S) => S1, ff: (x: F) => F1): Task<S1, F1> {
    return this.map(sf).mapRejected(ff)
  }

  // Transforms a task by applying `fn` to the successful value, where `fn` returns a Task
  chain<S1, F1>(fn: (x: S) => Task<S1, F1>): Task<S1, F | F1> {
    return new Chain(this, fn)
  }

  // Transforms a task by applying `fn` to the failure value, where `fn` returns a Task
  orElse<S1, F1>(fn: (x: F) => Task<S1, F1>): Task<S | S1, F1> {
    return new OrElse(this, fn)
  }

  // Applies the successful value of task `this` to to the successful value of task `otherTask`
  ap<F1>(otherTask: Task<any, F1>): Task<any, F | F1> {
    return this.chain(f => otherTask.map(x => (f: any)(x)))
  }

  // Selects the earlier of the two tasks
  concat<S1, F1>(otherTask: Task<S1, F1>): Task<S | S1, F | F1> {
    return Task.race([this, otherTask])
  }

  _run(handlers: Handlers<S, F>): Cancel { // eslint-disable-line
    throw new Error('Method run() is not implemented in basic Task class.')
  }

  run(h: LooseHandlers<S, F>): Cancel {
    const handlers = typeof h === 'function'
      ? {success: h, failure: defaultFailureHandler}
      : {success: h.success || noop, failure: h.failure || defaultFailureHandler, catch: h.catch}
    return this._run(handlers)
  }

  runAndLog(): void {
    this.run({
      success(x) { console.log('Success:', x) }, // eslint-disable-line
      failure(x) { console.log('Failure:', x) }, // eslint-disable-line
    })
  }

}

class FromComputation<S, F> extends Task<S, F> {

  _computation: Computation<S, F>;

  constructor(computation: Computation<S, F>) {
    super()
    this._computation = computation
  }

  _run(handlers: Handlers<S, F>) {
    const {_computation} = this
    return runHelper((s, f, c) => {
      let cancel
      if (c) {
        try {
          cancel = _computation(s, f)
        } catch (e) { c(e) }
      } else {
        cancel = _computation(s, f)
      }
      return {onCancel: cancel || noop}
    }, handlers)
  }

}

class Of<S> extends Task<S, any> {

  _value: S;

  constructor(value: S) {
    super()
    this._value = value
  }

  _run(handlers: Handlers<S, any>): Cancel {
    const {success} = handlers
    success(this._value)
    return noop
  }

}

class Rejected<F> extends Task<any, F> {

  _error: F;

  constructor(error: F) {
    super()
    this._error = error
  }

  _run(handlers: Handlers<any, F>): Cancel {
    const {failure} = handlers
    failure(this._error)
    return noop
  }

}

class Empty<S, F> extends Task<S, F> {

  run(): Cancel {
    return noop
  }

}

class Parallel<S, F> extends Task<S[], F> {

  _tasks: Array<Task<S, F>>;

  constructor(tasks: Array<Task<S, F>>) {
    super()
    this._tasks = tasks
  }

  _run(handlers: Handlers<S[], F>): Cancel {
    return runHelper((s, f, c) => {
      const length = this._tasks.length
      const values: Array<?S> = Array(length)
      let completedCount = 0
      const runTask = (task, index) => task.run({
        success(x) {
          values[index] = x
          completedCount++
          if (completedCount === length) {
            s((values: any))
          }
        },
        failure: f,
        catch: c,
      })
      const cancels = this._tasks.map(runTask)
      return {onClose() { cancels.forEach(cancel => cancel()) }}
    }, handlers)
  }

}

class Race<S, F> extends Task<S, F> {

  _tasks: Array<Task<S, F>>;

  constructor(tasks: Array<Task<S, F>>) {
    super()
    this._tasks = tasks
  }

  _run(handlers: Handlers<S, F>): Cancel {
    return runHelper((success, failure) => {
      const handlers = {success, failure}
      const cancels = this._tasks.map(task => task.run(handlers))
      return {onClose() { cancels.forEach(cancel => cancel()) }}
    }, handlers)
  }

}

class Map<SIn, SOut, F> extends Task<SOut, F> {

  _task: Task<SIn, F>;
  _fn: (x: SIn) => SOut;

  constructor(task: Task<SIn, F>, fn: (x: SIn) => SOut) {
    super()
    this._task = task
    this._fn = fn
  }

  _run(handlers: Handlers<SOut, F>): Cancel {
    const {_fn} = this
    const {success, failure, catch: catch_} = handlers
    return this._task.run({
      success(x) {
        let value
        if (catch_) {
          try {
            value = _fn(x)
          } catch (e) {
            catch_(e)
            return
          }
        } else {
          value = _fn(x)
        }
        success(value)
      },
      failure,
      catch: catch_,
    })
  }
}

class MapRejected<S, FIn, FOut> extends Task<S, FOut> {

  _task: Task<S, FIn>;
  _fn: (x: FIn) => FOut;

  constructor(task: Task<S, FIn>, fn: (x: FIn) => FOut) {
    super()
    this._task = task
    this._fn = fn
  }

  _run(handlers: Handlers<S, FOut>): Cancel {
    const {_fn} = this
    const {success, failure, catch: catch_} = handlers
    return this._task.run({
      success,
      failure(x) {
        let value
        if (catch_) {
          try {
            value = _fn(x)
          } catch (e) {
            catch_(e)
            return
          }
        } else {
          value = _fn(x)
        }
        failure(value)
      },
      catch: catch_,
    })
  }
}

class Chain<SIn, SOut, F, F1> extends Task<SOut, F1 | F> {

  _task: Task<SIn, F>;
  _fn: (x: SIn) => Task<SOut, F1>;

  constructor(task: Task<SIn, F>, fn: (x: SIn) => Task<SOut, F1>) {
    super()
    this._task = task
    this._fn = fn
  }

  _run(handlers: Handlers<SOut, F | F1>): Cancel {
    const {_fn} = this
    return runHelper((success, failure, catch_) => {
      let cancel2 = noop
      const cancel1 = this._task.run({
        success(x) {
          let spawned
          if (catch_) {
            try {
              spawned = _fn(x)
            } catch (e) { catch_(e) }
          } else {
            spawned = _fn(x)
          }
          if (spawned) {
            cancel2 = spawned.run({success, failure, catch: catch_})
          }
        },
        failure,
        catch: catch_,
      })
      return {onCancel() { cancel1(); cancel2() }}
    }, handlers)
  }
}

class OrElse<S, S1, FIn, FOut> extends Task<S | S1, FOut> {

  _task: Task<S, FIn>;
  _fn: (x: FIn) => Task<S1, FOut>;

  constructor(task: Task<S, FIn>, fn: (x: FIn) => Task<S1, FOut>) {
    super()
    this._task = task
    this._fn = fn
  }

  _run(handlers: Handlers<S | S1, FOut>): Cancel {
    const {_fn} = this
    return runHelper((success, failure, catch_) => {
      let cancel2 = noop
      const cancel1 = this._task.run({
        success,
        failure(x) {
          let spawned
          if (catch_) {
            try {
              spawned = _fn(x)
            } catch (e) { catch_(e) }
          } else {
            spawned = _fn(x)
          }
          if (spawned) {
            cancel2 = spawned.run({success, failure, catch: catch_})
          }
        },
        catch: catch_,
      })
      return {onCancel() { cancel1(); cancel2() }}
    }, handlers)

  }
}
<|endoftext|>


<commit_before>import {registerMetaSchema} from './builder';
import './context';
import './loader';
import './schema';
import './util';

import './vendor/ipaddr';
import './vendor/url';

import * as Draft4 from './draft4/schema';
import './draft4/validators/any/allof';
import './draft4/validators/any/anyof';
import './draft4/validators/any/oneof';
import './draft4/validators/any/not';
import './draft4/validators/any/enum';
import './draft4/validators/any/type';
import './draft4/validators/array/items';
import './draft4/validators/array/maxitems';
import './draft4/validators/array/minitems';
import './draft4/validators/array/uniqueitems';
import './draft4/validators/number/maximum';
import './draft4/validators/number/minimum';
import './draft4/validators/number/multipleof';
import './draft4/validators/object/dependencies';
import './draft4/validators/object/maxproperties';
import './draft4/validators/object/minproperties';
import './draft4/validators/object/properties';
import './draft4/validators/object/required';
import './draft4/validators/string/maxlength';
import './draft4/validators/string/minlength';
import './draft4/validators/string/pattern';
import './draft4/validators/string/format';

export {Schema, Loader} from './schema';

registerMetaSchema(Draft4);
<commit_msg>Removed broken import<commit_after>import {registerMetaSchema} from './builder';
import './context';
import './loader';
import './schema';
import './util';

import './vendor/ipaddr';

import * as Draft4 from './draft4/schema';
import './draft4/validators/any/allof';
import './draft4/validators/any/anyof';
import './draft4/validators/any/oneof';
import './draft4/validators/any/not';
import './draft4/validators/any/enum';
import './draft4/validators/any/type';
import './draft4/validators/array/items';
import './draft4/validators/array/maxitems';
import './draft4/validators/array/minitems';
import './draft4/validators/array/uniqueitems';
import './draft4/validators/number/maximum';
import './draft4/validators/number/minimum';
import './draft4/validators/number/multipleof';
import './draft4/validators/object/dependencies';
import './draft4/validators/object/maxproperties';
import './draft4/validators/object/minproperties';
import './draft4/validators/object/properties';
import './draft4/validators/object/required';
import './draft4/validators/string/maxlength';
import './draft4/validators/string/minlength';
import './draft4/validators/string/pattern';
import './draft4/validators/string/format';

export {Schema, Loader} from './schema';

registerMetaSchema(Draft4);
<|endoftext|>


<commit_before>module.exports = {
    TabbedArea : require('./TabbedArea.jsx'),
    TabPane: require('./TabPane.jsx')
};
<commit_msg>Added Panel and PanelGroup to the export list<commit_after>module.exports = {
    TabbedArea : require('./TabbedArea.jsx'),
    TabPane: require('./TabPane.jsx'),
    Panel: require('./Panel.jsx'),
    PanelGroup: require('./PanelGroup.jsx')
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';

import SearchBar from './components/search_bar';

import secret from './_secret.js';

const YOUTUBE_API_KEY = secret.API_KEY;

// This is a class of a component
// To create an instance of this class use <App />
class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      videos: []
    };

    YTSearch({key: YOUTUBE_API_KEY, term: 'surfboards' }, (videos) => {
      this.setState({ videos: videos })
    })
  }

  render() {
    return (

        <SearchBar />

    );
  }
}

// Render App inside an element with class name 'container'
ReactDOM.render(<App />, document.querySelector('.container'));
<commit_msg>Use ES6 setState syntax.<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';

import SearchBar from './components/search_bar';

import secret from './_secret.js';

const YOUTUBE_API_KEY = secret.API_KEY;

// This is a class of a component
// To create an instance of this class use <App />
class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      videos: []
    };

    YTSearch({key: YOUTUBE_API_KEY, term: 'surfboards' }, (videos) => {
      this.setState({ videos })
    })
  }

  render() {
    return (

        <SearchBar />

    );
  }
}

// Render App inside an element with class name 'container'
ReactDOM.render(<App />, document.querySelector('.container'));
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { v4 as uuid } from 'uuid';

import BuildStates from 'app/constants/BuildStates';

const SIZE_DEFINITIONS = {
  Regular: {
    strokeWidth: 2,
    size: 32
  },
  Small: {
    strokeWidth: 3,
    size: 20
  },
  XSmall: {
    strokeWidth: 4,
    size: 13
  }
};

const STATE_COLORS = {
  [null]: '#cdcccc',
  [BuildStates.SCHEDULED]: '#bbbbbb',
  [BuildStates.RUNNING]: '#fdba12',
  [BuildStates.PASSED]: '#90c73e',
  [BuildStates.BLOCKED]: '#90c73e',
  [BuildStates.FAILED]: '#F83F23',
  [BuildStates.CANCELED]: '#F83F23',
  [BuildStates.CANCELING]: '#F83F23',
  [BuildStates.SKIPPED]: '#83B0E4',
  [BuildStates.NOT_RUN]: '#83B0E4'
};

class BuildState extends React.PureComponent {
  static propTypes = {
    className: PropTypes.string,
    size: PropTypes.number.isRequired,
    state: PropTypes.oneOf(Object.keys(STATE_COLORS)),
    strokeWidth: PropTypes.number.isRequired,
    style: PropTypes.object
  };

  state = {
    uuid: ''
  };

  componentWillMount() {
    this.setState({
      uuid: uuid()
    });
  }

  render() {
    const { className, size, strokeWidth, style } = this.props;

    const outerCircleId = `BuildState_${this.state.uuid}_circle`;
    const strokeClipPathId = `BuildState_${this.state.uuid}_strokeClipPath`;

    const { defs, content } = this.renderPaths();

    return (
      <svg
        className={className}
        style={style}
        width={size}
        height={size}
        viewBox="0 0 32 32"
      >
        <defs>
          <circle
            id={outerCircleId}
            fill="none"
            cx="16"
            cy="16"
            r="15"
            stroke={STATE_COLORS[this.props.state]}
            strokeWidth={strokeWidth * 2}
          />
          <clipPath id={strokeClipPathId}>
            <use xlinkHref={`#${outerCircleId}`} />
          </clipPath>
          {defs}
        </defs>
        <use
          xlinkHref={`#${outerCircleId}`}
          clipPath={`url(#${strokeClipPathId})`}
        />
        {content}
      </svg>
    );
  }

  renderPaths() {
    const applyStroke = {
      fill: 'none',
      stroke: STATE_COLORS[this.props.state],
      strokeWidth: this.props.strokeWidth
    };

    const maskId = `BuildState_${this.state.uuid}_mask`;

    let defs;
    let content;

    switch (this.props.state) {
      case BuildStates.FAILED:
      case BuildStates.CANCELED:
        content = (
          <g transform="translate(10.000000, 10.000000)" {...applyStroke}>
            <path d="M0.600275489,0.600275489 L11.3997245,11.3997245" />
            <path d="M11.3997245,0.600275489 L0.600275489,11.3997245" />
          </g>
        );
        break;

      case BuildStates.PASSED:
        content = (
          <polyline points="10 17.61 14.38 20.81 21 11.41" {...applyStroke} strokeMiterlimit="10" />
        );
        break;

      case BuildStates.BLOCKED:
        content = (
          <g {...applyStroke}>
            <path d="M13,21V11" />
            <path d="M19,21V11" />
          </g>
        );
        break;

      case BuildStates.SCHEDULED:
      case BuildStates.RUNNING:
      case BuildStates.CANCELING:
        defs = (
          <mask id={maskId} x="9" y="9" width="14" height="14" maskUnits="userSpaceOnUse">
            <polygon
              className="animation-spin"
              style={{ transformOrigin: 'center' }}
              fill="#fff"
              points="16 16 9 16 9 9 16 9 16 16 23 16 23 23 16 23 16 16"
            />
          </mask>
        );
        content = (
          <g mask={`url(#${maskId})`}>
            <circle cx="16" cy="16" r="6" {...applyStroke} />
          </g>
        );
        break;

      case null:
      case BuildStates.SKIPPED:
      case BuildStates.NOT_RUN:
        content = (
          <path d="M11,16H21" fill="none" {...applyStroke} />
        );
        break;
    }

    return { defs, content };
  }
}

const exported = {};

Object.keys(SIZE_DEFINITIONS).forEach((size) => {
  const component = (props) => <BuildState {...props} {...SIZE_DEFINITIONS[size]} />;
  component.displayName = `BuildState.${size}`;

  exported[size] = component;
});

export default exported;
<commit_msg>Don't use componentWillMount in BuildState<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { v4 as uuid } from 'uuid';

import BuildStates from 'app/constants/BuildStates';

const SIZE_DEFINITIONS = {
  Regular: {
    strokeWidth: 2,
    size: 32
  },
  Small: {
    strokeWidth: 3,
    size: 20
  },
  XSmall: {
    strokeWidth: 4,
    size: 13
  }
};

const STATE_COLORS = {
  [null]: '#cdcccc',
  [BuildStates.SCHEDULED]: '#bbbbbb',
  [BuildStates.RUNNING]: '#fdba12',
  [BuildStates.PASSED]: '#90c73e',
  [BuildStates.BLOCKED]: '#90c73e',
  [BuildStates.FAILED]: '#F83F23',
  [BuildStates.CANCELED]: '#F83F23',
  [BuildStates.CANCELING]: '#F83F23',
  [BuildStates.SKIPPED]: '#83B0E4',
  [BuildStates.NOT_RUN]: '#83B0E4'
};

class BuildState extends React.PureComponent {
  static propTypes = {
    className: PropTypes.string,
    size: PropTypes.number.isRequired,
    state: PropTypes.oneOf(Object.keys(STATE_COLORS)),
    strokeWidth: PropTypes.number.isRequired,
    style: PropTypes.object
  };

  constructor(props) {
    super(props);

    this.state = {
      uuid: uuid()
    };
  }

  render() {
    const { className, size, strokeWidth, style } = this.props;

    const outerCircleId = `BuildState_${this.state.uuid}_circle`;
    const strokeClipPathId = `BuildState_${this.state.uuid}_strokeClipPath`;

    const { defs, content } = this.renderPaths();

    return (
      <svg
        className={className}
        style={style}
        width={size}
        height={size}
        viewBox="0 0 32 32"
      >
        <defs>
          <circle
            id={outerCircleId}
            fill="none"
            cx="16"
            cy="16"
            r="15"
            stroke={STATE_COLORS[this.props.state]}
            strokeWidth={strokeWidth * 2}
          />
          <clipPath id={strokeClipPathId}>
            <use xlinkHref={`#${outerCircleId}`} />
          </clipPath>
          {defs}
        </defs>
        <use
          xlinkHref={`#${outerCircleId}`}
          clipPath={`url(#${strokeClipPathId})`}
        />
        {content}
      </svg>
    );
  }

  renderPaths() {
    const applyStroke = {
      fill: 'none',
      stroke: STATE_COLORS[this.props.state],
      strokeWidth: this.props.strokeWidth
    };

    const maskId = `BuildState_${this.state.uuid}_mask`;

    let defs;
    let content;

    switch (this.props.state) {
      case BuildStates.FAILED:
      case BuildStates.CANCELED:
        content = (
          <g transform="translate(10.000000, 10.000000)" {...applyStroke}>
            <path d="M0.600275489,0.600275489 L11.3997245,11.3997245" />
            <path d="M11.3997245,0.600275489 L0.600275489,11.3997245" />
          </g>
        );
        break;

      case BuildStates.PASSED:
        content = (
          <polyline points="10 17.61 14.38 20.81 21 11.41" {...applyStroke} strokeMiterlimit="10" />
        );
        break;

      case BuildStates.BLOCKED:
        content = (
          <g {...applyStroke}>
            <path d="M13,21V11" />
            <path d="M19,21V11" />
          </g>
        );
        break;

      case BuildStates.SCHEDULED:
      case BuildStates.RUNNING:
      case BuildStates.CANCELING:
        defs = (
          <mask id={maskId} x="9" y="9" width="14" height="14" maskUnits="userSpaceOnUse">
            <polygon
              className="animation-spin"
              style={{ transformOrigin: 'center' }}
              fill="#fff"
              points="16 16 9 16 9 9 16 9 16 16 23 16 23 23 16 23 16 16"
            />
          </mask>
        );
        content = (
          <g mask={`url(#${maskId})`}>
            <circle cx="16" cy="16" r="6" {...applyStroke} />
          </g>
        );
        break;

      case null:
      case BuildStates.SKIPPED:
      case BuildStates.NOT_RUN:
        content = (
          <path d="M11,16H21" fill="none" {...applyStroke} />
        );
        break;
    }

    return { defs, content };
  }
}

const exported = {};

Object.keys(SIZE_DEFINITIONS).forEach((size) => {
  const component = (props) => <BuildState {...props} {...SIZE_DEFINITIONS[size]} />;
  component.displayName = `BuildState.${size}`;

  exported[size] = component;
});

export default exported;
<|endoftext|>


<commit_before>const _ = require('underscore');
const compare = require('json-structure-diff').compareJSONObjects;

const structureJsonRaw = require('./keyfiles-structure.json');

/**
 * Deep copies JSON object with keys.toLowerCase()
 * @param  {Object} obj input
 * @return {Object}     output
 */
function toLower(obj) {
    const newObj = {};
    _.keys(obj).forEach((key) => {
        const type = typeof (newObj[key.toLowerCase()] = obj[key]);
        if (type === 'object') {
            newObj[key] = toLower(newObj[key]);
        }
    });
    return newObj;
}

const structureJson = toLower(structureJsonRaw);

/**
 * Matches the input object's structure against valid keyfile structures
 * (respects key and value-type)
 * @param  {Object} obj input keyfile object
 * @return {[String, Number]} array of type (web3|ethersale) and version
 */
module.exports = (obj) => {
    let result = null;
    const BreakException = {};
    try {
        _.keys(structureJson).forEach((structureType) => {
            const structure = {
                parent: structureType,
                content: structureJson[structureType].json,
            };
            const instance = {
                parent: 'obj',
                content: toLower(obj),
            };
            const error = compare([structure, instance]);
            if (!error) {
                const match = structureJson[structure.parent];
                result = [match.type, match.json.version];
                throw BreakException;
            }
        });
    } catch (err) {
        // break out of loop; keyfile already validated
    }
    return result;
};
<commit_msg>use 'strict mode'<commit_after>'strict mode';

const _ = require('underscore');
const compare = require('json-structure-diff').compareJSONObjects;

const structureJsonRaw = require('./keyfiles-structure.json');

/**
 * Deep copies JSON object with keys.toLowerCase()
 * @param  {Object} obj input
 * @return {Object}     output
 */
function toLower(obj) {
    const newObj = {};
    _.keys(obj).forEach((key) => {
        const type = typeof (newObj[key.toLowerCase()] = obj[key]);
        if (type === 'object') {
            newObj[key] = toLower(newObj[key]);
        }
    });
    return newObj;
}

const structureJson = toLower(structureJsonRaw);

/**
 * Matches the input object's structure against valid keyfile structures
 * (respects key and value-type)
 * @param  {Object} obj input keyfile object
 * @return {[String, Number]} array of type (web3|ethersale) and version
 */
module.exports = (obj) => {
    let result = null;
    const BreakException = {};
    try {
        _.keys(structureJson).forEach((structureType) => {
            const structure = {
                parent: structureType,
                content: structureJson[structureType].json,
            };
            const instance = {
                parent: 'obj',
                content: toLower(obj),
            };
            const error = compare([structure, instance]);
            if (!error) {
                const match = structureJson[structure.parent];
                result = [match.type, match.json.version];
                throw BreakException;
            }
        });
    } catch (err) {
        // break out of loop; keyfile already validated
    }
    return result;
};
<|endoftext|>


<commit_before>const invariant = require('invariant');

function patchRouteQuery(oldQueryName, newQueryName, query) {
  return eval(`(function(Relay) { return ${query.toString().replace(
    /getFragment\((\S*?)\)/,
    `getFragment(${JSON.stringify(newQueryName)})`
  )}; })`);
}

function generateRouteName(components) {
  return `Nested_${
    components.map(component => component.displayName).join('_')
  }`;
}

const CACHED_STATES = {};

export default function generateRootContainer(React, Relay) {
  return class NestedRootContainer extends React.Component {
    constructor(props) {
      super(props);
      this.state = this._generateContainer(props);
    }

    componentWillReceiveProps(props) {
      this.setState(this._generateContainer(props));
    }

    render() {
      const { Component, route } = this.state;

      return (
        <Relay.RootContainer
          Component={Component}
          route={{ ...route, params: this.props.params }}/>
      );
    }

    _generateContainer(newProps) {
      const { branch, components } = newProps;
      const routeName = generateRouteName(components);

      if (CACHED_STATES[routeName]) {
        return CACHED_STATES[routeName];
      }

      const queries = {};
      const fragments = {};
      let queryIdx = 0;

      const [, ...elems] = components.map((Component, index) => {
        const fragmentResolvers = [];

        if (Relay.isContainer(Component)) {
          const { route } = branch[index];

          invariant(
            route,
            'Routes with Relay.Containers must include a `route` prop.'
          );

          Object.keys(route.queries).forEach(queryName => {
            const newQueryName = `Nested_${route.routeName}_${queryName}_${++queryIdx}`;
            queries[newQueryName] = patchRouteQuery(
              queryName,
              newQueryName,
              route.queries[queryName]
            ).call(undefined, Relay);
            const fragment = Component.getFragment(queryName)._fragmentGetter;
            fragments[newQueryName] = () => fragment();
            fragmentResolvers.push({
              prop: queryName,
              resolve: function getLocalProp() {
                return this.props[newQueryName];
              },
            });
          });
        }

        return function ComponentGenerator(props) {
          fragmentResolvers.forEach(fragment => {
            props[fragment.prop] = fragment.resolve.call(this);
          });

          return <Component {...props}/>;
        };
      });

      class NestedRenderer extends React.Component {
        render() {
          return elems.reduceRight((children, generateComponent) => {
            return generateComponent.call(this, { children: children });
          }, null);
        }
      }

      const NestedRendererContainer = Relay.createContainer(NestedRenderer, {
        fragments,
      });

      const route = {
        name: routeName,
        queries,
      };

      const state = CACHED_STATES[routeName] = {
        Component: NestedRendererContainer,
        route,
      };
      return state;
    }
  };
}
<commit_msg>Better way of resolving fragments<commit_after>const invariant = require('invariant');

function generateRouteName(components) {
  return `Nested_${
    components.map(component => component.displayName).join('_')
  }`;
}

const CACHED_STATES = {};

export default function generateRootContainer(React, Relay) {
  return class NestedRootContainer extends React.Component {
    constructor(props, context) {
      super(props, context);
      this.state = this._generateContainer(props);
    }

    componentWillReceiveProps(props) {
      this.setState(this._generateContainer(props));
    }

    render() {
      const { Component, route } = this.state;

      return (
        <Relay.RootContainer
          Component={Component}
          route={{ ...route, params: this.props.params }}/>
      );
    }

    _generateContainer(newProps) {
      const { branch, components } = newProps;
      const routeName = generateRouteName(components);

      if (CACHED_STATES[routeName]) {
        return CACHED_STATES[routeName];
      }

      const queries = {};
      const fragments = {};
      let queryIdx = 0;

      const [, ...elems] = components.map((Component, index) => {
        const fragmentResolvers = [];

        if (Relay.isContainer(Component)) {
          const { route } = branch[index];

          invariant(
            route,
            'Routes with Relay.Containers must include a `route` prop.'
          );

          Object.keys(route.queries).forEach(queryName => {
            const newQueryName = `Nested_${route.name}_${queryName}_${++queryIdx}`;
            queries[newQueryName] = () => route.queries[queryName](Component);

            const fragment = Component.getFragment(queryName)._fragmentGetter;
            fragments[newQueryName] = () => fragment();
            fragmentResolvers.push({
              prop: queryName,
              resolve: function getLocalProp() {
                return this.props[newQueryName];
              },
            });
          });
        }

        return function ComponentGenerator(props) {
          fragmentResolvers.forEach(fragment => {
            props[fragment.prop] = fragment.resolve.call(this);
          });

          return <Component {...props}/>;
        };
      });

      class NestedRenderer extends React.Component {
        render() {
          return elems.reduceRight((children, generateComponent) => {
            return generateComponent.call(this, { children: children });
          }, null);
        }
      }

      const NestedRendererContainer = Relay.createContainer(NestedRenderer, {
        fragments,
      });

      const route = {
        name: routeName,
        queries,
      };

      const state = CACHED_STATES[routeName] = {
        Component: NestedRendererContainer,
        route,
      };
      return state;
    }
  };
}
<|endoftext|>


<commit_before>import { Component, createElement } from "react";

const DEFAULT_CHART_COLORS = [
  "#3366CC",
  "#DC3912",
  "#FF9900",
  "#109618",
  "#990099",
  "#3B3EAC",
  "#0099C6",
  "#DD4477",
  "#66AA00",
  "#B82E2E",
  "#316395",
  "#994499",
  "#22AA99",
  "#AAAA11",
  "#6633CC",
  "#E67300",
  "#8B0707",
  "#329262",
  "#5574A6",
  "#3B3EAC"
];

var DEFAULT_COLORS = /*#__PURE__*/ Object.freeze({
  DEFAULT_CHART_COLORS: DEFAULT_CHART_COLORS,
  default: DEFAULT_CHART_COLORS
});

const getGoogle = (windowAsArg = window) => {
  if (typeof windowAsArg === "undefined") {
    return {};
  }
  if (typeof windowAsArg.google === "undefined") {
    throw new Error("google not in window object. Error in get-google-charts.");
  }
  return windowAsArg.google;
};
const getGoogleCharts = (windowAsArg = window) => {
  if (typeof windowAsArg === "undefined") {
    return {};
  }
  if (typeof windowAsArg.google === "undefined") {
    throw new Error("google not in window object. Error in get-google-charts.");
  }
  return windowAsArg.google.charts;
};

class GoogleChartLoader {
  constructor() {
    this.isLoaded = false;
    this.isLoading = false;
    this.loadScript = null;
    this.destroy = () => {
      this.isLoading = false;
      this.isLoaded = false;
      this.loadScript = null;
    };
    this.init = (packages, version, language, mapsApiKey) => {
      if ((this.isLoading || this.isLoaded) && this.loadScript !== null) {
        return this.loadScript;
      }
      const script =
        typeof window !== "undefined"
          ? require("loadjs")
          : (link, { success: callback }) => callback();
      this.loadScript = new Promise(resolve => {
        script("https://www.gstatic.com/charts/loader.js", {
          success: () => {
            const google_charts = getGoogleCharts(window);
            google_charts.load(version || "current", {
              packages: packages || ["corechart"],
              language: language || "en",
              mapsApiKey
            });
            google_charts.setOnLoadCallback(() => {
              this.isLoaded = true;
              this.isLoading = false;
              resolve();
            });
          }
        });
      });
      this.isLoading = true;
      return this.loadScript;
    };
  }
}
const googleChartLoader = new GoogleChartLoader();

let uniqueID = 0;
const generateUniqueID = () => {
  uniqueID += 1;
  return `reactgooglegraph-${uniqueID}`;
};
class Chart extends Component {
  constructor(props) {
    super(props);
    this.chart = null;
    this.wrapper = null;
    this.hidden_columns = {};
    this.dataTable = [];
    this.isUnmounted = false;
    this.onResize = () => {
      this.drawChart();
    };
    this.onSelectToggle = () => {
      if (this.chart === null) return;
      const selection = this.chart.getSelection();
      if (selection.length > 0) {
        if (selection[0].row == null) {
          const column = selection[0].column;
          this.togglePoints(column);
        }
      }
    };
    this.getColumnColor = columnIndex => {
      if (this.props.options && this.props.options.colors) {
        if (this.props.options.colors[columnIndex]) {
          return this.props.options.colors[columnIndex];
        }
      } else if (columnIndex in DEFAULT_COLORS) {
        return DEFAULT_COLORS[columnIndex];
      }
      return DEFAULT_COLORS[0];
    };
    this.applyNumberFormat = (column, options) => {
      const googlefromWindow = getGoogle(window);
      const formatter = new googlefromWindow.visualization.NumberFormat(
        options
      );
      formatter.format(this.dataTable, column);
    };
    this.applyDateFormat = (column, options) => {
      const googlefromWindow = getGoogle(window);
      const formatter = new googlefromWindow.visualization.DateFormat(options);
      formatter.format(this.dataTable, column);
    };
    this.buildDataTableFromProps = () => {
      const chartType = this.props.chartType;
      const googlefromWindow = getGoogle(window);
      if (this.props.diffdata && this.props.chartType !== null) {
        const diffdata = this.props.diffdata;
        const oldData = googlefromWindow.visualization.arrayToDataTable(
          diffdata.old
        );
        const newData = googlefromWindow.visualization.arrayToDataTable(
          diffdata.new
        );
        const computeDiff =
          googlefromWindow.visualization[chartType].prototype.computeDiff;
        const chartDiff = computeDiff(oldData, newData);
        return chartDiff;
      }
      if (
        this.props.data === null &&
        (this.props.rows && this.props.rows.length === 0) &&
        !this.props.allowEmptyRows === false
      ) {
        throw new Error(
          "Can't build DataTable from rows and columns: rows array in props is empty"
        );
      } else if (
        this.props.data === null &&
        (this.props.columns && this.props.columns.length === 0)
      ) {
        throw new Error(
          "Can't build DataTable from rows and columns: columns array in props is empty"
        );
      }
      if (this.props.data !== null) {
        try {
          this.wrapper.setDataTable(this.props.data);
          const dataTable = this.wrapper.getDataTable();
          return dataTable;
        } catch (err) {
          throw new Error("Failed to set DataTable from data props ! ", err);
        }
      }
      const dataTable = new window.google.visualization.DataTable();
      this.props.columns.forEach(column => {
        dataTable.addColumn(column);
      });
      dataTable.addRows(this.props.rows);
      if (this.props.numberFormat) {
        const { column, options } = this.props.numberFormat;
        this.applyNumberFormat(column, options);
      }
      if (this.props.dateFormat) {
        const { columns, options } = this.props.dateFormat;
        columns.forEach(col => {
          this.applyDateFormat(col, options);
        });
      }
      this.props.formatters.forEach(({ type, column, options }) => {
        switch (type) {
          case "NumberFormat":
            this.applyNumberFormat(column, options);
            break;
          case "DateFormat":
            this.applyDateFormat(column, options);
            break;
          default:
            console.log(`Unkown formatter type: ${type}`);
            break;
        }
      });
      return dataTable;
    };
    this.updateDataTable = () => {
      window.google.visualization.errors.removeAll(
        document.getElementById(this.wrapper.getContainerId())
      );
      this.dataTable.removeRows(0, this.dataTable.getNumberOfRows());
      this.dataTable.removeColumns(0, this.dataTable.getNumberOfColumns());
      this.dataTable = this.buildDataTableFromProps();
      return this.dataTable;
    };
    this.drawChart = () => {
      if (this.isUnmounted) {
        return;
      }
      if (!this.wrapper) {
        const chartConfig = {
          chartType: this.props.chartType,
          options: this.props.options,
          containerId: this.state.graphID
        };
        this.wrapper = new window.google.visualization.ChartWrapper(
          chartConfig
        );
        this.dataTable = this.buildDataTableFromProps();
        this.wrapper.setDataTable(this.dataTable);
        window.google.visualization.events.addOneTimeListener(
          this.wrapper,
          "ready",
          () => {
            this.chart = this.wrapper.getChart();
            this.listenToChartEvents();
            this.addChartActions();
          }
        );
      } else {
        this.updateDataTable();
        this.wrapper.setDataTable(this.dataTable);
        this.wrapper.setOptions(this.props.options);
        if (this.wrapper.getChartType() !== this.props.chartType) {
          window.google.visualization.events.removeAllListeners(this.wrapper);
          this.wrapper.setChartType(this.props.chartType);
          const self = this;
          window.google.visualization.events.addOneTimeListener(
            this.wrapper,
            "ready",
            () => {
              self.chart = self.wrapper.getChart();
              self.listenToChartEvents.call(self);
            }
          );
        }
      }
      this.wrapper.draw();
    };
    this.addChartActions = () => {
      if (this.props.chartActions === null) {
        return;
      }
      this.props.chartActions.forEach(chartAction => {
        this.chart.setAction({
          id: chartAction.id,
          text: chartAction.text,
          action: chartAction.action.bind(this, this.chart)
        });
      });
    };
    this.listenToChartEvents = () => {
      if (this.props.legend_toggle) {
        window.google.visualization.events.addListener(
          this.wrapper,
          "select",
          this.onSelectToggle
        );
      }
      this.props.chartEvents.forEach(chartEvent => {
        if (chartEvent.eventName === "ready") {
          chartEvent.callback(this);
        } else {
          (event => {
            window.google.visualization.events.addListener(
              this.chart,
              event.eventName,
              e => {
                event.callback(this, e);
              }
            );
          })(chartEvent);
        }
      });
    };
    this.buildColumnFromSourceData = columnIndex => {
      return {
        label: this.dataTable.getColumnLabel(columnIndex),
        type: this.dataTable.getColumnType(columnIndex),
        sourceColumn: columnIndex,
        role: this.dataTable.getColumnRole(columnIndex)
      };
    };
    this.buildEmptyColumnFromSourceData = columnIndex => {
      return {
        label: this.dataTable.getColumnLabel(columnIndex),
        type: this.dataTable.getColumnType(columnIndex),
        calc: () => null,
        role: this.dataTable.getColumnRole(columnIndex)
      };
    };
    this.addEmptyColumnTo = (columns, columnIndex) => {
      const emptyColumn = this.buildEmptyColumnFromSourceData(columnIndex);
      columns.push(emptyColumn);
    };
    this.hideColumn = (colors, columnIndex) => {
      if (!this.isHidden(columnIndex)) {
        this.hidden_columns[columnIndex] = {
          color: this.getColumnColor(columnIndex - 1)
        };
      }
      colors.push("#CCCCCC");
    };
    this.addSourceColumnTo = (columns, columnIndex) => {
      const sourceColumn = this.buildColumnFromSourceData(columnIndex);
      columns.push(sourceColumn);
    };
    this.isHidden = columnIndex => {
      return this.hidden_columns[columnIndex] !== undefined;
    };
    this.restoreColorTo = (colors, columnIndex) => {
      let previousColor;
      if (this.isHidden(columnIndex)) {
        previousColor = this.hidden_columns[columnIndex].color;
        delete this.hidden_columns[columnIndex];
      } else {
        previousColor = this.getColumnColor(columnIndex - 1);
      }
      if (columnIndex !== 0) {
        colors.push(previousColor);
      }
    };
    this.debounce = (func, wait) => {
      let timeout;
      return function(...args) {
        const context = this;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
      };
    };
    this.togglePoints = column => {
      const view = new window.google.visualization.DataView(
        this.wrapper.getDataTable()
      );
      const columnCount = view.getNumberOfColumns();
      let colors = [];
      let columns = [];
      for (let i = 0; i < columnCount; i += 1) {
        if (i === 0) {
          this.addSourceColumnTo(columns, i);
        } else if (i === column) {
          if (this.isHidden(i)) {
            this.addSourceColumnTo(columns, i);
            this.restoreColorTo(colors, i);
          } else {
            this.addEmptyColumnTo(columns, i);
            this.hideColumn(colors, i);
          }
        } else if (this.isHidden(i)) {
          this.addEmptyColumnTo(columns, i);
          this.hideColumn(colors, i);
        } else {
          this.addSourceColumnTo(columns, i);
          this.restoreColorTo(colors, i);
        }
      }
      view.setColumns(columns);
      this.props.options.colors = colors;
      this.chart.draw(view, this.props.options);
    };
    this.state = { graphID: props.graph_id || generateUniqueID() };
  }
  componentDidMount() {
    if (typeof window === "undefined") {
      return;
    }
    if (this.props.loadCharts) {
      googleChartLoader
        .init(
          this.props.chartPackages,
          this.props.chartVersion,
          this.props.chartLanguage
        )
        .then(() => {
          this.drawChart();
          this.onResize = this.debounce(this.onResize, 200);
          window.addEventListener("resize", this.onResize);
        });
    } else {
      this.drawChart();
    }
  }
  componentDidUpdate() {
    if (!this.props.loadCharts) {
      this.drawChart();
    } else if (googleChartLoader.isLoading) {
      googleChartLoader.loadScript &&
        googleChartLoader.loadScript.then(() => {
          this.drawChart();
        });
    } else if (googleChartLoader.isLoaded) {
      this.drawChart();
    }
  }
  componentWillUnmount() {
    this.isUnmounted = true;
    googleChartLoader.destroy();
    try {
      if (window) {
        if (window.google && window.google.visualization) {
          window.google.visualization.events.removeAllListeners(this.wrapper);
        }
        window.removeEventListener("resize", this.onResize);
      }
    } catch (err) {
      return;
    }
  }
  render() {
    const divStyle = {
      height: this.props.height || this.props.options.height,
      width: this.props.width || this.props.options.width
    };
    return createElement(
      "div",
      { id: this.state.graphID, style: divStyle },
      this.props.loader ? this.props.loader : "Rendering Chart..."
    );
  }
}
Chart.defaultProps = {
  chartType: "LineChart",
  rows: [],
  columns: [],
  options: {
    chart: {
      title: "Chart Title",
      subtitle: "Subtitle"
    },
    hAxis: { title: "X Label" },
    vAxis: { title: "Y Label" },
    width: "100%",
    height: "100%"
  },
  width: "400px",
  height: "300px",
  chartEvents: [],
  chartActions: null,
  data: null,
  legend_toggle: false,
  allowEmptyRows: false,
  loadCharts: true,
  loader: createElement("div", null, "Rendering Chart"),
  chartPackages: ["corechart"],
  chartVersion: "current",
  chartLanguage: "en",
  numberFormat: null,
  dateFormat: null,
  formatters: [],
  diffdata: null
};

var index = { Chart };

export default index;
export { Chart };
<commit_msg>Read mapsApiKey from props.<commit_after>import { Component, createElement } from "react";

const DEFAULT_CHART_COLORS = [
  "#3366CC",
  "#DC3912",
  "#FF9900",
  "#109618",
  "#990099",
  "#3B3EAC",
  "#0099C6",
  "#DD4477",
  "#66AA00",
  "#B82E2E",
  "#316395",
  "#994499",
  "#22AA99",
  "#AAAA11",
  "#6633CC",
  "#E67300",
  "#8B0707",
  "#329262",
  "#5574A6",
  "#3B3EAC"
];

var DEFAULT_COLORS = /*#__PURE__*/ Object.freeze({
  DEFAULT_CHART_COLORS: DEFAULT_CHART_COLORS,
  default: DEFAULT_CHART_COLORS
});

const getGoogle = (windowAsArg = window) => {
  if (typeof windowAsArg === "undefined") {
    return {};
  }
  if (typeof windowAsArg.google === "undefined") {
    throw new Error("google not in window object. Error in get-google-charts.");
  }
  return windowAsArg.google;
};
const getGoogleCharts = (windowAsArg = window) => {
  if (typeof windowAsArg === "undefined") {
    return {};
  }
  if (typeof windowAsArg.google === "undefined") {
    throw new Error("google not in window object. Error in get-google-charts.");
  }
  return windowAsArg.google.charts;
};

class GoogleChartLoader {
  constructor() {
    this.isLoaded = false;
    this.isLoading = false;
    this.loadScript = null;
    this.destroy = () => {
      this.isLoading = false;
      this.isLoaded = false;
      this.loadScript = null;
    };
    this.init = (packages, version, language, mapsApiKey) => {
      if ((this.isLoading || this.isLoaded) && this.loadScript !== null) {
        return this.loadScript;
      }
      const script =
        typeof window !== "undefined"
          ? require("loadjs")
          : (link, { success: callback }) => callback();
      this.loadScript = new Promise(resolve => {
        script("https://www.gstatic.com/charts/loader.js", {
          success: () => {
            const google_charts = getGoogleCharts(window);
            google_charts.load(version || "current", {
              packages: packages || ["corechart"],
              language: language || "en",
              mapsApiKey
            });
            google_charts.setOnLoadCallback(() => {
              this.isLoaded = true;
              this.isLoading = false;
              resolve();
            });
          }
        });
      });
      this.isLoading = true;
      return this.loadScript;
    };
  }
}
const googleChartLoader = new GoogleChartLoader();

let uniqueID = 0;
const generateUniqueID = () => {
  uniqueID += 1;
  return `reactgooglegraph-${uniqueID}`;
};
class Chart extends Component {
  constructor(props) {
    super(props);
    this.chart = null;
    this.wrapper = null;
    this.hidden_columns = {};
    this.dataTable = [];
    this.isUnmounted = false;
    this.onResize = () => {
      this.drawChart();
    };
    this.onSelectToggle = () => {
      if (this.chart === null) return;
      const selection = this.chart.getSelection();
      if (selection.length > 0) {
        if (selection[0].row == null) {
          const column = selection[0].column;
          this.togglePoints(column);
        }
      }
    };
    this.getColumnColor = columnIndex => {
      if (this.props.options && this.props.options.colors) {
        if (this.props.options.colors[columnIndex]) {
          return this.props.options.colors[columnIndex];
        }
      } else if (columnIndex in DEFAULT_COLORS) {
        return DEFAULT_COLORS[columnIndex];
      }
      return DEFAULT_COLORS[0];
    };
    this.applyNumberFormat = (column, options) => {
      const googlefromWindow = getGoogle(window);
      const formatter = new googlefromWindow.visualization.NumberFormat(
        options
      );
      formatter.format(this.dataTable, column);
    };
    this.applyDateFormat = (column, options) => {
      const googlefromWindow = getGoogle(window);
      const formatter = new googlefromWindow.visualization.DateFormat(options);
      formatter.format(this.dataTable, column);
    };
    this.buildDataTableFromProps = () => {
      const chartType = this.props.chartType;
      const googlefromWindow = getGoogle(window);
      if (this.props.diffdata && this.props.chartType !== null) {
        const diffdata = this.props.diffdata;
        const oldData = googlefromWindow.visualization.arrayToDataTable(
          diffdata.old
        );
        const newData = googlefromWindow.visualization.arrayToDataTable(
          diffdata.new
        );
        const computeDiff =
          googlefromWindow.visualization[chartType].prototype.computeDiff;
        const chartDiff = computeDiff(oldData, newData);
        return chartDiff;
      }
      if (
        this.props.data === null &&
        (this.props.rows && this.props.rows.length === 0) &&
        !this.props.allowEmptyRows === false
      ) {
        throw new Error(
          "Can't build DataTable from rows and columns: rows array in props is empty"
        );
      } else if (
        this.props.data === null &&
        (this.props.columns && this.props.columns.length === 0)
      ) {
        throw new Error(
          "Can't build DataTable from rows and columns: columns array in props is empty"
        );
      }
      if (this.props.data !== null) {
        try {
          this.wrapper.setDataTable(this.props.data);
          const dataTable = this.wrapper.getDataTable();
          return dataTable;
        } catch (err) {
          throw new Error("Failed to set DataTable from data props ! ", err);
        }
      }
      const dataTable = new window.google.visualization.DataTable();
      this.props.columns.forEach(column => {
        dataTable.addColumn(column);
      });
      dataTable.addRows(this.props.rows);
      if (this.props.numberFormat) {
        const { column, options } = this.props.numberFormat;
        this.applyNumberFormat(column, options);
      }
      if (this.props.dateFormat) {
        const { columns, options } = this.props.dateFormat;
        columns.forEach(col => {
          this.applyDateFormat(col, options);
        });
      }
      this.props.formatters.forEach(({ type, column, options }) => {
        switch (type) {
          case "NumberFormat":
            this.applyNumberFormat(column, options);
            break;
          case "DateFormat":
            this.applyDateFormat(column, options);
            break;
          default:
            console.log(`Unkown formatter type: ${type}`);
            break;
        }
      });
      return dataTable;
    };
    this.updateDataTable = () => {
      window.google.visualization.errors.removeAll(
        document.getElementById(this.wrapper.getContainerId())
      );
      this.dataTable.removeRows(0, this.dataTable.getNumberOfRows());
      this.dataTable.removeColumns(0, this.dataTable.getNumberOfColumns());
      this.dataTable = this.buildDataTableFromProps();
      return this.dataTable;
    };
    this.drawChart = () => {
      if (this.isUnmounted) {
        return;
      }
      if (!this.wrapper) {
        const chartConfig = {
          chartType: this.props.chartType,
          options: this.props.options,
          containerId: this.state.graphID
        };
        this.wrapper = new window.google.visualization.ChartWrapper(
          chartConfig
        );
        this.dataTable = this.buildDataTableFromProps();
        this.wrapper.setDataTable(this.dataTable);
        window.google.visualization.events.addOneTimeListener(
          this.wrapper,
          "ready",
          () => {
            this.chart = this.wrapper.getChart();
            this.listenToChartEvents();
            this.addChartActions();
          }
        );
      } else {
        this.updateDataTable();
        this.wrapper.setDataTable(this.dataTable);
        this.wrapper.setOptions(this.props.options);
        if (this.wrapper.getChartType() !== this.props.chartType) {
          window.google.visualization.events.removeAllListeners(this.wrapper);
          this.wrapper.setChartType(this.props.chartType);
          const self = this;
          window.google.visualization.events.addOneTimeListener(
            this.wrapper,
            "ready",
            () => {
              self.chart = self.wrapper.getChart();
              self.listenToChartEvents.call(self);
            }
          );
        }
      }
      this.wrapper.draw();
    };
    this.addChartActions = () => {
      if (this.props.chartActions === null) {
        return;
      }
      this.props.chartActions.forEach(chartAction => {
        this.chart.setAction({
          id: chartAction.id,
          text: chartAction.text,
          action: chartAction.action.bind(this, this.chart)
        });
      });
    };
    this.listenToChartEvents = () => {
      if (this.props.legend_toggle) {
        window.google.visualization.events.addListener(
          this.wrapper,
          "select",
          this.onSelectToggle
        );
      }
      this.props.chartEvents.forEach(chartEvent => {
        if (chartEvent.eventName === "ready") {
          chartEvent.callback(this);
        } else {
          (event => {
            window.google.visualization.events.addListener(
              this.chart,
              event.eventName,
              e => {
                event.callback(this, e);
              }
            );
          })(chartEvent);
        }
      });
    };
    this.buildColumnFromSourceData = columnIndex => {
      return {
        label: this.dataTable.getColumnLabel(columnIndex),
        type: this.dataTable.getColumnType(columnIndex),
        sourceColumn: columnIndex,
        role: this.dataTable.getColumnRole(columnIndex)
      };
    };
    this.buildEmptyColumnFromSourceData = columnIndex => {
      return {
        label: this.dataTable.getColumnLabel(columnIndex),
        type: this.dataTable.getColumnType(columnIndex),
        calc: () => null,
        role: this.dataTable.getColumnRole(columnIndex)
      };
    };
    this.addEmptyColumnTo = (columns, columnIndex) => {
      const emptyColumn = this.buildEmptyColumnFromSourceData(columnIndex);
      columns.push(emptyColumn);
    };
    this.hideColumn = (colors, columnIndex) => {
      if (!this.isHidden(columnIndex)) {
        this.hidden_columns[columnIndex] = {
          color: this.getColumnColor(columnIndex - 1)
        };
      }
      colors.push("#CCCCCC");
    };
    this.addSourceColumnTo = (columns, columnIndex) => {
      const sourceColumn = this.buildColumnFromSourceData(columnIndex);
      columns.push(sourceColumn);
    };
    this.isHidden = columnIndex => {
      return this.hidden_columns[columnIndex] !== undefined;
    };
    this.restoreColorTo = (colors, columnIndex) => {
      let previousColor;
      if (this.isHidden(columnIndex)) {
        previousColor = this.hidden_columns[columnIndex].color;
        delete this.hidden_columns[columnIndex];
      } else {
        previousColor = this.getColumnColor(columnIndex - 1);
      }
      if (columnIndex !== 0) {
        colors.push(previousColor);
      }
    };
    this.debounce = (func, wait) => {
      let timeout;
      return function(...args) {
        const context = this;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
      };
    };
    this.togglePoints = column => {
      const view = new window.google.visualization.DataView(
        this.wrapper.getDataTable()
      );
      const columnCount = view.getNumberOfColumns();
      let colors = [];
      let columns = [];
      for (let i = 0; i < columnCount; i += 1) {
        if (i === 0) {
          this.addSourceColumnTo(columns, i);
        } else if (i === column) {
          if (this.isHidden(i)) {
            this.addSourceColumnTo(columns, i);
            this.restoreColorTo(colors, i);
          } else {
            this.addEmptyColumnTo(columns, i);
            this.hideColumn(colors, i);
          }
        } else if (this.isHidden(i)) {
          this.addEmptyColumnTo(columns, i);
          this.hideColumn(colors, i);
        } else {
          this.addSourceColumnTo(columns, i);
          this.restoreColorTo(colors, i);
        }
      }
      view.setColumns(columns);
      this.props.options.colors = colors;
      this.chart.draw(view, this.props.options);
    };
    this.state = { graphID: props.graph_id || generateUniqueID() };
  }
  componentDidMount() {
    if (typeof window === "undefined") {
      return;
    }
    if (this.props.loadCharts) {
      googleChartLoader
        .init(
          this.props.chartPackages,
          this.props.chartVersion,
          this.props.chartLanguage,
          this.props.mapsApiKey
        )
        .then(() => {
          this.drawChart();
          this.onResize = this.debounce(this.onResize, 200);
          window.addEventListener("resize", this.onResize);
        });
    } else {
      this.drawChart();
    }
  }
  componentDidUpdate() {
    if (!this.props.loadCharts) {
      this.drawChart();
    } else if (googleChartLoader.isLoading) {
      googleChartLoader.loadScript &&
        googleChartLoader.loadScript.then(() => {
          this.drawChart();
        });
    } else if (googleChartLoader.isLoaded) {
      this.drawChart();
    }
  }
  componentWillUnmount() {
    this.isUnmounted = true;
    googleChartLoader.destroy();
    try {
      if (window) {
        if (window.google && window.google.visualization) {
          window.google.visualization.events.removeAllListeners(this.wrapper);
        }
        window.removeEventListener("resize", this.onResize);
      }
    } catch (err) {
      return;
    }
  }
  render() {
    const divStyle = {
      height: this.props.height || this.props.options.height,
      width: this.props.width || this.props.options.width
    };
    return createElement(
      "div",
      { id: this.state.graphID, style: divStyle },
      this.props.loader ? this.props.loader : "Rendering Chart..."
    );
  }
}
Chart.defaultProps = {
  chartType: "LineChart",
  rows: [],
  columns: [],
  options: {
    chart: {
      title: "Chart Title",
      subtitle: "Subtitle"
    },
    hAxis: { title: "X Label" },
    vAxis: { title: "Y Label" },
    width: "100%",
    height: "100%"
  },
  width: "400px",
  height: "300px",
  chartEvents: [],
  chartActions: null,
  data: null,
  legend_toggle: false,
  allowEmptyRows: false,
  loadCharts: true,
  loader: createElement("div", null, "Rendering Chart"),
  chartPackages: ["corechart"],
  chartVersion: "current",
  chartLanguage: "en",
  numberFormat: null,
  dateFormat: null,
  formatters: [],
  diffdata: null
};

var index = { Chart };

export default index;
export { Chart };
<|endoftext|>


<commit_before>import Cast from './cast';

global.chrome = {
  cast: Cast, // eslint-disable-line
};

global.requestHandler = (receiverList) =>
  new Promise((resolve) => resolve(receiverList[0]));

global.castConsole = {
  log: (...args) => {
    if (!global.castDevMode) return;
    castConsole.log(...args); // eslint-disable-line
  },
  info: (...args) => {
    if (!global.castDevMode) return;
    castConsole.info(...args); // eslint-disable-line
  },
  warn: (...args) => {
    if (!global.castDevMode) return;
    castConsole.warn(...args); // eslint-disable-line
  },
  error: (...args) => {
    if (!global.castDevMode) return;
    castConsole.error(...args); // eslint-disable-line
  },
};

module.exports = (requestHandler, dev) => {
  global.requestHandler = requestHandler;
  global.castDevMode = dev;
};
<commit_msg>fix recursive log methods<commit_after>import Cast from './cast';

global.chrome = {
  cast: Cast, // eslint-disable-line
};

global.requestHandler = (receiverList) =>
  new Promise((resolve) => resolve(receiverList[0]));

global.castConsole = {
  log: (...args) => {
    if (!global.castDevMode) return;
    console.log(...args); // eslint-disable-line
  },
  info: (...args) => {
    if (!global.castDevMode) return;
    console.info(...args); // eslint-disable-line
  },
  warn: (...args) => {
    if (!global.castDevMode) return;
    console.warn(...args); // eslint-disable-line
  },
  error: (...args) => {
    if (!global.castDevMode) return;
    console.error(...args); // eslint-disable-line
  },
};

module.exports = (requestHandler, dev) => {
  global.requestHandler = requestHandler;
  global.castDevMode = dev;
};
<|endoftext|>


<commit_before>'use strict';

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  ListView,
  TouchableOpacity
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

let ds = new ListView.DataSource({ rowHasChanged: (row1, row2) => row !== row2 });

export default class WeeklyPlanList extends React.Component {
  constructor(props) {
    super(props);
    let mealArray = [];
    for(let i = 0; i < this.props.data.mealPlansByDate[this.props.selectedDate][this.props.mealType].length; i++) {
      mealArray.push(this.props.data.mealsById[this.props.data.mealPlansByDate[this.props.selectedDate][this.props.mealType][i]]);
    };

    this.state = {
      dataSource: ds.cloneWithRows(mealArray)
    };
  }

  handleDeleteMeal(mealId) {
    this.props.deleteMeal(this.props.userId, this.props.selectedDate, this.props.mealType, mealId);
  }

  componentWillReceiveProps(nextProps) {
    let newMealArray = [];
    let len = nextProps.data.mealPlansByDate[nextProps.selectedDate][nextProps.mealType].length;

    if(this.props.data.mealPlansByDate[this.props.selectedDate][this.props.mealType].length !== nextProps.data.mealPlansByDate[nextProps.selectedDate][nextProps.mealType]) {
      for(let i = 0; i < len; i++) {
        newMealArray.push(nextProps.data.mealsById[nextProps.data.mealPlansByDate[nextProps.selectedDate][nextProps.mealType][i]]);
      };
    };

    this.setState({
      dataSource: ds.cloneWithRows(newMealArray)
    });
  }

  renderRow(mealItem) {
    return (
      <View style={ styles.mealContainer }>
        <Text style={ styles.mealName }>{ mealItem.name }</Text>
        <TouchableOpacity style={ styles.removeButton } onPress={() => this.handleDeleteMeal(mealItem.mealId)}>
          <Icon name='md-remove' size={ 30 } color='#c62733' />
        </TouchableOpacity>
      </View>
    )
  }

  render() {
    return (
      <View style={ styles.container }>
        <ListView
          dataSource={ this.state.dataSource }
          renderRow={ this.renderRow.bind(this) }
          enableEmptySections={ true } />
      </View>
    )
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  mealContainer: {
    height: 50,
    flexDirection: 'row',
    backgroundColor: '#e9e9e9',
    borderRadius: 7,
    marginBottom: 10,
    padding: 5,
    width: 339,
    justifyContent: 'space-between'
  },
  mealName: {
    fontFamily: 'OpenSans',
    fontSize: 18
  },
  removeButton: {

  }
});
<commit_msg>Hot Fix for weeklyplanlist remove button<commit_after>'use strict';

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  Image,
  ListView,
  TouchableOpacity
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

let ds = new ListView.DataSource({ rowHasChanged: (row1, row2) => row !== row2 });

export default class WeeklyPlanList extends React.Component {
  constructor(props) {
    super(props);
    let mealArray = [];
    for(let i = 0; i < this.props.data.mealPlansByDate[this.props.selectedDate][this.props.mealType].length; i++) {
      mealArray.push(this.props.data.mealsById[this.props.data.mealPlansByDate[this.props.selectedDate][this.props.mealType][i]]);
    };

    this.state = {
      dataSource: ds.cloneWithRows(mealArray)
    };
  }

  handleDeleteMeal(mealId) {
    this.props.deleteMeal(this.props.userId, this.props.selectedDate, this.props.mealType, mealId);
  }

  componentWillReceiveProps(nextProps) {
    let newMealArray = [];
    let len = nextProps.data.mealPlansByDate[nextProps.selectedDate][nextProps.mealType].length;

    if(this.props.data.mealPlansByDate[this.props.selectedDate][this.props.mealType].length !== nextProps.data.mealPlansByDate[nextProps.selectedDate][nextProps.mealType]) {
      for(let i = 0; i < len; i++) {
        newMealArray.push(nextProps.data.mealsById[nextProps.data.mealPlansByDate[nextProps.selectedDate][nextProps.mealType][i]]);
      };
    };

    this.setState({
      dataSource: ds.cloneWithRows(newMealArray)
    });
  }

  renderRow(mealItem) {
    return (
      <View style={ styles.mealContainer }>
        <Text style={ styles.mealName }>{ mealItem.name }</Text>
        <TouchableOpacity style={ styles.removeButton } onPress={() => this.handleDeleteMeal(mealItem.mealId)}>
          <Icon name='md-remove-circle' size={ 25 } color='#c62733' />
        </TouchableOpacity>
      </View>
    )
  }

  render() {
    return (
      <View style={ styles.container }>
        <ListView
          dataSource={ this.state.dataSource }
          renderRow={ this.renderRow.bind(this) }
          enableEmptySections={ true } />
      </View>
    )
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  mealContainer: {
    height: 50,
    flexDirection: 'row',
    backgroundColor: '#e9e9e9',
    borderRadius: 7,
    marginBottom: 10,
    padding: 5,
    width: 339,
    justifyContent: 'space-between'
  },
  mealName: {
    fontFamily: 'OpenSans',
    fontSize: 18
  },
  removeButton: {

  }
});
<|endoftext|>


<commit_before>// License headers that will be preserved in distributed bundles.
/**
 * GeoJS
 * @copyright 2013-2016, Kitware, Inc.
 * @license Apache-2.0
 *
 * Bundled with the following libraries:
 *
 * vgl
 * @copyright 2014-2016, Kitware, Inc.
 * @license Apache-2.0
 *
 * Proj4js
 * @copyright 2014, Mike Adair, Richard Greenwood, Didier Richard, Stephen Irons, Olivier Terral and Calvin Metcalf
 * @license MIT
 *
 * gl-matrix
 * @copyright 2015, Brandon Jones, Colin MacKenzie IV
 * @license MIT
 *
 * JQuery
 * @copyright jQuery Foundation and other contributors
 * @license MIT
 *
 * earcut
 * @copyright 2016, Mapbox
 * @license ISC
 */

var $ = require('jquery');
require('./polyfills');

module.exports = $.extend({
  camera: require('./camera'),
  choroplethFeature: require('./choroplethFeature'),
  clock: require('./clock'),
  contourFeature: require('./contourFeature'),
  domRenderer: require('./domRenderer'),
  event: require('./event'),
  feature: require('./feature'),
  featureLayer: require('./featureLayer'),
  fetchQueue: require('./fetchQueue'),
  fileReader: require('./fileReader'),
  geomFeature: require('./geomFeature'),
  graphFeature: require('./graphFeature'),
  imageTile: require('./imageTile'),
  jsonReader: require('./jsonReader'),
  layer: require('./layer'),
  lineFeature: require('./lineFeature'),
  map: require('./map'),
  mapInteractor: require('./mapInteractor'),
  object: require('./object'),
  osmLayer: require('./osmLayer'),
  pathFeature: require('./pathFeature'),
  planeFeature: require('./planeFeature'),
  pointFeature: require('./pointFeature'),
  polygonFeature: require('./polygonFeature'),
  quadFeature: require('./quadFeature'),
  heatmapFeature: require('./heatmapFeature'),
  renderer: require('./renderer'),
  sceneObject: require('./sceneObject'),
  tile: require('./tile'),
  tileCache: require('./tileCache'),
  tileLayer: require('./tileLayer'),
  timestamp: require('./timestamp'),
  transform: require('./transform'),
  vectorFeature: require('./vectorFeature'),
  inherit: require('./inherit'),
  version: require('./version'),
  sha: require('./sha'),

  util: require('./util'),
  jQuery: $,
  d3: require('./d3'),
  gl: require('./gl'),
  canvas: require('./canvas'),
  gui: require('./ui')
}, require('./registry'));

if (window && !window.$) {
  window.$ = $;
}
<commit_msg>Expose jquery as `jQuery` as well<commit_after>// License headers that will be preserved in distributed bundles.
/**
 * GeoJS
 * @copyright 2013-2016, Kitware, Inc.
 * @license Apache-2.0
 *
 * Bundled with the following libraries:
 *
 * vgl
 * @copyright 2014-2016, Kitware, Inc.
 * @license Apache-2.0
 *
 * Proj4js
 * @copyright 2014, Mike Adair, Richard Greenwood, Didier Richard, Stephen Irons, Olivier Terral and Calvin Metcalf
 * @license MIT
 *
 * gl-matrix
 * @copyright 2015, Brandon Jones, Colin MacKenzie IV
 * @license MIT
 *
 * JQuery
 * @copyright jQuery Foundation and other contributors
 * @license MIT
 *
 * earcut
 * @copyright 2016, Mapbox
 * @license ISC
 */

var $ = require('jquery');
require('./polyfills');

module.exports = $.extend({
  camera: require('./camera'),
  choroplethFeature: require('./choroplethFeature'),
  clock: require('./clock'),
  contourFeature: require('./contourFeature'),
  domRenderer: require('./domRenderer'),
  event: require('./event'),
  feature: require('./feature'),
  featureLayer: require('./featureLayer'),
  fetchQueue: require('./fetchQueue'),
  fileReader: require('./fileReader'),
  geomFeature: require('./geomFeature'),
  graphFeature: require('./graphFeature'),
  imageTile: require('./imageTile'),
  jsonReader: require('./jsonReader'),
  layer: require('./layer'),
  lineFeature: require('./lineFeature'),
  map: require('./map'),
  mapInteractor: require('./mapInteractor'),
  object: require('./object'),
  osmLayer: require('./osmLayer'),
  pathFeature: require('./pathFeature'),
  planeFeature: require('./planeFeature'),
  pointFeature: require('./pointFeature'),
  polygonFeature: require('./polygonFeature'),
  quadFeature: require('./quadFeature'),
  heatmapFeature: require('./heatmapFeature'),
  renderer: require('./renderer'),
  sceneObject: require('./sceneObject'),
  tile: require('./tile'),
  tileCache: require('./tileCache'),
  tileLayer: require('./tileLayer'),
  timestamp: require('./timestamp'),
  transform: require('./transform'),
  vectorFeature: require('./vectorFeature'),
  inherit: require('./inherit'),
  version: require('./version'),
  sha: require('./sha'),

  util: require('./util'),
  jQuery: $,
  d3: require('./d3'),
  gl: require('./gl'),
  canvas: require('./canvas'),
  gui: require('./ui')
}, require('./registry'));

if (window && !window.$) {
  window.$ = $;
}
if (window && !window.jQuery) {
  window.jQuery = $;
}
<|endoftext|>


<commit_before>'use strict'

const browserify = require('./browserify')
const uglify = require('./uglify')

/**
 * Load, transform, bundle and compress JS.
 * @public
 * @param {String} filePath - Absolute path to file.
 * @param {?Object} opts - Options.
 * @returns {Promise<String>} JS.
 */
module.exports = async function(filePath, opts = {}) {

	if (typeof filePath !== 'string') throw new Error(`'filePath' must be a string`)
	if (typeof opts !== 'object') throw new Error(`'opts' must be undefined, null or an object`)

	opts = Object.assign({
		optimize: false
	}, opts)

	let output = null

	output = await browserify(filePath, opts)
	output = await uglify(output, opts)

	return output

}

/**
 * Tell Rosid with which file extension it should load the file.
 * @public
 * @param {?Object} opts - Options.
 * @returns {String} File extension.
 */
module.exports.in = function(opts) {

	return (opts != null && opts.in != null) ? opts.in : '.js'

}

/**
 * Tell Rosid with which file extension it should save the file.
 * @public
 * @param {?Object} opts - Options.
 * @returns {String} File extension.
 */
module.exports.out = function(opts) {

	return (opts != null && opts.out != null) ? opts.out : '.js'

}

/**
 * Attach an array to the function, which contains a list of
 * file patterns used by the handler. The array will be used by Rosid for caching purposes.
 * @public
 */
module.exports.cache = [
	'**/*.js',
	'**/*.json'
]<commit_msg>Keep in sync with oder handlers<commit_after>'use strict'

const browserify = require('./browserify')
const uglify = require('./uglify')

/**
 * Load, transform, bundle and compress JS.
 * @public
 * @param {String} filePath - Absolute path to file.
 * @param {?Object} opts - Options.
 * @returns {Promise<String>} JS.
 */
module.exports = async function(filePath, opts = {}) {

	if (typeof filePath !== 'string') throw new Error(`'filePath' must be a string`)
	if (typeof opts !== 'object') throw new Error(`'opts' must be undefined or an object`)

	opts = Object.assign({
		optimize: false
	}, opts)

	let output = null

	output = await browserify(filePath, opts)
	output = await uglify(output, opts)

	return output

}

/**
 * Tell Rosid with which file extension it should load the file.
 * @public
 * @param {?Object} opts - Options.
 * @returns {String} File extension.
 */
module.exports.in = function(opts) {

	return (opts != null && opts.in != null) ? opts.in : '.js'

}

/**
 * Tell Rosid with which file extension it should save the file.
 * @public
 * @param {?Object} opts - Options.
 * @returns {String} File extension.
 */
module.exports.out = function(opts) {

	return (opts != null && opts.out != null) ? opts.out : '.js'

}

/**
 * Attach an array to the function, which contains a list of
 * file patterns used by the handler. The array will be used by Rosid for caching purposes.
 * @public
 */
module.exports.cache = [
	'**/*.js',
	'**/*.json'
]<|endoftext|>


<commit_before>import JavaFormatter from "./javaFormatter"

export default class Formatter {
    constructor(spacing) {
        this.spacing = spacing;
        this.javaFormatter = null
    }

    getJavaFormatter() {
        if (this.javaFormatter === null) {
            this.javaFormatter = new JavaFormatter(this.spacing)
        }
        return this.javaFormatter
    }

    testModule() {
        console.log("I am working")
    }
}

<commit_msg>trying more new things<commit_after>import JavaFormatter from "./javaFormatter"

export default Formatter = {
    createJavaFormatter(spacing) {
        return new JavaFormatter(spacing)
    },

    testModule() {
        console.log("I am working")
    }
}
<|endoftext|>