<commit_before>(function($) {
    $(document).ready(function($) {

        var preview_delayed = false;

        function update_preview_delay() {
            preview_delayed = false;
        }

        $("#id_content_raw").keyup(function() {
            if (!preview_delayed) {
                window.setTimeout(update_preview_delay,1000);
                preview_delayed = true;
                $('a[title="Preview"]').trigger('mousedown');
            }
        });

        mySettings.markupSet.push({
            name: 'Mediacracy',
            key: 'M',
            className:"MediaWindow",
            replaceWith: function(markItUp) {
                return MediacracyPopUp(markItUp);
            },
        }, {
            name: 'Save',
            key: 'S',
            className:"Save",
            replaceWith: function(markItUp) {
                return MediacracySave(markItUp);
            },
        });

        $("#{{ id }}").markItUp(mySettings);
        $('a[title="Preview"]').trigger('mousedown');

    });
})(jQuery);

ForceSaveContinue = function() {
    $("input[name='_continue']").click();
}

MediacracySave = function(markItUp) {
    var the_form = $("form");

    //check if this a new object OR if there are errors already here. If so, force normal save. Otherwise, use ajax.
    if ($(window.location.pathname.split('/')).get(-2) == 'add' || $('ul.errorlist').length>0) {
        ForceSaveContinue();
    }

    $.ajax({ // create an AJAX call...
        data: the_form.serialize()+"&_continue=", // get the form data, send as "save and continue"
        type: the_form.attr('method'), // GET or POST
        url: the_form.attr('action'), // the file to call
        success: function(response) { // on 400 response..
            var success_message = $(response).find('ul.messagelist');
            if (success_message.length > 0) { //success message. Perhaps this should be made more explicit?
                $('ul.messagelist').remove();
                success_message.insertBefore($('#content')).delay(1000).toggle(function() {
                    success_message.remove();
                });
            } else { // did not get success message
                ForceSaveContinue();
            }
        },
        error: function(response) { // on non 400 responses
            ForceSaveContinue();
        }
    });
}

/*

The Textify Page "/medical/treatments/laser/ -- LASER" was changed successfully. You may edit it again below.

*/

MediacracyPopUp = function(markItUp) {
    var url = '{% url mediacracy_window %}';
    var windowName = "Mediacracy";
    var windowSize = "width=820,height=500";

    window.open(url, windowName, windowSize);
}

mediacracy_window_callback = function(target, type, id) {
    target.close();
    var result = '{% templatetag openblock %} show_media "' + type + '" ' + id;
    if (type=='image') {
        result = result + ' file_size="thumbnail|small|medium|large|file" fig_class="left|right"'
    }
    result = result + ' {% templatetag closeblock %}'
    $.markItUp({ replaceWith: result });
}<commit_msg>using new url tag for 1.5 compatibility<commit_after>{% load url from future %}

(function($) {
    $(document).ready(function($) {

        var preview_delayed = false;

        function update_preview_delay() {
            preview_delayed = false;
        }

        $("#id_content_raw").keyup(function() {
            if (!preview_delayed) {
                window.setTimeout(update_preview_delay,1000);
                preview_delayed = true;
                $('a[title="Preview"]').trigger('mousedown');
            }
        });

        mySettings.markupSet.push({
            name: 'Mediacracy',
            key: 'M',
            className:"MediaWindow",
            replaceWith: function(markItUp) {
                return MediacracyPopUp(markItUp);
            },
        }, {
            name: 'Save',
            key: 'S',
            className:"Save",
            replaceWith: function(markItUp) {
                return MediacracySave(markItUp);
            },
        });

        $("#{{ id }}").markItUp(mySettings);
        $('a[title="Preview"]').trigger('mousedown');

    });
})(jQuery);

ForceSaveContinue = function() {
    $("input[name='_continue']").click();
}

MediacracySave = function(markItUp) {
    var the_form = $("form");

    //check if this a new object OR if there are errors already here. If so, force normal save. Otherwise, use ajax.
    if ($(window.location.pathname.split('/')).get(-2) == 'add' || $('ul.errorlist').length>0) {
        ForceSaveContinue();
    }

    $.ajax({ // create an AJAX call...
        data: the_form.serialize()+"&_continue=", // get the form data, send as "save and continue"
        type: the_form.attr('method'), // GET or POST
        url: the_form.attr('action'), // the file to call
        success: function(response) { // on 400 response..
            var success_message = $(response).find('ul.messagelist');
            if (success_message.length > 0) { //success message. Perhaps this should be made more explicit?
                $('ul.messagelist').remove();
                success_message.insertBefore($('#content')).delay(1000).toggle(function() {
                    success_message.remove();
                });
            } else { // did not get success message
                ForceSaveContinue();
            }
        },
        error: function(response) { // on non 400 responses
            ForceSaveContinue();
        }
    });
}

/*

The Textify Page "/medical/treatments/laser/ -- LASER" was changed successfully. You may edit it again below.

*/

MediacracyPopUp = function(markItUp) {
    var url = '{% url 'mediacracy_window' %}';
    var windowName = "Mediacracy";
    var windowSize = "width=820,height=500";

    window.open(url, windowName, windowSize);
}

mediacracy_window_callback = function(target, type, id) {
    target.close();
    var result = '{% templatetag openblock %} show_media "' + type + '" ' + id;
    if (type=='image') {
        result = result + ' file_size="thumbnail|small|medium|large|file" fig_class="left|right"'
    }
    result = result + ' {% templatetag closeblock %}'
    $.markItUp({ replaceWith: result });
}<|endoftext|>


<commit_before>import path from 'path'
import webpack from 'webpack'
import nodeExternals from 'webpack-node-externals'

import getModulesDirs from './get_modules_dirs'
import getWebpackEnvPlugin from './get_webpack_env_plugin'

const getWebpackServerConfig = ({
  resolveConfig,
  deployOptions,
  env,
  alias
}) => {
  const serverIndexPath = path.resolve(__dirname, '../runtime/server/index.js')

  const serverDistDir = path.resolve(
    process.cwd(),
    resolveConfig.distDir,
    'server'
  )

  const isClient = false

  return {
    name: 'Server',
    entry: ['@babel/runtime/regenerator', serverIndexPath],
    context: path.resolve(process.cwd()),
    mode: deployOptions.mode,
    performance: false,
    devtool: 'source-map',
    target: 'node',
    node: {
      __dirname: true,
      __filename: true
    },
    resolve: {
      modules: getModulesDirs(),
      alias
    },
    output: {
      path: serverDistDir,
      filename: 'server.js',
      devtoolModuleFilenameTemplate: '[absolute-resource-path]',
      devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]'
    },
    module: {
      rules: [
        {
          test: /core\/alias\/\$resolve.\w+\.js/,
          use: [
            {
              loader: 'val-loader',
              options: {
                resolveConfig,
                deployOptions,
                isClient
              }
            },
            {
              loader: 'babel-loader',
              options: {
                cacheDirectory: true
              }
            }
          ]
        },
        {
          test: /\.js$/,
          use: {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              env: {
                development: {
                  plugins: ['babel-plugin-object-source']
                }
              }
            }
          },
          exclude: [
            /node_modules/,
            ...getModulesDirs(),
            path.resolve(__dirname, '../../dist')
          ]
        }
      ]
    },
    plugins: [
      getWebpackEnvPlugin({ resolveConfig, deployOptions, env, isClient }),
      new webpack.BannerPlugin({
        banner: 'require("source-map-support").install();',
        raw: true,
        entryOnly: false
      })
    ],
    externals: getModulesDirs().map(modulesDir => nodeExternals({ modulesDir }))
  }
}

export default getWebpackServerConfig
<commit_msg>Update get_webpack_server_config.js<commit_after>import path from 'path'
import webpack from 'webpack'
import nodeExternals from 'webpack-node-externals'

import getModulesDirs from './get_modules_dirs'
import getWebpackEnvPlugin from './get_webpack_env_plugin'

const getWebpackServerConfig = ({
  resolveConfig,
  deployOptions,
  env,
  alias
}) => {
  const serverIndexPath = path.resolve(__dirname, '../runtime/server/index.js')

  const serverDistDir = path.resolve(
    process.cwd(),
    resolveConfig.distDir,
    'server'
  )

  const isClient = false

  return {
    name: 'Server',
    entry: ['@babel/runtime/regenerator', serverIndexPath],
    context: path.resolve(process.cwd()),
    mode: deployOptions.mode,
    performance: false,
    devtool: 'source-map',
    target: 'node',
    node: {
      __dirname: true,
      __filename: true
    },
    resolve: {
      modules: getModulesDirs(),
      alias
    },
    output: {
      path: serverDistDir,
      filename: 'server.js',
      devtoolModuleFilenameTemplate: '[absolute-resource-path]',
      devtoolFallbackModuleFilenameTemplate: '[absolute-resource-path]?[hash]'
    },
    module: {
      rules: [
        {
          test: /core(\/|\\)alias(\/|\\)\$resolve.\w+\.js/,
          use: [
            {
              loader: 'val-loader',
              options: {
                resolveConfig,
                deployOptions,
                isClient
              }
            },
            {
              loader: 'babel-loader',
              options: {
                cacheDirectory: true
              }
            }
          ]
        },
        {
          test: /\.js$/,
          use: {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              env: {
                development: {
                  plugins: ['babel-plugin-object-source']
                }
              }
            }
          },
          exclude: [
            /node_modules/,
            ...getModulesDirs(),
            path.resolve(__dirname, '../../dist')
          ]
        }
      ]
    },
    plugins: [
      getWebpackEnvPlugin({ resolveConfig, deployOptions, env, isClient }),
      new webpack.BannerPlugin({
        banner: 'require("source-map-support").install();',
        raw: true,
        entryOnly: false
      })
    ],
    externals: getModulesDirs().map(modulesDir => nodeExternals({ modulesDir }))
  }
}

export default getWebpackServerConfig
<|endoftext|>


<commit_before>/**
 * @fileOverview the arc guide
 * @author sima.zhang
 */
const Util = require('../../util');
const Base = require('./base');

function calculateAngle(point, center) {
  const x = point.x - center.x;
  const y = point.y - center.y;
  let deg;
  if (y === 0) {
    if (x < 0) {
      deg = Math.PI / 2;
    } else {
      deg = (270 * Math.PI) / 180;
    }
  } else if (x >= 0 && y > 0) {
    deg = Math.PI * 2 - Math.atan(x / y);
  } else if (x <= 0 && y < 0) {
    deg = Math.PI - Math.atan(x / y);
  } else if (x > 0 && y < 0) {
    deg = Math.PI + Math.atan(-x / y);
  } else if (x < 0 && y > 0) {
    deg = Math.atan(x / -y);
  }
  return deg;
}

class Arc extends Base {
  getDefaultCfg() {
    const cfg = super.getDefaultCfg();
    return Util.mix({}, cfg, {
      /**
       * 辅助元素类型
       * @type {String}
       */
      type: 'arc',
      /**
       * 辅助弧线的起始点
       * @type {Object | Function | Array}
       */
      start: null,
      /**
       * 辅助弧线的终止点
       * @type {Object | Function | Array}
       */
      end: null,
      /**
       * 辅助文本的样式配置
       * @type {Object}
       */
      style: {
        stroke: '#999',
        lineWidth: 1
      }
    });
  }

  render(coord, group) {
    const self = this;
    const start = self.parsePoint(coord, self.start);
    const end = self.parsePoint(coord, self.end);
    const coordCenter = coord.getCenter();
    const radius = Math.sqrt((start.x - coordCenter.x) * (start.x - coordCenter.x)
      + (start.y - coordCenter.y) * (start.y - coordCenter.y));
    const startAngle = calculateAngle(start, coordCenter);
    const endAngle = calculateAngle(end, coordCenter);
    const dAngle = (endAngle - startAngle) % (Math.PI * 2);
    const largeArc = dAngle > Math.PI ? 1 : 0;
    const clockwise = endAngle - startAngle >= 0 ? 1 : 0;
    const arcShape = group.addShape('path', {
      zIndex: self.zIndex,
      attrs: Util.mix({
        path: [
          [ 'M', start.x, start.y ],
          [ 'A', radius, radius, startAngle, largeArc, clockwise, end.x, end.y ]
        ]
      }, self.style)
    });
    arcShape.name = 'guide-arc';
    self.appendInfo && arcShape.setSilent('appendInfo', self.appendInfo);
    self.el = arcShape;
  }
}

module.exports = Arc;
<commit_msg>fix(arc): fix unable to draw circle<commit_after>/**
 * @fileOverview the arc guide
 * @author sima.zhang
 */
const Util = require('../../util');
const Base = require('./base');

function calculateAngle(point, center) {
  const x = point.x - center.x;
  const y = point.y - center.y;
  let deg;
  if (y === 0) {
    if (x < 0) {
      deg = Math.PI / 2;
    } else {
      deg = (270 * Math.PI) / 180;
    }
  } else if (x >= 0 && y > 0) {
    deg = Math.PI * 2 - Math.atan(x / y);
  } else if (x <= 0 && y < 0) {
    deg = Math.PI - Math.atan(x / y);
  } else if (x > 0 && y < 0) {
    deg = Math.PI + Math.atan(-x / y);
  } else if (x < 0 && y > 0) {
    deg = Math.atan(x / -y);
  }
  return deg;
}

class Arc extends Base {
  getDefaultCfg() {
    const cfg = super.getDefaultCfg();
    return Util.mix({}, cfg, {
      /**
       * 辅助元素类型
       * @type {String}
       */
      type: 'arc',
      /**
       * 辅助弧线的起始点
       * @type {Object | Function | Array}
       */
      start: null,
      /**
       * 辅助弧线的终止点
       * @type {Object | Function | Array}
       */
      end: null,
      /**
       * 辅助文本的样式配置
       * @type {Object}
       */
      style: {
        stroke: '#999',
        lineWidth: 1
      }
    });
  }

  render(coord, group) {
    const self = this;
    const start = self.parsePoint(coord, self.start);
    const end = self.parsePoint(coord, self.end);
    const coordCenter = coord.getCenter();
    const radius = Math.sqrt((start.x - coordCenter.x) * (start.x - coordCenter.x)
      + (start.y - coordCenter.y) * (start.y - coordCenter.y));
    let path;
    // 处理整圆的情况
    if (Util.isNumberEqual(start.x, end.x) && Util.isNumberEqual(start.y, end.y)) {
      path = [
        [ 'M', start.x, start.y ],
        [ 'A', radius, radius, 0, 1, 1, 2 * coordCenter.x - start.x, 2 * coordCenter.y - start.y ],
        [ 'A', radius, radius, 0, 1, 1, start.x, start.y ]
      ];
    } else {
      const startAngle = calculateAngle(start, coordCenter);
      let endAngle = calculateAngle(end, coordCenter);
      if (endAngle < startAngle) {
        endAngle += (Math.PI * 2);
      }
      const dAngle = (endAngle - startAngle) % (Math.PI * 2);
      const largeArc = dAngle > Math.PI ? 1 : 0;
      path = [
        [ 'M', start.x, start.y ],
        [ 'A', radius, radius, 0, largeArc, 1, end.x, end.y ]
      ];
    }
    const arcShape = group.addShape('path', {
      zIndex: self.zIndex,
      attrs: Util.mix({ path }, self.style)
    });
    arcShape.name = 'guide-arc';
    self.appendInfo && arcShape.setSilent('appendInfo', self.appendInfo);
    self.el = arcShape;
  }
}

module.exports = Arc;
<|endoftext|>


<commit_before>import React from 'react'
import ReactDOMServer from 'react-dom/server'
import PropTypes from 'prop-types'
import _isEqual from 'lodash/isEqual'
import $ from 'jquery'
import 'twix'
import 'fullcalendar'
import 'fullcalendar-scheduler'
import 'fullcalendar/dist/locale/fr.js'
import 'fullcalendar/dist/locale/it.js'
import 'fullcalendar/dist/locale/de.js'
import '!style-loader!css-loader!fullcalendar/dist/fullcalendar.css'
import '!style-loader!css-loader!fullcalendar-scheduler/dist/scheduler.css'
import {injectIntl, intlShape} from 'react-intl'
import {consoleLogger} from 'tocco-util'

import Conflict from '../Conflict'
import NavigationFullCalendar from '../NavigationFullCalendar'
import StyledFullCalendar from './StyledFullCalendar'
window.$ = window.jQuery = require('jquery')
require('bootstrap/dist/js/bootstrap.min.js')

class FullCalendar extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      currentStartDate: null,
      currentEndDate: null,
      wrapperId: new Date().getTime()
    }
  }

  getLicense = () => {
    try {
      return require('./license').key
    } catch (e) {
      consoleLogger.logWarning('This Version runs with the NonCommercial FullCalendar license.')
      return 'CC-Attribution-NonCommercial-NoDerivatives' // noncommercial license
    }
  }

  fixOptions = {
    schedulerLicenseKey: this.getLicense(),
    defaultView: 'timelineDay',
    header: false,
    editable: false,
    height: 'auto',
    resourceAreaWidth: '15%',
    timezone: 'local',
    eventClick: event => this.props.onEventClick(event),
    eventRender: (event, element) => {
      const time = event.start.twix(event.end).format({monthFormat: 'MMMM', dayFormat: 'Do'})
      const tooltipDescriptionContent =

{event.description}

{time}

<Conflict conflictStatus={event.conflict} intl={this.props.intl}/>

      const content = ReactDOMServer.renderToString(tooltipDescriptionContent)

      window.jQuery(element).popover({
        title: event.title,
        animation: true,
        placement: 'bottom',
        trigger: 'hover',
        html: true,
        container: `.${this.state.wrapperId}`,
        content: `${content}`
      })
    }
  }

  resourceColumsRemoveButton = [
    {
      labelText: '',
      field: 'title',
      render: (resource, el) => {
        const button = document.createElement('button')
        button.innerHTML = '−'
        button.className = 'remove-resource-btn'
        button.onclick = () => this.props.onCalendarRemove(resource.entityKey, resource.calendarType)
        el.prepend(button)
      }
    }
  ]

  changeRange = () => {
    const view = this.calendarElement.fullCalendar('getView')

    if (this.props.onDateRangeChange) {
      const startMoment = view.start
      const endMoment = view.end
      if (!startMoment.isSame(this.state.currentStartDate) || !endMoment.isSame(this.state.currentEndDate)) {
        this.props.onDateRangeChange({startDate: startMoment._d, endDate: endMoment._d})
        this.setState({...this.state, currentStartDate: startMoment, currentEndDate: endMoment})
      }
    }
  }

  getFullCalendarOptions = props => {
    const {locale, resources} = props

    const dynamicOptions = {}
    if (this.props.onCalendarRemove) {
      dynamicOptions.resourceColumns = this.resourceColumsRemoveButton
    }

    return {...this.fixOptions, ...dynamicOptions, locale, resources}
  }

  componentDidMount() {
    this.calendarElement = $(this.calendarElementRef)
    this.calendarElement.fullCalendar(this.getFullCalendarOptions(this.props))
    this.changeRange()
    this.forceUpdate()
  }

  componentWillReceiveProps(newProps) {
    this.calendarElement.fullCalendar('option', this.getFullCalendarOptions(newProps))

    if (!_isEqual(newProps.events, this.props.events)) {
      this.calendarElement.fullCalendar('removeEventSources')
      this.calendarElement.fullCalendar('addEventSource', newProps.events)
    }

    if (!_isEqual(newProps.resources, this.props.resources)) {
      this.calendarElement.fullCalendar('refetchResources')
    }
  }

  changeView = (view = 'timelineDay') => {
    this.calendarElement.fullCalendar('changeView', view)
    this.changeRange()
  }

  render = () =>

}

FullCalendar.defaultProps = {
  events: [],
  resources: [],
  locale: 'en'
}

FullCalendar.propTypes = {
  intl: intlShape.isRequired,
  onDateRangeChange: PropTypes.func,
  onCalendarRemove: PropTypes.func,
  onRefresh: PropTypes.func,
  onEventClick: PropTypes.func,
  events: PropTypes.arrayOf(
    PropTypes.shape({
      resourceId: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired,
      start: PropTypes.number.isRequired,
      end: PropTypes.number.isRequired,
      allDay: PropTypes.bool
    }
    )),
  resources: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string.isRequired,
      calendarType: PropTypes.string.isRequired,
      entityKey: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired
    }
    )),
  locale: PropTypes.string,
  isLoading: PropTypes.bool
}

export default injectIntl(FullCalendar)
<commit_msg>fix(scheduler): fix description HTML display<commit_after>import React from 'react'
import ReactDOMServer from 'react-dom/server'
import PropTypes from 'prop-types'
import _isEqual from 'lodash/isEqual'
import $ from 'jquery'
import 'twix'
import 'fullcalendar'
import 'fullcalendar-scheduler'
import 'fullcalendar/dist/locale/fr.js'
import 'fullcalendar/dist/locale/it.js'
import 'fullcalendar/dist/locale/de.js'
import '!style-loader!css-loader!fullcalendar/dist/fullcalendar.css'
import '!style-loader!css-loader!fullcalendar-scheduler/dist/scheduler.css'
import {injectIntl, intlShape} from 'react-intl'
import {consoleLogger} from 'tocco-util'
import {FormattedValue} from 'tocco-ui'

import Conflict from '../Conflict'
import NavigationFullCalendar from '../NavigationFullCalendar'
import StyledFullCalendar from './StyledFullCalendar'
window.$ = window.jQuery = require('jquery')
require('bootstrap/dist/js/bootstrap.min.js')

class FullCalendar extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      currentStartDate: null,
      currentEndDate: null,
      wrapperId: new Date().getTime()
    }
  }

  getLicense = () => {
    try {
      return require('./license').key
    } catch (e) {
      consoleLogger.logWarning('This Version runs with the NonCommercial FullCalendar license.')
      return 'CC-Attribution-NonCommercial-NoDerivatives' // noncommercial license
    }
  }

  fixOptions = {
    schedulerLicenseKey: this.getLicense(),
    defaultView: 'timelineDay',
    header: false,
    editable: false,
    height: 'auto',
    resourceAreaWidth: '15%',
    timezone: 'local',
    eventClick: event => this.props.onEventClick(event),
    eventRender: (event, element) => {
      const time = event.start.twix(event.end).format({monthFormat: 'MMMM', dayFormat: 'Do'})
      const tooltipDescriptionContent =

        <FormattedValue type="html" value={event.description}/>

{time}

<Conflict conflictStatus={event.conflict} intl={this.props.intl}/>

      const content = ReactDOMServer.renderToString(tooltipDescriptionContent)

      window.jQuery(element).popover({
        title: event.title,
        animation: true,
        placement: 'bottom',
        trigger: 'hover',
        html: true,
        container: `.${this.state.wrapperId}`,
        content: `${content}`
      })
    }
  }

  resourceColumsRemoveButton = [
    {
      labelText: '',
      field: 'title',
      render: (resource, el) => {
        const button = document.createElement('button')
        button.innerHTML = '−'
        button.className = 'remove-resource-btn'
        button.onclick = () => this.props.onCalendarRemove(resource.entityKey, resource.calendarType)
        el.prepend(button)
      }
    }
  ]

  changeRange = () => {
    const view = this.calendarElement.fullCalendar('getView')

    if (this.props.onDateRangeChange) {
      const startMoment = view.start
      const endMoment = view.end
      if (!startMoment.isSame(this.state.currentStartDate) || !endMoment.isSame(this.state.currentEndDate)) {
        this.props.onDateRangeChange({startDate: startMoment._d, endDate: endMoment._d})
        this.setState({...this.state, currentStartDate: startMoment, currentEndDate: endMoment})
      }
    }
  }

  getFullCalendarOptions = props => {
    const {locale, resources} = props

    const dynamicOptions = {}
    if (this.props.onCalendarRemove) {
      dynamicOptions.resourceColumns = this.resourceColumsRemoveButton
    }

    return {...this.fixOptions, ...dynamicOptions, locale, resources}
  }

  componentDidMount() {
    this.calendarElement = $(this.calendarElementRef)
    this.calendarElement.fullCalendar(this.getFullCalendarOptions(this.props))
    this.changeRange()
    this.forceUpdate()
  }

  componentWillReceiveProps(newProps) {
    this.calendarElement.fullCalendar('option', this.getFullCalendarOptions(newProps))

    if (!_isEqual(newProps.events, this.props.events)) {
      this.calendarElement.fullCalendar('removeEventSources')
      this.calendarElement.fullCalendar('addEventSource', newProps.events)
    }

    if (!_isEqual(newProps.resources, this.props.resources)) {
      this.calendarElement.fullCalendar('refetchResources')
    }
  }

  changeView = (view = 'timelineDay') => {
    this.calendarElement.fullCalendar('changeView', view)
    this.changeRange()
  }

  render = () =>

}

FullCalendar.defaultProps = {
  events: [],
  resources: [],
  locale: 'en'
}

FullCalendar.propTypes = {
  intl: intlShape.isRequired,
  onDateRangeChange: PropTypes.func,
  onCalendarRemove: PropTypes.func,
  onRefresh: PropTypes.func,
  onEventClick: PropTypes.func,
  events: PropTypes.arrayOf(
    PropTypes.shape({
      resourceId: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired,
      start: PropTypes.number.isRequired,
      end: PropTypes.number.isRequired,
      allDay: PropTypes.bool
    }
    )),
  resources: PropTypes.arrayOf(
    PropTypes.shape({
      id: PropTypes.string.isRequired,
      calendarType: PropTypes.string.isRequired,
      entityKey: PropTypes.string.isRequired,
      title: PropTypes.string.isRequired
    }
    )),
  locale: PropTypes.string,
  isLoading: PropTypes.bool
}

export default injectIntl(FullCalendar)
<|endoftext|>


<commit_before>import '../_styles/Chart.css'

import React, {PropTypes as T} from 'react'
import uniqueId from 'lodash/uniqueId'
const d3 = Object.assign({},
  require('d3-selection'),
  require('d3-scale'),
  require('d3-array'),
  require('d3-axis')
)
/**
 * @component Chart
 * @description Main chart component
 */
class ChartFaC extends React.Component {
  componentWillMount() {
    this.id = uniqueId('Chart')
  }

  componentDidMount() {
    const id = "resize." + this.container.attr('id')
    d3.select(window)
      .on(id, this.forceUpdate.bind(this))
  }

  componentWillUnmount() {
    const id = "resize." + this.container.attr('id')
    d3.select(window)
      .on(id, null)
  }

  componentDidUpdate() {
    const {xTicks, yTicks} = this.props
    const {xScale, yScale} = this.getScales()
    const {xAxis, yAxis, xGrid, yGrid} = this
    d3.select(xAxis)
      .attr('transform', `translate(0, ${this.innerHeight()})`)
      .call(
        d3.axisBottom(xScale)
          .ticks(xTicks)
      )
    d3.select(yAxis)
      .call(
        d3.axisLeft(yScale)
          .ticks(yTicks)
      )
    d3.select(xGrid)
      .attr('transform', `translate(0, ${this.innerHeight()})`)
      .call(
        d3.axisBottom(xScale)
          .ticks(5)
          .tickSize(-this.innerHeight())
          .tickFormat('')
      )
    d3.select(yGrid)
      .call(
        d3.axisLeft(yScale)
          .ticks(5)
          .tickSize(-this.innerWidth())
          .tickFormat('')
      )
  }

  getScales = () => {
    const {props: {data, xAxis, yAxis}, yScale, xScale} = this
    return  {
      xScale: xScale(data, xAxis),
      yScale: yScale(data, yAxis),
    }
  }

  yScale = (data, type) => {
    const scale = this.getScale(type, data, 1)
    return (
      scale
      .range([this.innerHeight(), 0])
    )
  }

  xScale = (data, type) => {
    const scale = this.getScale(type, data, 0)
    return (
      scale
      .range([0, this.innerWidth()])
    )
  }

  getScale = (type, data, index=0) => {
    let scale
    switch(type) {
      case 'band':
        scale = d3.scaleBand()
                  .domain(data.map(d => d[index]))
                  .paddingOuter(0.1)
                  .paddingInner(0.2)
        break
      case 'time':
        scale = d3.scaleTime().domain([
          new Date(this.min(data, d => d[index])),
          new Date(this.max(data, d => d[index]))
        ])
        break
      case 'linear':
      default:
        scale = d3.scaleLinear().domain([
          0,
          d3.max(data, d => d[index])
        ])
    }
    return scale
  }

  min = (data=[], getter) => {
    return d3.min(data, getter)
  }

  max = (data=[], getter) => {
    return d3.max(data, getter)
  }

  innerWidth = () => {
    const {width, margin} = this.props
    return width - margin.left - margin.right
  }

  innerHeight = () => {
    const {height, margin} = this.props
    return height - margin.top - margin.bottom
  }

  targetWidth = () => {
    if (!this.container) return 0
    return parseInt(this.container.style('width'))
  }

  aspectHeight = (aspect) => {
    return Math.round(this.targetWidth() / aspect)
  }

  mouseCoordinates = (e) => {
    const {nativeEvent: {offsetX, offsetY}} = e
    return [offsetX, offsetY]
  }

  render() {
    const {
      margin,
      width,
      height,
      stroke,
      fill,
      data,
      xGrid,
      yGrid,
      className,
      tooltip,
      children,
    } = this.props

    const {
      xScale,
      yScale
    } = this.getScales()

    const {
      mouseCoordinates
    } = this

    const w = this.innerWidth()
    const h = this.innerHeight()

    const aspect = width / height

    return (

 (this.container = d3.select(c))}>
        {tooltip ? tooltip : <none/>}
        <svg width={this.targetWidth() || width || 0}
             height={this.aspectHeight(aspect) || height || 0}
             viewBox={`0 0 ${width || 0} ${height || 0}`}
             ref={c => (this.svg = c)}
             preserveAspectRatio="xMinYMid">
          <g transform={`translate(${margin.left}, ${margin.top})`}>
            <g className="xAxis" ref={c => (this.xAxis = c)}/>
            <g className="yAxis" ref={c => (this.yAxis = c)}/>
          {xGrid &&
            <g className="xGrid" ref={c => (this.xGrid = c)}/>}
          {yGrid &&
            <g className="yGrid" ref={c => (this.yGrid = c)}/>}
            {children({
              data,
              xScale,
              yScale,
              fill,
              stroke,
              w,
              h,
              mouseCoordinates,
            })}
          </g>
        </svg>

    )
  }
}

ChartFaC.propTypes = {
  children: T.func.isRequired,
  data: T.array.isRequired,
  margin: T.shape({
    top: T.number,
    right: T.number,
    bottom: T.number,
    left: T.number,
  }),
  width: T.number,
  height: T.number,
  fill: T.string,
  stroke: T.string,
  yAxis: T.string,
  xAxis: T.string,
  xTicks: T.number,
  yTicks: T.number,
  xGrid: T.bool,
  yGrid: T.bool,
  tooltip: T.element,
  className: T.string,
}

ChartFaC.defaultProps = {
  margin: {top: 30, right: 15, bottom: 80, left: 30},
  fill: '#5B5F97',
  stroke: '#0C105E',
  xAxis: 'linear',
  yAxis: 'linear',
  xTicks: 5,
  yTicks: 5,
  xGrid: true,
  yGrid: true,
  className: 'ChartContainer',
}

export default ChartFaC
<commit_msg>fixed bug when repainting d3 grid<commit_after>import '../_styles/Chart.css'

import React, {PropTypes as T} from 'react'
import uniqueId from 'lodash/uniqueId'
const d3 = Object.assign({},
  require('d3-selection'),
  require('d3-scale'),
  require('d3-array'),
  require('d3-axis')
)
/**
 * @component Chart
 * @description Main chart component
 */
class ChartFaC extends React.Component {
  componentWillMount() {
    this.id = uniqueId('Chart')
  }

  componentDidMount() {
    const id = "resize." + this.container.attr('id')
    d3.select(window)
      .on(id, this.forceUpdate.bind(this))
  }

  componentWillUnmount() {
    const id = "resize." + this.container.attr('id')
    d3.select(window)
      .on(id, null)
  }

  componentWillReceiveProps(props) {
    if (
      props.xTicks !== this.props.xTicks ||
      props.yTicks !== this.props.yTicks
    ) {
      this.d3Update()
    }
  }

  componentDidUpdate() {
    this.d3Update()
  }

  d3Update = () => {
    const {xTicks, yTicks} = this.props
    const {xScale, yScale} = this.getScales()
    const {xAxis, yAxis, xGrid, yGrid} = this
    d3.select(xAxis)
      .attr('transform', `translate(0, ${this.innerHeight()})`)
      .call(
        d3.axisBottom(xScale)
          .ticks(xTicks)
      )
    d3.select(yAxis)
      .call(
        d3.axisLeft(yScale)
          .ticks(yTicks)
      )
    d3.select(xGrid)
      .attr('transform', `translate(0, ${this.innerHeight()})`)
      .call(
        d3.axisBottom(xScale)
          .ticks(5)
          .tickSize(-this.innerHeight())
          .tickFormat('')
      )
    d3.select(yGrid)
      .call(
        d3.axisLeft(yScale)
          .ticks(5)
          .tickSize(-this.innerWidth())
          .tickFormat('')
      )
  }

  getScales = () => {
    const {props: {data, xAxis, yAxis}, yScale, xScale} = this
    return  {
      xScale: xScale(data, xAxis),
      yScale: yScale(data, yAxis),
    }
  }

  yScale = (data, type) => {
    const scale = this.getScale(type, data, 1)
    return (
      scale
      .range([this.innerHeight(), 0])
    )
  }

  xScale = (data, type) => {
    const scale = this.getScale(type, data, 0)
    return (
      scale
      .range([0, this.innerWidth()])
    )
  }

  getScale = (type, data, index=0) => {
    let scale
    switch(type) {
      case 'band':
        scale = d3.scaleBand()
                  .domain(data.map(d => d[index]))
                  .paddingOuter(0.1)
                  .paddingInner(0.2)
        break
      case 'time':
        scale = d3.scaleTime().domain([
          new Date(this.min(data, d => d[index])),
          new Date(this.max(data, d => d[index]))
        ])
        break
      case 'linear':
      default:
        scale = d3.scaleLinear().domain([
          0,
          d3.max(data, d => d[index])
        ])
    }
    return scale
  }

  min = (data=[], getter) => {
    return d3.min(data, getter)
  }

  max = (data=[], getter) => {
    return d3.max(data, getter)
  }

  innerWidth = () => {
    const {width, margin} = this.props
    return width - margin.left - margin.right
  }

  innerHeight = () => {
    const {height, margin} = this.props
    return height - margin.top - margin.bottom
  }

  targetWidth = () => {
    if (!this.container) return 0
    return parseInt(this.container.style('width'))
  }

  aspectHeight = (aspect) => {
    return Math.round(this.targetWidth() / aspect)
  }

  mouseCoordinates = (e) => {
    const {nativeEvent: {offsetX, offsetY}} = e
    return [offsetX, offsetY]
  }

  render() {
    const {
      margin,
      width,
      height,
      stroke,
      fill,
      data,
      xGrid,
      yGrid,
      className,
      tooltip,
      children,
    } = this.props

    const {
      xScale,
      yScale
    } = this.getScales()

    const {
      mouseCoordinates
    } = this

    const w = this.innerWidth()
    const h = this.innerHeight()

    const aspect = width / height

    return (

 (this.container = d3.select(c))}>
        {tooltip ? tooltip : <none/>}
        <svg width={this.targetWidth() || width || 0}
             height={this.aspectHeight(aspect) || height || 0}
             viewBox={`0 0 ${width || 0} ${height || 0}`}
             ref={c => (this.svg = c)}
             preserveAspectRatio="xMinYMid">
          <g transform={`translate(${margin.left}, ${margin.top})`}>
            <g className="xAxis" ref={c => (this.xAxis = c)}/>
            <g className="yAxis" ref={c => (this.yAxis = c)}/>
          {xGrid &&
            <g className="xGrid" ref={c => (this.xGrid = c)}/>}
          {yGrid &&
            <g className="yGrid" ref={c => (this.yGrid = c)}/>}
            {children({
              data,
              xScale,
              yScale,
              fill,
              stroke,
              w,
              h,
              mouseCoordinates,
            })}
          </g>
        </svg>

    )
  }
}

ChartFaC.propTypes = {
  children: T.func.isRequired,
  data: T.array.isRequired,
  margin: T.shape({
    top: T.number,
    right: T.number,
    bottom: T.number,
    left: T.number,
  }),
  width: T.number,
  height: T.number,
  fill: T.string,
  stroke: T.string,
  yAxis: T.string,
  xAxis: T.string,
  xTicks: T.number,
  yTicks: T.number,
  xGrid: T.bool,
  yGrid: T.bool,
  tooltip: T.element,
  className: T.string,
}

ChartFaC.defaultProps = {
  margin: {top: 30, right: 15, bottom: 80, left: 30},
  fill: '#5B5F97',
  stroke: '#0C105E',
  xAxis: 'linear',
  yAxis: 'linear',
  xTicks: 5,
  yTicks: 5,
  xGrid: true,
  yGrid: true,
  className: 'ChartContainer',
}

export default ChartFaC
<|endoftext|>


<commit_before>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import FormBuilder from './FormBuilder';
import _clone from 'lodash/clone';
import _cloneDeep from 'lodash/cloneDeep';
import _camelCase from 'lodash/camelCase';

export default class extends Component {
  static propTypes = {
    form: PropTypes.object.isRequired,
    options: PropTypes.object,
    builder: PropTypes.any,
    onSave: PropTypes.func
  }

  constructor(props) {
    super(props);

    const {form} = props;

    this.state = {
      form: form
        ? _cloneDeep(form)
        : {
          title: '',
          name: '',
          path: '',
          display: 'form',
          type: 'form',
          components: [],
        },
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.form && (prevState.form._id !== nextProps.form._id || prevState.form.modified !== nextProps.form.modified)) {
      return {
        form: _cloneDeep(nextProps.form),
      };
    }

    return null;
  }

  setForm(form) {
    this.setState({
      form
    });
  }

  saveForm() {
    if (this.props.saveForm && typeof this.props.saveForm === 'function') {
      this.props.saveForm(this.state.form);
    }
  }

  handleChange(prop, event) {
    const value = event.target.value;
    this.setState(prev => {
      const form = _clone(prev.form);
      form[prop] = value;

      // If setting title, autogenerate name and path as well.
      if (prop === 'title' && !form._id) {
        form['name'] = _camelCase(value);
        form['path'] = _camelCase(value).toLowerCase();
      }

      return {
        ...prev,
        form,
      };
    });
  }

  render() {
    const {form} = this.state;
    const {saveText} = this.props;

    return (

              Title
              <input
                type="text"
                className="form-control" id="title"
                placeholder="Enter the form title"
                value={this.state.form.title}
                onChange={event => this.handleChange('title', event)}
              />

              Name
              <input
                type="text"
                className="form-control"
                id="name"
                placeholder="Enter the form machine name"
                value={this.state.form.name}
                onChange={event => this.handleChange('name', event)}
              />

              Display as

                <select
                  className="form-control"
                  name="form-display"
                  id="form-display"
                  value={this.state.form.display}
                  onChange={event => this.handleChange('display', event)}
                >
                  <option label="Form" value="form">Form</option>
                  <option label="Wizard" value="wizard">Wizard</option>
                  <option label="PDF" value="pdf">PDF</option>
                </select>

              Type

                <select
                  className="form-control"
                  name="form-type"
                  id="form-type"
                  value={this.state.form.type}
                  onChange={event => this.handleChange('type', event)}
                >
                  <option label="Form" value="form">Form</option>
                  <option label="Resource" value="resource">Resource</option>
                </select>

              Path

                <input
                  type="text"
                  className="form-control"
                  id="path"
                  placeholder="example"
                  style={{'textTransform': 'lowercase', width:'120px'}}
                  value={this.state.form.path}
                  onChange={event => this.handleChange('path', event)}
                />

               this.saveForm()}>
                {saveText}

        <FormBuilder
          key={form._id}
          form={form}
          options={this.props.options}
          onChange={(form) => this.setForm(form)}
          builder={this.props.builder}
        />

    );
  }
}
<commit_msg>Handle form change better.<commit_after>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import FormBuilder from './FormBuilder';
import _set from 'lodash/set';
import _cloneDeep from 'lodash/cloneDeep';
import _camelCase from 'lodash/camelCase';

export default class extends Component {
  static propTypes = {
    form: PropTypes.object.isRequired,
    options: PropTypes.object,
    builder: PropTypes.any,
    onSave: PropTypes.func
  }

  constructor(props) {
    super(props);

    const {form} = props;

    this.state = {
      form: form
        ? _cloneDeep(form)
        : {
          title: '',
          name: '',
          path: '',
          display: 'form',
          type: 'form',
          components: [],
        },
    };
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.form && (prevState.form._id !== nextProps.form._id || prevState.form.modified !== nextProps.form.modified)) {
      return {
        form: _cloneDeep(nextProps.form),
      };
    }

    return null;
  }

  setForm(form) {
    this.setState((state) => {
      state.form.components = form.components;
      return state;
    });
  }

  saveForm() {
    if (this.props.saveForm && typeof this.props.saveForm === 'function') {
      this.props.saveForm(this.state.form);
    }
  }

  handleChange(path, event) {
    const {target} = event;
    const value = target.type === 'checkbox' ? target.checked : target.value;

    this.setState((prev) => {
      const form = _cloneDeep(prev.form);
      _set(form, path, value);

      // If setting title, autogenerate name and path as well.
      if (path === 'title' && !form._id) {
        form.name = _camelCase(value);
        form.path = _camelCase(value).toLowerCase();
      }

      return {
        ...prev,
        form,
      };
    });
  }

  render() {
    const {form} = this.state;
    const {saveText} = this.props;

    return (

              Title
              <input
                type="text"
                className="form-control" id="title"
                placeholder="Enter the form title"
                value={this.state.form.title}
                onChange={event => this.handleChange('title', event)}
              />

              Name
              <input
                type="text"
                className="form-control"
                id="name"
                placeholder="Enter the form machine name"
                value={this.state.form.name}
                onChange={event => this.handleChange('name', event)}
              />

              Display as

                <select
                  className="form-control"
                  name="form-display"
                  id="form-display"
                  value={this.state.form.display}
                  onChange={event => this.handleChange('display', event)}
                >
                  <option label="Form" value="form">Form</option>
                  <option label="Wizard" value="wizard">Wizard</option>
                  <option label="PDF" value="pdf">PDF</option>
                </select>

              Type

                <select
                  className="form-control"
                  name="form-type"
                  id="form-type"
                  value={this.state.form.type}
                  onChange={event => this.handleChange('type', event)}
                >
                  <option label="Form" value="form">Form</option>
                  <option label="Resource" value="resource">Resource</option>
                </select>

              Path

                <input
                  type="text"
                  className="form-control"
                  id="path"
                  placeholder="example"
                  style={{'textTransform': 'lowercase', width:'120px'}}
                  value={this.state.form.path}
                  onChange={event => this.handleChange('path', event)}
                />

               this.saveForm()}>
                {saveText}

        <FormBuilder
          key={form._id}
          form={form}
          options={this.props.options}
          onChange={(form) => this.setForm(form)}
          builder={this.props.builder}
        />

    );
  }
}
<|endoftext|>


<commit_before>import React from 'react';
import SvgCanon from './SvgCanon';
import Fade from 'react-reveal/Fade';
import {
  Link
} from 'react-router-dom';

class HomeMain extends React.Component {

  render(){
    return (

          <Fade>

Currently the lead front-end web developer at Tufts University, I am passionate about building scalable design systems that enhance the user-experience. From hands-on development to high-level strategic planning, I've done it all. Check out my latest work below:

          </Fade>

              <Fade>

                    <Link to="/tufts-magazine" className="project-teaser__content">

                        Tufts Magazine

                        Reimaging an award-winning print publication and bringing it t to life on the web

                    </Link>

              </Fade>
              <Fade>

                    <Link to="/tufts-university-web-standard" className="project-teaser__content">

                        Tufts Web Standard

                        Building a scalable web framework to support rapid production of university-wide Drupal 8 websites

                    </Link>

              </Fade>
              <Fade>

                    <Link to="/boston-college-redesign" className="project-teaser__content">

                        Boston College Website Redesign

                        Enhancing the digital gateway to Boston College using Adobe Experience Manager

                    </Link>

              </Fade>

        <Fade>

                  <Link to="/contact">
                    Located in
                    Watertown Ma
                  </Link>

                    <SvgCanon />

        </Fade>

    )
  }

}

export default HomeMain;<commit_msg>CONTENT - Copy issue on homepage projects<commit_after>import React from 'react';
import SvgCanon from './SvgCanon';
import Fade from 'react-reveal/Fade';
import {
  Link
} from 'react-router-dom';

class HomeMain extends React.Component {

  render(){
    return (

          <Fade>

Currently the lead front-end web developer at Tufts University, I am passionate about building scalable design systems that enhance the user-experience. From hands-on development to high-level strategic planning, I've done it all. Check out my latest work below:

          </Fade>

              <Fade>

                    <Link to="/tufts-magazine" className="project-teaser__content">

                        Tufts Magazine

                        Reimaging an award-winning print publication and bringing it to life on the web

                    </Link>

              </Fade>
              <Fade>

                    <Link to="/tufts-university-web-standard" className="project-teaser__content">

                        Tufts Web Standard

                        Building a scalable web framework to support rapid production of university-wide Drupal 8 websites

                    </Link>

              </Fade>
              <Fade>

                    <Link to="/boston-college-redesign" className="project-teaser__content">

                        Boston College Website Redesign

                        Enhancing the digital gateway to Boston College using Adobe Experience Manager

                    </Link>

              </Fade>

        <Fade>

                  <Link to="/contact">
                    Located in
                    Watertown Ma
                  </Link>

                    <SvgCanon />

        </Fade>

    )
  }

}

export default HomeMain;<|endoftext|>


<commit_before>import React from 'react';
import {
  Text,
  View,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import { connect } from 'react-redux';
import Icon from 'react-native-vector-icons/FontAwesome';
import AwesomeButton from 'react-native-awesome-button';
import Button from 'react-native-button';
import commonStyles from './commonStyles';

const styles = StyleSheet.create({
  buttonContainer: {
    marginTop: 10,
    marginBottom: 10,
  },
  button: {
    padding: 15,
    backgroundColor: '#B69099',
    alignItems: 'center',
  },
  buttonLabel: {
    color: 'white',
    marginBottom: 5,
  },
  buttonIcon: {
    color: 'white',
  },
});

class HomeView extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    const calculatedOdometerReading = this.props.calculatedOdometerReading;
    return (
      <ScrollView style={commonStyles.container} keyboardShouldPersistTaps="always">
        <View style={{ padding: 10, flexDirection: 'row', justifyContent: 'space-between' }}>
          <Text style={{ fontWeight: 'bold', fontSize: 18 }}>
            Aktueller Tachostand: { calculatedOdometerReading } km
          </Text>
          <Button>korrigieren</Button>
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={styles.button}>
            <Text style={styles.buttonLabel}>Betriebsfahrt aufzeichnen</Text>
            <Icon name="suitcase" style={styles.buttonIcon} size={30} />
          </TouchableOpacity>
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={styles.button}>
            <Text style={styles.buttonLabel}>Arbeitsweg aufzeichnen</Text>
            <Icon name="building" style={styles.buttonIcon} size={30} />
          </TouchableOpacity>
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={styles.button}>
            <Text style={styles.buttonLabel}>Privatfahrt aufzeichnen</Text>
            <Icon name="home" style={styles.buttonIcon} size={30} />
          </TouchableOpacity>
        </View>
      </ScrollView>
    );
  }
}

HomeView.propTypes = {
  // from mapStateToProps:
  calculatedOdometerReading: React.PropTypes.number,
  // from mapDispatchToProps:
};

const mapStateToProps = state => ({
  calculatedOdometerReading: state.odometer.calculatedOdometerReading,
});

export default connect(mapStateToProps, null)(HomeView);
<commit_msg>More pleasing colors<commit_after>import React from 'react';
import {
  Text,
  View,
  ScrollView,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import { connect } from 'react-redux';
import Icon from 'react-native-vector-icons/FontAwesome';
import AwesomeButton from 'react-native-awesome-button';
import Button from 'react-native-button';
import commonStyles from './commonStyles';

const styles = StyleSheet.create({
  buttonContainer: {
    marginTop: 10,
    marginBottom: 10,
  },
  button: {
    padding: 15,
    backgroundColor: '#AA3366',
    alignItems: 'center',
  },
  buttonLabel: {
    color: '#F0F0F0',
    marginBottom: 5,
  },
  buttonIcon: {
    color: '#F0F0F0',
  },
});

class HomeView extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    const calculatedOdometerReading = this.props.calculatedOdometerReading;
    return (
      <ScrollView style={commonStyles.container} keyboardShouldPersistTaps="always">
        <View style={{ padding: 10, flexDirection: 'row', justifyContent: 'space-between' }}>
          <Text style={{ fontWeight: 'bold', fontSize: 18 }}>
            Aktueller Tachostand: { calculatedOdometerReading } km
          </Text>
          <Button>korrigieren</Button>
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={styles.button}>
            <Text style={styles.buttonLabel}>Betriebsfahrt aufzeichnen</Text>
            <Icon name="suitcase" style={styles.buttonIcon} size={30} />
          </TouchableOpacity>
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={styles.button}>
            <Text style={styles.buttonLabel}>Arbeitsweg aufzeichnen</Text>
            <Icon name="building" style={styles.buttonIcon} size={30} />
          </TouchableOpacity>
        </View>
        <View style={styles.buttonContainer}>
          <TouchableOpacity style={styles.button}>
            <Text style={styles.buttonLabel}>Privatfahrt aufzeichnen</Text>
            <Icon name="home" style={styles.buttonIcon} size={30} />
          </TouchableOpacity>
        </View>
      </ScrollView>
    );
  }
}

HomeView.propTypes = {
  // from mapStateToProps:
  calculatedOdometerReading: React.PropTypes.number,
  // from mapDispatchToProps:
};

const mapStateToProps = state => ({
  calculatedOdometerReading: state.odometer.calculatedOdometerReading,
});

export default connect(mapStateToProps, null)(HomeView);
<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import { css } from 'glamor';

import Globals from '../utils/Globals';

const styles = {
  container: css({
    alignSelf: 'flex-end',
    display: 'flex',
    '@media(max-width: 720px)': {
      alignSelf: 'flex-end',
      display: 'block',
      width: '80%',
      margin: '0 auto',
    },
  }),
  link: css({
    color: Globals.colors.background,
    padding: '15px 50px',
    background: Globals.colors.main,
    cursor: 'pointer',
    fontWeight: 'lighter',
    textDecoration: 'none',
    position: 'absolute',
    top: '35px',
    right: '30px',
    fontSize: 20,
    borderRadius: 40,

    ':hover': {
      backgroundColor: Globals.colors.white,
    },

    '@media(max-width: 720px)': {
      display: 'block',
      textAlign: 'center',
      position: 'relative',
      marginBottom: '20px',
      top: '0',
      right: '0',
    },
  }),
};

class Ingresso extends PureComponent {
  render() {
    return (

          Ingressos

    );
  }
}

export default Ingresso;
<commit_msg>added Ingressos' button disabled style (#76)<commit_after>import React, { PureComponent } from 'react';
import { css } from 'glamor';

import Globals from '../utils/Globals';

const styles = {
  container: css({
    alignSelf: 'flex-end',
    display: 'flex',
    '@media(max-width: 720px)': {
      alignSelf: 'flex-end',
      display: 'block',
      width: '80%',
      margin: '0 auto',
    },
  }),
  link: css({
    color: Globals.colors.background,
    padding: '15px 50px',
    background: Globals.colors.main,
    cursor: 'pointer',
    fontWeight: 'lighter',
    textDecoration: 'none',
    position: 'absolute',
    top: '35px',
    right: '30px',
    fontSize: 20,
    borderRadius: 40,
    ':not(.is-disabled):hover': {
      backgroundColor: Globals.colors.white,
    },
    '&.is-disabled': {
      backgroundColor: Globals.colors.gray,
      color: Globals.colors.lightGray,
      cursor: 'initial',
    },
    '@media(max-width: 720px)': {
      display: 'block',
      textAlign: 'center',
      position: 'relative',
      marginBottom: '20px',
      top: '0',
      right: '0',
    },
  }),
};

class Ingresso extends PureComponent {
  render() {
    return (

          Ingressos Esgotados

    );
  }
}

export default Ingresso;
<|endoftext|>


<commit_before>import { h } from 'preact'
import { ThemeProvider } from 'styled-components'
import defaultTheme from '../theme'

const Provider = ({ theme, ...props }) => {
  return <ThemeProvider theme={theme || defaultTheme} {...props} />
}

export default Provider
<commit_msg>Provider cascades theme font styling to children<commit_after>import { h } from 'preact'
import styled, { ThemeProvider } from 'styled-components'
import defaultTheme from '../theme'

const Base = styled.div`font-family: ${props => props.theme.font};`

const Provider = ({ theme, ...props }) => {
  return (
    <ThemeProvider theme={theme || defaultTheme}>
      <Base {...props} />
    </ThemeProvider>
  )
}

export default Provider
<|endoftext|>


<commit_before>import Component from '../Component'

const Repeater = (times = 1) => Component((v, next) => {
  for (let i = 1; i <= times; i++) next(v)
})

export default Repeater
<commit_msg>Repeater times parameter mandatory<commit_after>import Component from '../Component'

const Repeater = times => Component((v, next) => {
  for (let i = 1; i <= times; i++) next(v)
})

export default Repeater
<|endoftext|>


<commit_before>/* eslint-disable */
import React from 'react';
import '../assets/sponsors.scss';

const Sponsors = () => (

Sponsors

Interested in sponsoring BoilerMake?

        sponsorship@boilermake.org

Special Thanks to

);

export default Sponsors;
<commit_msg>update capital one link<commit_after>/* eslint-disable */
import React from 'react';
import '../assets/sponsors.scss';

const Sponsors = () => (

Sponsors

Interested in sponsoring BoilerMake?

        sponsorship@boilermake.org

Special Thanks to

);

export default Sponsors;
<|endoftext|>


<commit_before>var fs = require('fs');
module.exports = function(app) {
  app.config([
    'formioComponentsProvider',
    function(formioComponentsProvider) {
      formioComponentsProvider.register('datetime', {
        title: 'Date / Time',
        template: 'formio/components/datetime.html',
        tableView: function(data, component, $interpolate) {
          return $interpolate('{{ "' + data + '" | date: "' + component.format + '" }}')();
        },
        group: 'advanced',
        controller: ['$scope', '$timeout', function($scope, $timeout) {
          if ($scope.builder) return;

          // Close calendar pop up when tabbing off button
          $scope.onKeyDown = function(event) {
            return event.keyCode === 9 ? false : $scope.calendarOpen;
          };

          var dateValue = function() {
            // If the date is set, then return the true date value.
            if ($scope.data[$scope.component.key]) {
              return ($scope.data[$scope.component.key] instanceof Date) ? $scope.data[$scope.component.key] : new Date($scope.data[$scope.component.key]);
            }

            // See if a default date is set.
            if ($scope.component.defaultDate) {
              var defaultDate = new Date($scope.component.defaultDate);
              if (!defaultDate || isNaN(defaultDate.getDate())) {
                try {
                  defaultDate = new Date(eval($scope.component.defaultDate));
                }
                catch (e) {
                  defaultDate = '';
                }
              }

              if (defaultDate && !isNaN(defaultDate.getDate())) {
                return defaultDate;
              }
            }

            // Default to empty.
            return '';
          };

          // Ensure the date value is always a date object when loaded, then unbind the watch.
          var loadComplete = $scope.$watch('data.' + $scope.component.key, function() {
            if (!$scope.data) {
              return;
            }
            var valueSet = !!$scope.data[$scope.component.key];
            var newValue = dateValue();
            if (newValue) {
              $scope.data[$scope.component.key] = newValue;
            }
            if (valueSet) {
              loadComplete();
            }
          });

          // If they have 12 hour time enabled, we need to ensure that we see the meridian in the format.
          if (
            $scope.component.enableTime &&
            $scope.component.timePicker &&
            $scope.component.timePicker.showMeridian &&
            ($scope.component.format.indexOf('mm') !== -1) &&
            ($scope.component.format.indexOf('a') === -1)
          ) {
            $scope.component.format += ' a';
          }
          else {
            $scope.component.format = $scope.component.format.replace(/ a/, '');
          }

          if (!$scope.component.datePicker.maxDate) {
            delete $scope.component.datePicker.maxDate;
          }
          else {
            var maxDate = new Date($scope.component.datePicker.maxDate);
            $scope.component.datePicker.maxDate = new Date(
              maxDate.getUTCFullYear(),
              maxDate.getUTCMonth(),
              maxDate.getUTCDate(),
              23,
              59,
              59,
              999
            );
          }

          if (!$scope.component.datePicker.minDate) {
            delete $scope.component.datePicker.minDate;
          }
          else {
            var minDate = new Date($scope.component.datePicker.minDate);
            $scope.component.datePicker.minDate = new Date(
              minDate.getUTCFullYear(),
              minDate.getUTCMonth(),
              minDate.getUTCDate(),
              0,
              0,
              0,
              0
            );
          }

          $scope.autoOpen = true;
          $scope.onClosed = function() {
            $scope.autoOpen = false;
            $timeout(function() {
              $scope.autoOpen = true;
            }, 250);
          };
        }],
        settings: {
          input: true,
          tableView: true,
          label: '',
          key: 'datetimeField',
          placeholder: '',
          format: 'yyyy-MM-dd HH:mm a',
          enableDate: true,
          enableTime: true,
          defaultDate: '',
          datepickerMode: 'day',
          datePicker: {
            showWeeks: true,
            startingDay: 0,
            initDate: '',
            minMode: 'day',
            maxMode: 'year',
            yearRows: 4,
            yearColumns: 5
            minDate: null,
            maxDate: null
          },
          timePicker: {
            hourStep: 1,
            minuteStep: 1,
            showMeridian: true,
            readonlyInput: false,
            mousewheel: true,
            arrowkeys: true
          },
          protected: false,
          persistent: true,
          clearOnHide: true,
          validate: {
            required: false,
            custom: ''
          }
        }
      });
    }
  ]);
  app.run([
    '$templateCache',
    'FormioUtils',
    function($templateCache, FormioUtils) {
      $templateCache.put('formio/components/datetime.html', FormioUtils.fieldWrap(
        fs.readFileSync(__dirname + '/../templates/components/datetime.html', 'utf8')
      ));
    }
  ]);
};
<commit_msg>Fixing merge issue and missing comma in object properties.<commit_after>var fs = require('fs');
module.exports = function(app) {
  app.config([
    'formioComponentsProvider',
    function(formioComponentsProvider) {
      formioComponentsProvider.register('datetime', {
        title: 'Date / Time',
        template: 'formio/components/datetime.html',
        tableView: function(data, component, $interpolate) {
          return $interpolate('{{ "' + data + '" | date: "' + component.format + '" }}')();
        },
        group: 'advanced',
        controller: ['$scope', '$timeout', function($scope, $timeout) {
          if ($scope.builder) return;

          // Close calendar pop up when tabbing off button
          $scope.onKeyDown = function(event) {
            return event.keyCode === 9 ? false : $scope.calendarOpen;
          };

          var dateValue = function() {
            // If the date is set, then return the true date value.
            if ($scope.data[$scope.component.key]) {
              return ($scope.data[$scope.component.key] instanceof Date) ? $scope.data[$scope.component.key] : new Date($scope.data[$scope.component.key]);
            }

            // See if a default date is set.
            if ($scope.component.defaultDate) {
              var defaultDate = new Date($scope.component.defaultDate);
              if (!defaultDate || isNaN(defaultDate.getDate())) {
                try {
                  defaultDate = new Date(eval($scope.component.defaultDate));
                }
                catch (e) {
                  defaultDate = '';
                }
              }

              if (defaultDate && !isNaN(defaultDate.getDate())) {
                return defaultDate;
              }
            }

            // Default to empty.
            return '';
          };

          // Ensure the date value is always a date object when loaded, then unbind the watch.
          var loadComplete = $scope.$watch('data.' + $scope.component.key, function() {
            if (!$scope.data) {
              return;
            }
            var valueSet = !!$scope.data[$scope.component.key];
            var newValue = dateValue();
            if (newValue) {
              $scope.data[$scope.component.key] = newValue;
            }
            if (valueSet) {
              loadComplete();
            }
          });

          // If they have 12 hour time enabled, we need to ensure that we see the meridian in the format.
          if (
            $scope.component.enableTime &&
            $scope.component.timePicker &&
            $scope.component.timePicker.showMeridian &&
            ($scope.component.format.indexOf('mm') !== -1) &&
            ($scope.component.format.indexOf('a') === -1)
          ) {
            $scope.component.format += ' a';
          }
          else {
            $scope.component.format = $scope.component.format.replace(/ a/, '');
          }

          if (!$scope.component.datePicker.maxDate) {
            delete $scope.component.datePicker.maxDate;
          }
          else {
            var maxDate = new Date($scope.component.datePicker.maxDate);
            $scope.component.datePicker.maxDate = new Date(
              maxDate.getUTCFullYear(),
              maxDate.getUTCMonth(),
              maxDate.getUTCDate(),
              23,
              59,
              59,
              999
            );
          }

          if (!$scope.component.datePicker.minDate) {
            delete $scope.component.datePicker.minDate;
          }
          else {
            var minDate = new Date($scope.component.datePicker.minDate);
            $scope.component.datePicker.minDate = new Date(
              minDate.getUTCFullYear(),
              minDate.getUTCMonth(),
              minDate.getUTCDate(),
              0,
              0,
              0,
              0
            );
          }

          $scope.autoOpen = true;
          $scope.onClosed = function() {
            $scope.autoOpen = false;
            $timeout(function() {
              $scope.autoOpen = true;
            }, 250);
          };
        }],
        settings: {
          input: true,
          tableView: true,
          label: '',
          key: 'datetimeField',
          placeholder: '',
          format: 'yyyy-MM-dd HH:mm a',
          enableDate: true,
          enableTime: true,
          defaultDate: '',
          datepickerMode: 'day',
          datePicker: {
            showWeeks: true,
            startingDay: 0,
            initDate: '',
            minMode: 'day',
            maxMode: 'year',
            yearRows: 4,
            yearColumns: 5,
            minDate: null,
            maxDate: null
          },
          timePicker: {
            hourStep: 1,
            minuteStep: 1,
            showMeridian: true,
            readonlyInput: false,
            mousewheel: true,
            arrowkeys: true
          },
          protected: false,
          persistent: true,
          clearOnHide: true,
          validate: {
            required: false,
            custom: ''
          }
        }
      });
    }
  ]);
  app.run([
    '$templateCache',
    'FormioUtils',
    function($templateCache, FormioUtils) {
      $templateCache.put('formio/components/datetime.html', FormioUtils.fieldWrap(
        fs.readFileSync(__dirname + '/../templates/components/datetime.html', 'utf8')
      ));
    }
  ]);
};
<|endoftext|>


<commit_before>// IE<9 lacks Array.prototype.indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(needle) {
        for (var i=0, l=this.length; i<l; ++i) {
            if (this[i] === needle) return i;
        }
        return -1;
    };
}

django.jQuery(function($){
    // Patch up urlify maps to generate nicer slugs in german
    if(typeof(Downcoder) != "undefined"){
        Downcoder.Initialize() ;
        Downcoder.map["ö"] = Downcoder.map["Ö"] = "oe";
        Downcoder.map["ä"] = Downcoder.map["Ä"] = "ae";
        Downcoder.map["ü"] = Downcoder.map["Ü"] = "ue";
    }

    // .dataset.context instead of getAttribute would be nicer
    var ItemEditor = JSON.parse(
            document.getElementById('item-editor-script').getAttribute('data-context'));

    // Move the item editor to its place
    $('h2:contains(' + ItemEditor.feincmsContentFieldsetName + ')').parent().replaceWith($('#main_wrapper'));

    var currentRegion,
        orderMachine = $('.order-machine'),
        pluginInlineGroups = (function selectPluginInlineGroups() {
            var selector = [];
            for (var i=0; i < ItemEditor.plugins.length; i++) {
                selector.push('#' + ItemEditor.plugins[i][0] + '_set-group');
            }
            return $(selector.join(', '));
        })();

    // Order inlines according to their `ordering` value
    var inlines = pluginInlineGroups.find('.inline-related').detach();
    inlines.sort(function inlinesCompareFunction(a, b) {
        var aOrdering = $(a).find('.field-ordering input').val() || 1e9;
        var bOrdering = $(b).find('.field-ordering input').val() || 1e9;
        return Math.sign(aOrdering - bOrdering);
    });
    orderMachine.append(inlines);
    pluginInlineGroups.hide();

    function moveEmptyFormsToEnd() {
        orderMachine.append(orderMachine.find('.empty-form').detach());
    }
    moveEmptyFormsToEnd();

    // Assing data-region to all inlines.
    // We also want to the data attribute to be visible to selectors (that's why we're using $.attr)
    orderMachine.find('.inline-related:not(.empty-form)').each(function assignRegionDataAttribute() {
        var $this = $(this),
            region = $this.find('.field-region input').val();

        $this.attr('data-region', region);
    });

    // Always move empty forms to the end, because new plugins are inserted
    // just before its empty form. Also, assign region data.
    $(document).on('formset:added', function newForm(event, row, optionsPrefix) {
        moveEmptyFormsToEnd();

        row.find('.field-region input').val(currentRegion);
        row.attr('data-region', currentRegion);
    });

    // Initialize tabs and currentRegion.
    (function() {
        var tabs = $('.tabs>div'), tab;
        tabs.on('click', function() {
            currentRegion = $(this).data('region');
            $('.tabs>div').removeClass('active').filter('[data-region="' + currentRegion + '"]').addClass('active');
            orderMachine.find('.inline-related:not(.empty-form)').hide().filter('[data-region="' + currentRegion + '"]').show();
            window.location.hash = 'tab_' + currentRegion;
        });

        // Restore tab if location hash matches.
        if (window.location.hash && (tab = tabs.filter('[data-region="' + window.location.hash.substr(5) + '"]'))) {
            tab.click();
        } else {
            tabs.eq(0).click();
        }

        // Hide tabs if only one.
        if (tabs.length <= 1) tabs.hide();
    })();

    // Start sortable; hide fieldsets when dragging, and hide fieldsets of to-be-deleted inlines.
    orderMachine.sortable({
        handle: 'h3',
        placeholder: 'placeholder',
        start: function(event, ui) {
            ui.item.find('fieldset').hide();
        },
        stop: function(event, ui) {
            ui.item.find('fieldset').show();
        }
    }).on('click', '.delete>input[type=checkbox]', function toggleForDeletionClass() {
        $(this).closest('.inline-related')[this.checked ? 'addClass' : 'removeClass']('for-deletion');
    });

    // Fill in ordering field and try to keep the current region tab (location hash).
    $('form').submit(function(){
        $('.field-ordering input').each(function assignOrdering(index) {
            this.value = index + 1; // Avoid default=0 just because.
        });

        var form = $(this);
        form.attr('action', form.attr('action') + window.location.hash);
        return true;
    });

    // Cmd-S and Escape behavior.
    $(document).keydown(function handleKeys(event) {
        if (event.which == 83 && event.metaKey) {
            $('form input[name=' + (event.shiftKey ? '_continue' : '_save') + ']').click();
            return false;
        } else if (event.which == 27) {
            orderMachine.sortable('cancel');
        }
    });

    (function buildPluginDropdown() {
        var select = document.createElement('select');
        select.options[0] = new Option(ItemEditor.messages.createNew, '', true);

        for (var i=0; i<ItemEditor.plugins.length; i++) {
            select.options[i + 1] = new Option(ItemEditor.plugins[i][1], ItemEditor.plugins[i][0]);
        }

        select.addEventListener('change', function() {
            $('#' + select.value + '_set-group .add-row a').click();
            select.value = '';
        });

        $(select).appendTo('.machine-control').wrap('

');
    })();

});
<commit_msg>Make JS code more reusable, set ordering for newly added inlines<commit_after>// IE<9 lacks Array.prototype.indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(needle) {
        for (var i=0, l=this.length; i<l; ++i) {
            if (this[i] === needle) return i;
        }
        return -1;
    };
}

django.jQuery(function($){
    // Patch up urlify maps to generate nicer slugs in german
    if(typeof(Downcoder) != "undefined"){
        Downcoder.Initialize() ;
        Downcoder.map["ö"] = Downcoder.map["Ö"] = "oe";
        Downcoder.map["ä"] = Downcoder.map["Ä"] = "ae";
        Downcoder.map["ü"] = Downcoder.map["Ü"] = "ue";
    }

    // .dataset.context instead of getAttribute would be nicer
    var ItemEditor = JSON.parse(
        document.getElementById('item-editor-script').getAttribute('data-context'));

    // Move the item editor to its place
    $('h2:contains(' + ItemEditor.feincmsContentFieldsetName + ')').parent().replaceWith($('#main_wrapper'));

    var currentRegion,
        orderMachine = $('.order-machine');

    function moveEmptyFormsToEnd() {
        orderMachine.append(orderMachine.find('.empty-form').detach());
    }

    function reorderInlines(context) {
        var inlines = context.find('.inline-related').detach();
        inlines.sort(function inlinesCompareFunction(a, b) {
            var aOrdering = $(a).find('.field-ordering input').val() || 1e9;
            var bOrdering = $(b).find('.field-ordering input').val() || 1e9;
            return Math.sign(aOrdering - bOrdering);
        });
        orderMachine.append(inlines);
        moveEmptyFormsToEnd();
    }

    // Assing data-region to all inlines.
    // We also want to the data attribute to be visible to selectors (that's why we're using $.attr)
    function assignRegionDataAttribute() {
        orderMachine.find('.inline-related:not(.empty-form)').each(function() {
            var $this = $(this),
                region = $this.find('.field-region input').val();

            $this.attr('data-region', region);
        });
    }

    var pluginInlineGroups = (function selectPluginInlineGroups() {
        var selector = [];
        for (var i=0; i < ItemEditor.plugins.length; i++) {
            selector.push('#' + ItemEditor.plugins[i][0] + '_set-group');
        }
        return $(selector.join(', '));
    })();

    reorderInlines(pluginInlineGroups);
    pluginInlineGroups.hide();
    assignRegionDataAttribute();

    // Always move empty forms to the end, because new plugins are inserted
    // just before its empty form. Also, assign region data.
    $(document).on('formset:added', function newForm(event, row, optionsPrefix) {
        moveEmptyFormsToEnd();

        row.find('.field-region input').val(currentRegion);
        row.attr('data-region', currentRegion);

        // The formset has already been added at this time — select the next-to-last
        // instead of the last.
        var nextToLast = orderMachine.find('.field-ordering input:not([name*=__prefix__])').eq(-2);
        row.find('.field-ordering input').val(10 + +nextToLast.val());
    });

    // Initialize tabs and currentRegion.
    (function() {
        var tabs = $('.tabs>div'), tab;
        tabs.on('click', function() {
            currentRegion = $(this).data('region');
            $('.tabs>div').removeClass('active').filter('[data-region="' + currentRegion + '"]').addClass('active');
            orderMachine.find('.inline-related:not(.empty-form)').hide().filter('[data-region="' + currentRegion + '"]').show();
            window.location.hash = 'tab_' + currentRegion;
        });

        // Restore tab if location hash matches.
        if (window.location.hash && (tab = tabs.filter('[data-region="' + window.location.hash.substr(5) + '"]'))) {
            tab.click();
        } else {
            tabs.eq(0).click();
        }

        // Hide tabs if only one.
        if (tabs.length <= 1) tabs.hide();
    })();

    // Start sortable; hide fieldsets when dragging, and hide fieldsets of to-be-deleted inlines.
    orderMachine.sortable({
        handle: 'h3',
        placeholder: 'placeholder',
        start: function(event, ui) {
            ui.item.find('fieldset').hide();
        },
        stop: function(event, ui) {
            ui.item.find('fieldset').show();
        }
    }).on('click', '.delete>input[type=checkbox]', function toggleForDeletionClass() {
        $(this).closest('.inline-related')[this.checked ? 'addClass' : 'removeClass']('for-deletion');
    });

    // Fill in ordering field and try to keep the current region tab (location hash).
    $('form').submit(function(){
        $('.field-ordering input').each(function assignOrdering(index) {
            this.value = 10 * (index + 1); // Avoid default=0 just because.
        });

        var form = $(this);
        form.attr('action', form.attr('action') + window.location.hash);
        return true;
    });

    // Cmd-S and Escape behavior.
    $(document).keydown(function handleKeys(event) {
        if (event.which == 83 && event.metaKey) {
            $('form input[name=' + (event.shiftKey ? '_continue' : '_save') + ']').click();
            return false;
        } else if (event.which == 27) {
            orderMachine.sortable('cancel');
        }
    });

    (function buildPluginDropdown() {
        var select = document.createElement('select');
        select.options[0] = new Option(ItemEditor.messages.createNew, '', true);

        for (var i=0; i<ItemEditor.plugins.length; i++) {
            select.options[i + 1] = new Option(ItemEditor.plugins[i][1], ItemEditor.plugins[i][0]);
        }

        select.addEventListener('change', function() {
            $('#' + select.value + '_set-group .add-row a').click();
            select.value = '';
        });

        $(select).appendTo('.machine-control').wrap('

');
    })();

});
<|endoftext|>


<commit_before>/**
 * Created by huangxinghui on 2015/5/19.
 */

var $ = require('jquery');
var plugin = require('../plugin');
var toggle   = '[data-toggle="dropdown"]';
var backdrop = '.dropdown-backdrop';

var Dropdown = plugin('dropdown', {
    events: {
        'click': 'toggle'
    },

    toggle: function (e) {
        var $this = $(this)

        if ($this.is('.disabled, :disabled')) return

        var $parent  = getParent($this)
        var isActive = $parent.hasClass('open')

        clearMenus()

        if (!isActive) {
            if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
                // if mobile we use a backdrop because click events don't delegate
                $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
            }

            var relatedTarget = { relatedTarget: this }
            $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))

            if (e.isDefaultPrevented()) return

            $this
                .trigger('focus')
                .attr('aria-expanded', 'true')

            $parent
                .toggleClass('open')
                .trigger('shown.bs.dropdown', relatedTarget)
        }

        return false
    },

    keydown: function (e) {
        if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return

        var $this = $(this)

        e.preventDefault()
        e.stopPropagation()

        if ($this.is('.disabled, :disabled')) return

        var $parent  = getParent($this)
        var isActive = $parent.hasClass('open')

        if ((!isActive && e.which != 27) || (isActive && e.which == 27)) {
            if (e.which == 27) $parent.find(toggle).trigger('focus')
            return $this.trigger('click')
        }

        var desc = ' li:not(.disabled):visible a'
        var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)

        if (!$items.length) return

        var index = $items.index(e.target)

        if (e.which == 38 && index > 0)                 index--                        // up
        if (e.which == 40 && index < $items.length - 1) index++                        // down
        if (!~index)                                      index = 0

        $items.eq(index).trigger('focus')
    }

});

function clearMenus(e) {
    if (e && e.which === 3) return
    $(backdrop).remove()
    $(toggle).each(function () {
        var $this         = $(this)
        var $parent       = getParent($this)
        var relatedTarget = { relatedTarget: this }

        if (!$parent.hasClass('open')) return

        $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))

        if (e.isDefaultPrevented()) return

        $this.attr('aria-expanded', 'false')
        $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
    })
}

function getParent($this) {
    var selector = $this.attr('data-target')

    if (!selector) {
        selector = $this.attr('href')
        selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
    }

    var $parent = selector && $(selector)

    return $parent && $parent.length ? $parent : $this.parent()
}

$(document)
    .on('click.bs.dropdown.data-api', clearMenus)
    .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
    .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
    .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
    .on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown.prototype.keydown)
    .on('keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown.prototype.keydown)<commit_msg>change dropdown define<commit_after>/**
 * Created by huangxinghui on 2015/5/19.
 */

var $ = require('jquery');
var _ = require('underscore');
var plugin = require('../plugin');
var toggle = '[data-toggle="dropdown"]';

plugin('dropdown', {
    options: {
        triggerEvent: 'click',
        target: null
    },

    _create: function () {
        this.delegate(this.options.triggerEvent, null, _.bind(this.toggle, this));

        this.$parent = this.getParent();
    },

    open: function () {
        if (this.isOpen()) return;

        this._opened = true;
        this.$parent.addClass('open');
        this.trigger('open');
    },

    close: function () {
        if (!this.isOpen()) return;

        this._opened = false;
        this.$parent.removeClass('open');
        this.trigger('close');
    },

    toggle: function (e) {
        this.isOpen() ? this.close() : this.open();
        return false;
    },

    isOpen: function () {
        return this._opened;
    },

    getParent: function () {
        if (this.options.target) {
            return (this.options.target instanceof $ ? this.options.target : $(this.options.target)).parent();
        } else {
            return this.$element.parent();
        }
    }
});

function clearMenus(e) {
    if (e && e.which === 3) return;

    $(toggle).dropdown('close');
}

$(document)
    .on('click.dropdown.data-api', clearMenus)
    .on('click.dropdown.data-api', '[data-toggle="dropdown"]', function (e) {
        $(this).dropdown('toggle');
    });<|endoftext|>


<commit_before>var Select = require('react-select'),
	React = require('react'),
	Field = require('../Field'),
	Note = require('../../components/Note'),
	superagent = require('superagent'),
	_ = require('underscore');

module.exports = Field.create({

	getInitialState: function() {
		return {
			ready: this.props.value ? false : true,
			simpleValue: this.props.value,
			expandedValues: null
		};
	},

	componentDidMount: function() {
		this.loadValues(this.props.value);
	},

	componentWillReceiveProps: function(newProps) {
		if (newProps.value !== this.state.simpleValue) {
			this.setState({
				ready: false,
				simpleValue: newProps.value,
				expandedValues: null
			});
			this.loadValues(newProps.value);
		}
	},

	loadValues: function(input) {
		var expandedValues = [];
		var inputs = _.compact([].concat(input));
		var self = this;

		var finish = function () {
			self.setState({
				ready: true,
				expandedValues: expandedValues
			});
		};

		if (!inputs.length) return finish();

		_.each(inputs, function(input) {
			superagent
				.get('/keystone/api/' + self.props.refList.path + '/get?dataset=simple&id=' + input)
				.set('Accept', 'application/json')
				.end(function (err, res) {
					if (err) throw err;

					var value = res.body;

					expandedValues.push({
						value: value.id,
						label: value.name
					});

					if (expandedValues.length === inputs.length) {
						finish();
					}
				});
		});
	},

	buildFilters: function() {
		var filters = {};

		_.each(this.props.filter, function(value, key) {
			if(_.isString(value) && value[0] == ':') {
				fieldName = value.slice(1);

				var val = self.props.values[fieldName];
				if (val) {
					filters[key] = val;
					return;
				}

				// check if filtering by id and item was already saved
				if (fieldName === ':_id' && Keystone.item) {
					filters[key] = Keystone.item.id;
					return;
				}
			} else {
				filters[key] = value;
			}
		});

		var parts = [];

		_.each(filters, function (val, key) {
			parts.push('filters[' + key + ']=' + encodeURIComponent(val));
		})

		return parts.join('&');
	}.

	buildOptionQuery: function () {
		return 'context=relationship&q=' + input + '&list=' + Keystone.list.path + '&field=' + this.props.path + '&' + this.buildFilters()
	},

	getOptions: function(input, callback) {
		superagent
			.get('/keystone/api/' + this.props.refList.path + '/autocomplete?' + this.buildOptionQuery())
			.set('Accept', 'application/json')
			.end(function (err, res) {
				if (err) throw err;

				var data = res.body;

				callback(null, {
					options: data.items.map(function (item) {
						return {
							value: item.id,
							label: item.name
						};
					}),
					complete: data.total === data.items.length
				});
			});
	},

	renderLoadingUI: function() {
		return
loading...
;
	},

	updateValue: function(simpleValue, expandedValues) {
		this.setState({
			simpleValue: simpleValue,
			expandedValues: expandedValues
		});
		this.props.onChange({
			path: this.props.path,
			value: this.props.many ? _.pluck(expandedValues, 'value') : simpleValue
		});
	},

	renderValue: function() {
		if (!this.state.ready) {
			return this.renderLoadingUI();
		}
		// TODO expand IDs
		if (this.props.many) {
			// a(href='/keystone/' + refList.path + '/' + item.get(field.path), data-ref-path=refList.path).ui-related-item= item.get(field.path)
			return
{this.props.value}
;
		} else if (this.props.many && this.props.value.length) {
			// var body = [];
			//
			// _.each(this.props.value, function (value) {
			// 	body.push({value});
			// }, this);
			//
			// return value;
			return
{this.props.value}
;
		} else {
			return
(not set)
;
		}
	},

	renderField: function() {
		if (!this.state.ready) {
			return this.renderLoadingUI();
		}
		var body = [];

		body.push(<Select multi={this.props.many} onChange={this.updateValue} name={this.props.path} asyncOptions={this.getOptions} value={this.state.expandedValues} />);

		if (!this.props.many && this.props.value) {
			body.push(

					view {this.props.refList.singular.toLowerCase()}

			);
		}

		return body;
	}

});
<commit_msg>Fixing issues with #1005<commit_after>var Select = require('react-select'),
	React = require('react'),
	Field = require('../Field'),
	Note = require('../../components/Note'),
	superagent = require('superagent'),
	_ = require('underscore');

module.exports = Field.create({

	getInitialState: function() {
		return {
			ready: this.props.value ? false : true,
			simpleValue: this.props.value,
			expandedValues: null
		};
	},

	componentDidMount: function() {
		this.loadValues(this.props.value);
	},

	componentWillReceiveProps: function(newProps) {
		if (newProps.value !== this.state.simpleValue) {
			this.setState({
				ready: false,
				simpleValue: newProps.value,
				expandedValues: null
			});
			this.loadValues(newProps.value);
		}
	},

	loadValues: function(input) {
		var expandedValues = [];
		var inputs = _.compact([].concat(input));
		var self = this;

		var finish = function () {
			self.setState({
				ready: true,
				expandedValues: expandedValues
			});
		};

		if (!inputs.length) return finish();

		_.each(inputs, function(input) {
			superagent
				.get('/keystone/api/' + self.props.refList.path + '/get?dataset=simple&id=' + input)
				.set('Accept', 'application/json')
				.end(function (err, res) {
					if (err) throw err;

					var value = res.body;

					expandedValues.push({
						value: value.id,
						label: value.name
					});

					if (expandedValues.length === inputs.length) {
						finish();
					}
				});
		});
	},

	buildFilters: function() {
		var filters = {};

		_.each(this.props.filter, function(value, key) {
			if(_.isString(value) && value[0] == ':') {
				fieldName = value.slice(1);

				var val = self.props.values[fieldName];
				if (val) {
					filters[key] = val;
					return;
				}

				// check if filtering by id and item was already saved
				if (fieldName === ':_id' && Keystone.item) {
					filters[key] = Keystone.item.id;
					return;
				}
			} else {
				filters[key] = value;
			}
		});

		var parts = [];

		_.each(filters, function (val, key) {
			parts.push('filters[' + key + ']=' + encodeURIComponent(val));
		})

		return parts.join('&');
	},

	buildOptionQuery: function (input) {
		return 'context=relationship&q=' + input + '&list=' + Keystone.list.path + '&field=' + this.props.path + '&' + this.buildFilters()
	},

	getOptions: function(input, callback) {
		superagent
			.get('/keystone/api/' + this.props.refList.path + '/autocomplete?' + this.buildOptionQuery(input))
			.set('Accept', 'application/json')
			.end(function (err, res) {
				if (err) throw err;

				var data = res.body;

				callback(null, {
					options: data.items.map(function (item) {
						return {
							value: item.id,
							label: item.name
						};
					}),
					complete: data.total === data.items.length
				});
			});
	},

	renderLoadingUI: function() {
		return
loading...
;
	},

	updateValue: function(simpleValue, expandedValues) {
		this.setState({
			simpleValue: simpleValue,
			expandedValues: expandedValues
		});
		this.props.onChange({
			path: this.props.path,
			value: this.props.many ? _.pluck(expandedValues, 'value') : simpleValue
		});
	},

	renderValue: function() {
		if (!this.state.ready) {
			return this.renderLoadingUI();
		}
		// TODO expand IDs
		if (this.props.many) {
			// a(href='/keystone/' + refList.path + '/' + item.get(field.path), data-ref-path=refList.path).ui-related-item= item.get(field.path)
			return
{this.props.value}
;
		} else if (this.props.many && this.props.value.length) {
			// var body = [];
			//
			// _.each(this.props.value, function (value) {
			// 	body.push({value});
			// }, this);
			//
			// return value;
			return
{this.props.value}
;
		} else {
			return
(not set)
;
		}
	},

	renderField: function() {
		if (!this.state.ready) {
			return this.renderLoadingUI();
		}
		var body = [];

		body.push(<Select multi={this.props.many} onChange={this.updateValue} name={this.props.path} asyncOptions={this.getOptions} value={this.state.expandedValues} />);

		if (!this.props.many && this.props.value) {
			body.push(

					view {this.props.refList.singular.toLowerCase()}

			);
		}

		return body;
	}

});
<|endoftext|>


<commit_before>var FileBrowserDialogue = {
    init : function () {
        // remove tinymce stylesheet.
        var allLinks = document.getElementsByTagName("link");
        allLinks[allLinks.length-1].parentNode.removeChild(allLinks[allLinks.length-1]);
    },
    fileSubmit : function (FileURL) {
        var URL = FileURL;
        var win = tinyMCEPopup.getWindowArg("window");

        // insert information now
        win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = URL;

        // change width/height & show preview
        if (win.ImageDialog){
            if (win.ImageDialog.getImageData)
                win.ImageDialog.getImageData();
            if (win.ImageDialog.showPreviewImage)
                win.ImageDialog.showPreviewImage(URL);
        }

        // close popup window
        tinyMCEPopup.close();
    }
    photoSubmit : function (PhotoURL, PhotoCaption, PhotoTitle) {
        var URL = PhotoURL;
        var win = tinyMCEPopup.getWindowArg("window");

        // insert information now
        win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = URL;
        win.document.getElementById("alt") = PhotoCaption;
        win.document.getElementById("title").value = PhotoTitle;

        // change width/height & show preview
        if (win.ImageDialog){
            if (win.ImageDialog.getImageData)
                win.ImageDialog.getImageData();
            if (win.ImageDialog.showPreviewImage)
                win.ImageDialog.showPreviewImage(URL);
        }

        // close popup window
        tinyMCEPopup.close();
    }
}

tinyMCEPopup.onInit.add(FileBrowserDialogue.init, FileBrowserDialogue);

<commit_msg>Fix missing punctuation for new photoSubmit() function<commit_after>var FileBrowserDialogue = {
    init : function () {
        // remove tinymce stylesheet.
        var allLinks = document.getElementsByTagName("link");
        allLinks[allLinks.length-1].parentNode.removeChild(allLinks[allLinks.length-1]);
    },
    fileSubmit : function (FileURL) {
        var URL = FileURL;
        var win = tinyMCEPopup.getWindowArg("window");

        // insert information now
        win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = URL;

        // change width/height & show preview
        if (win.ImageDialog){
            if (win.ImageDialog.getImageData)
                win.ImageDialog.getImageData();
            if (win.ImageDialog.showPreviewImage)
                win.ImageDialog.showPreviewImage(URL);
        }

        // close popup window
        tinyMCEPopup.close();
    },
    photoSubmit : function (PhotoURL, PhotoCaption, PhotoTitle) {
        var URL = PhotoURL;
        var win = tinyMCEPopup.getWindowArg("window");

        // insert information now
        win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = URL;
        win.document.getElementById("alt").value = PhotoCaption;
        win.document.getElementById("title").value = PhotoTitle;

        // change width/height & show preview
        if (win.ImageDialog){
            if (win.ImageDialog.getImageData)
                win.ImageDialog.getImageData();
            if (win.ImageDialog.showPreviewImage)
                win.ImageDialog.showPreviewImage(URL);
        }

        // close popup window
        tinyMCEPopup.close();
    }
}

tinyMCEPopup.onInit.add(FileBrowserDialogue.init, FileBrowserDialogue);

<|endoftext|>