<commit_before>/**
 *
 * @license
 * Copyright (C) 2016 Joseph Roque
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Joseph Roque
 * @file Tooltip.js
 * @providesModule Tooltip
 * @description Displays a text overlay on the screen at a specified position, to be dismissed by the user
 *
 * @flow
 */
'use strict';

// React imports
import React from 'react';
import {
  AsyncStorage,
  Dimensions,
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

// Type definition for component state.
type State = {
  active: boolean,
  backgroundColor: string,
  callback: ?() => any,
  hAlign: 'left' | 'right',
  text: ?string,
  textColor: string,
  vAlign: 'top' | 'bottom',
  x: number,
  y: number,
};

// Parameters that creating a tooltip accepts
type TooltipOptions = {
  backgroundColor?: string,
  callback?: () => any,
  hAlign: 'left' | 'right' | 'center',
  text: string,
  textColor?: string,
  vAlign: 'top' | 'bottom' | 'center',
  x?: number,
  y?: number,
};

// Imports
const Constants = require('Constants');
const Ionicon = require('react-native-vector-icons/Ionicons');

// For defining width, position of the tooltip
const {width, height} = Dimensions.get('window');
const TOOLTIP_WIDTH_PCT: number = 0.75;

// Size of the dismiss icon
const DISMISS_ICON_SIZE: number = 24;

// Name of the close icon to display
let dismissIcon: string;
if (Platform.OS === 'ios') {
  dismissIcon = 'ios-close';
} else {
  dismissIcon = 'md-close';
}

/** Instance of the tooltip. */
let globalTooltip: any;

class Tooltip extends React.Component {

  /** Represents if the user has seen the tooltip indicating how to search all. */
  static HOW_TO_SEARCH_ALL: string = 'tooltip_search_all';

  /** Represents if the user has seen the tooltip to show building image. */
  static SHOW_BUILDING_IMAGE: string = 'tooltip_show_building_image';

  /**
   * Checks if a certain tooltip has already been acknowledged by a user.
   *
   * @param {string} id     tooltip id to check
   * @param {function} done callback to return result
   */
  static hasSeenTooltip(id: string, done: () => any): void {
    if (id == null || id.length === 0) {
      // If id is invalid, return false
      done(false);
      return;
    }

    AsyncStorage.getItem(id, (err, result) => {
      if (err) {
        // Output any errors, return false
        console.error('Error retrieving tooltip info: ' + id + '. ' + err);
        done(false);
        return;
      }

      // Only return true if the value is exactly equal to true
      done(result === 'true');
    });
  }

  /**
   * Tooltip has been acknowledged by a user.
   *
   * @param {string} id tooltip to acknowledge
   */
  static setHasSeenTooltip(id: string) {
    AsyncStorage.setItem(id, 'true');
  }

  /**
   * Returns true if and only if a tooltip is currently shown.
   *
   * @returns {boolean} false if the tooltip is null or not active, true otherwise.
   */
  static isTooltipActive(): boolean {
    return globalTooltip != null && globalTooltip.state.active;
  }

  /**
   * Shows the tooltip overlaying a certain position, with the text provided.
   *
   * @param {TooltipOptions} options configuration of tooltip
   */
  static showTooltip(options: TooltipOptions) {
    if (globalTooltip != null) {
      // Either center horizontally, or set to provided x value
      let x = 0;
      if (options.hAlign === 'center') {
        x = width / 2 - (width * TOOLTIP_WIDTH_PCT) / 2;
      } else {
        x = options.x ? options.x : 0;
      }

      // Either center vertically, or set to provided y value
      let y = 0;
      if (options.vAlign === 'center') {
        y = height / 2;
      } else {
        y = options.y ? options.y : 0;
      }

      globalTooltip.setState({
        active: true,
        backgroundColor: options.backgroundColor ? options.backgroundColor : Constants.Colors.charcoalGrey,
        callback: options.callback,
        hAlign: options.hAlign,
        text: options.text,
        textColor: options.textColor ? options.textColor : Constants.Colors.primaryWhiteText,
        vAlign: options.vAlign,
        x: x,
        y: y,
      });
    }
  }

  /** State of the component. */
  state: State;

  /**
   * Declares initial state.
   *
   * @param {{}} props props of the component
   */
  constructor(props: {}) {
    super(props);

    this.state = {
      active: false,
      backgroundColor: Constants.Colors.charcoalGrey,
      callback: null,
      hAlign: 'left',
      text: null,
      textColor: Constants.Colors.primaryWhiteText,
      vAlign: 'top',
      x: 0,
      y: 0,
    };
  }

  /**
   * Stores a reference to this Tooltip instance in a variable.
   */
  componentDidMount(): void {

    /* eslint-disable consistent-this */

    globalTooltip = this;

    /* eslint-disable consistent-this */

  }

  /**
   * Clears the reference to this Tooltip.
   */
  componentWillUnmount(): void {
    globalTooltip = null;
  }

  /**
   * Hides the tooltip when clicked.
   */
  _dismiss(): void {
    if (this.state.callback) {
      this.state.callback();
    }

    this.setState({
      active: false,
    });
  }

  /**
   * Displays the Tooltip if it is active.
   *
   * @returns {?ReactElement<any>} the tooltip, if this.state.active is true, null otherwise.
   */
  render(): ?ReactElement< any > {
    if (!this.state.active) {
      return null;
    }

    let hAlign: Object = {};
    if (this.state.hAlign === 'right') {
      hAlign = {
        right: this.state.x,
      };
    } else {
      hAlign = {
        left: this.state.x,
      };
    }

    let vAlign: Object = {};
    if (this.state.vAlign === 'bottom') {
      vAlign = {
        bottom: this.state.y,
      };
    } else {
      vAlign = {
        top: this.state.y,
      };
    }

    return (
      <TouchableOpacity
          style={[{position: 'absolute'}, hAlign, vAlign]}
          onPress={this._dismiss.bind(this)}>
        <View style={[_styles.tooltip, {backgroundColor: this.state.backgroundColor}]}>
          <Text style={[_styles.tooltipText, {color: this.state.textColor}]}>{this.state.text}</Text>
          <Ionicon
              color={Constants.Colors.secondaryWhiteText}
              name={dismissIcon}
              size={DISMISS_ICON_SIZE}
              style={_styles.tooltipIcon} />
        </View>
      </TouchableOpacity>
    );
  }
}

// Private styles for the component
const _styles = StyleSheet.create({
  tooltip: {
    width: width * TOOLTIP_WIDTH_PCT,
    borderRadius: 5,
    flexDirection: 'row',
    alignItems: 'center',
  },
  tooltipText: {
    flex: 1,
    margin: 10,
    fontSize: Constants.Text.Medium,
  },
  tooltipIcon: {
    marginRight: 10,
  },
});

module.exports = Tooltip;
<commit_msg>Add animation to tooltip show/dismiss<commit_after>/**
 *
 * @license
 * Copyright (C) 2016 Joseph Roque
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Joseph Roque
 * @file Tooltip.js
 * @providesModule Tooltip
 * @description Displays a text overlay on the screen at a specified position, to be dismissed by the user
 *
 * @flow
 */
'use strict';

// React imports
import React from 'react';
import {
  AsyncStorage,
  Dimensions,
  LayoutAnimation,
  Platform,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

// Type definition for component state.
type State = {
  active: boolean,
  backgroundColor: string,
  callback: ?() => any,
  hAlign: 'left' | 'right',
  text: ?string,
  textColor: string,
  vAlign: 'top' | 'bottom',
  x: number,
  y: number,
};

// Parameters that creating a tooltip accepts
type TooltipOptions = {
  backgroundColor?: string,
  callback?: () => any,
  hAlign: 'left' | 'right' | 'center',
  text: string,
  textColor?: string,
  vAlign: 'top' | 'bottom' | 'center',
  x?: number,
  y?: number,
};

// Imports
const Constants = require('Constants');
const Ionicon = require('react-native-vector-icons/Ionicons');

// For defining width, position of the tooltip
const {width, height} = Dimensions.get('window');
const TOOLTIP_WIDTH_PCT: number = 0.75;

// Size of the dismiss icon
const DISMISS_ICON_SIZE: number = 24;

// Name of the close icon to display
let dismissIcon: string;
if (Platform.OS === 'ios') {
  dismissIcon = 'ios-close';
} else {
  dismissIcon = 'md-close';
}

/** Instance of the tooltip. */
let globalTooltip: any;

class Tooltip extends React.Component {

  /** Represents if the user has seen the tooltip indicating how to search all. */
  static HOW_TO_SEARCH_ALL: string = 'tooltip_search_all';

  /** Represents if the user has seen the tooltip to show building image. */
  static SHOW_BUILDING_IMAGE: string = 'tooltip_show_building_image';

  /**
   * Checks if a certain tooltip has already been acknowledged by a user.
   *
   * @param {string} id     tooltip id to check
   * @param {function} done callback to return result
   */
  static hasSeenTooltip(id: string, done: () => any): void {
    if (id == null || id.length === 0) {
      // If id is invalid, return false
      done(false);
      return;
    }

    AsyncStorage.getItem(id, (err, result) => {
      if (err) {
        // Output any errors, return false
        console.error('Error retrieving tooltip info: ' + id + '. ' + err);
        done(false);
        return;
      }

      // Only return true if the value is exactly equal to true
      done(result === 'true');
    });
  }

  /**
   * Tooltip has been acknowledged by a user.
   *
   * @param {string} id tooltip to acknowledge
   */
  static setHasSeenTooltip(id: string) {
    AsyncStorage.setItem(id, 'true');
  }

  /**
   * Returns true if and only if a tooltip is currently shown.
   *
   * @returns {boolean} false if the tooltip is null or not active, true otherwise.
   */
  static isTooltipActive(): boolean {
    return globalTooltip != null && globalTooltip.state.active;
  }

  /**
   * Shows the tooltip overlaying a certain position, with the text provided.
   *
   * @param {TooltipOptions} options configuration of tooltip
   */
  static showTooltip(options: TooltipOptions) {
    if (globalTooltip != null) {
      // Either center horizontally, or set to provided x value
      let x = 0;
      if (options.hAlign === 'center') {
        x = width / 2 - (width * TOOLTIP_WIDTH_PCT) / 2;
      } else {
        x = options.x ? options.x : 0;
      }

      // Either center vertically, or set to provided y value
      let y = 0;
      if (options.vAlign === 'center') {
        y = height / 2;
      } else {
        y = options.y ? options.y : 0;
      }

      LayoutAnimation.easeInEaseOut();
      globalTooltip.setState({
        active: true,
        backgroundColor: options.backgroundColor ? options.backgroundColor : Constants.Colors.charcoalGrey,
        callback: options.callback,
        hAlign: options.hAlign,
        text: options.text,
        textColor: options.textColor ? options.textColor : Constants.Colors.primaryWhiteText,
        vAlign: options.vAlign,
        x: x,
        y: y,
      });
    }
  }

  /** State of the component. */
  state: State;

  /**
   * Declares initial state.
   *
   * @param {{}} props props of the component
   */
  constructor(props: {}) {
    super(props);

    this.state = {
      active: false,
      backgroundColor: Constants.Colors.charcoalGrey,
      callback: null,
      hAlign: 'left',
      text: null,
      textColor: Constants.Colors.primaryWhiteText,
      vAlign: 'top',
      x: 0,
      y: 0,
    };
  }

  /**
   * Stores a reference to this Tooltip instance in a variable.
   */
  componentDidMount(): void {

    /* eslint-disable consistent-this */

    globalTooltip = this;

    /* eslint-disable consistent-this */

  }

  /**
   * Clears the reference to this Tooltip.
   */
  componentWillUnmount(): void {
    globalTooltip = null;
  }

  /**
   * Hides the tooltip when clicked.
   */
  _dismiss(): void {
    if (this.state.callback) {
      this.state.callback();
    }

    LayoutAnimation.easeInEaseOut();
    this.setState({
      active: false,
    });
  }

  /**
   * Displays the Tooltip if it is active.
   *
   * @returns {?ReactElement<any>} the tooltip, if this.state.active is true, null otherwise.
   */
  render(): ?ReactElement< any > {
    if (!this.state.active) {
      return null;
    }

    let hAlign: Object = {};
    if (this.state.hAlign === 'right') {
      hAlign = {
        right: this.state.x,
      };
    } else {
      hAlign = {
        left: this.state.x,
      };
    }

    let vAlign: Object = {};
    if (this.state.vAlign === 'bottom') {
      vAlign = {
        bottom: this.state.y,
      };
    } else {
      vAlign = {
        top: this.state.y,
      };
    }

    return (
      <TouchableOpacity
          style={[{position: 'absolute'}, hAlign, vAlign]}
          onPress={this._dismiss.bind(this)}>
        <View style={[_styles.tooltip, {backgroundColor: this.state.backgroundColor}]}>
          <Text style={[_styles.tooltipText, {color: this.state.textColor}]}>{this.state.text}</Text>
          <Ionicon
              color={Constants.Colors.secondaryWhiteText}
              name={dismissIcon}
              size={DISMISS_ICON_SIZE}
              style={_styles.tooltipIcon} />
        </View>
      </TouchableOpacity>
    );
  }
}

// Private styles for the component
const _styles = StyleSheet.create({
  tooltip: {
    width: width * TOOLTIP_WIDTH_PCT,
    borderRadius: 5,
    flexDirection: 'row',
    alignItems: 'center',
  },
  tooltipText: {
    flex: 1,
    margin: 10,
    fontSize: Constants.Text.Medium,
  },
  tooltipIcon: {
    marginRight: 10,
  },
});

module.exports = Tooltip;
<|endoftext|>


<commit_before>/**
 * Created by bjedrzejewski on 05/10/2015.
 */

angular.module('bitcoinTransactionControllers', ['txDirectives']).controller('TransactionCtrl', ['$routeParams', 'TxData', function ($routeParams, TxData) {
    var that = this;
    that.nodes = [];
    that.links = [];

    that.rparam = $routeParams.hash;
    that.reqFail = false;
    //unexpanded nodes - 2 arrays for processing
    that.uNodes = [];
    that.newUNodes = [];
    that.expanding = false;

    //function that expands and updates nodes
    that.expandNodes = function () {
        //needs handling for this being repeatedly called
        if(that.expanding){
            return;
        }
        that.expanding = true;
        that.uNodes = that.newUNodes;
        that.newUNodes = [];

        function asyncExpand(i1) {
            if (i1 >= that.uNodes.length) {
                that.expanding = false;
                return;
            } else {
                function asyncExpandInner(i2, j) {
                    if (j >= that.uNodes[i2].vin.length) {
                        asyncExpand(++i2, 0);
                    }
                    else {
                        if (that.uNodes[i2].vin[j].txid)
                            TxData.get({hashValue: that.uNodes[i2].vin[j].txid}, function (newTx) {
                                var thisNumber = that.nodes.length;
                                var originNumber = that.uNodes[i2].oNumber;
                                that.uNodes[i2].expanded = true;
                                newTx.oNumber = thisNumber;
                                newTx.x = that.uNodes[i2].x;
                                newTx.y = that.uNodes[i2].y;
                                that.links.push({'target': newTx.oNumber, 'source': that.uNodes[i2].oNumber});
                                that.nodes.push(newTx);
                                that.newUNodes.push(newTx);
                                asyncExpandInner(i2, ++j);
                            }, function (errorResult) {
                                console.log('error: ' + errorResult);
                            });
                        else {
                            console.log('bingo ended');
                            that.uNodes[i2].ended = true;
                            asyncExpandInner(i2, ++j);
                        }
                    }
                }

                asyncExpandInner(i1, 0);
            }
        }

        asyncExpand(0);

    }

    if (that.rparam.length === 64) {
        TxData.get({hashValue: that.rparam}, function (tx) {
            that.tx = tx;
            that.tx.oNumber = 0;
            that.tx.initNode = true;
            that.tx.x = 200;
            that.tx.y = 200;
            that.nodes.push(tx);
            that.newUNodes.push(tx);
        }, function (errorResult) {
            that.reqFail = true;
        });
    } else {
        that.reqFail = true;
    }

}]);<commit_msg>Comment fix<commit_after>/**
 * Created by bjedrzejewski on 05/10/2015.
 */

angular.module('bitcoinTransactionControllers', ['txDirectives']).controller('TransactionCtrl', ['$routeParams', 'TxData', function ($routeParams, TxData) {
    var that = this;
    that.nodes = [];
    that.links = [];

    that.rparam = $routeParams.hash;
    that.reqFail = false;
    //unexpanded nodes - 2 arrays for processing
    that.uNodes = [];
    that.newUNodes = [];
    that.expanding = false;

    //function that expands and updates nodes
    that.expandNodes = function () {
        //will work because js is single threaded
        if(that.expanding){
            return;
        }
        that.expanding = true;
        that.uNodes = that.newUNodes;
        that.newUNodes = [];

        function asyncExpand(i1) {
            if (i1 >= that.uNodes.length) {
                that.expanding = false;
                return;
            } else {
                function asyncExpandInner(i2, j) {
                    if (j >= that.uNodes[i2].vin.length) {
                        asyncExpand(++i2, 0);
                    }
                    else {
                        if (that.uNodes[i2].vin[j].txid)
                            TxData.get({hashValue: that.uNodes[i2].vin[j].txid}, function (newTx) {
                                var thisNumber = that.nodes.length;
                                var originNumber = that.uNodes[i2].oNumber;
                                that.uNodes[i2].expanded = true;
                                newTx.oNumber = thisNumber;
                                newTx.x = that.uNodes[i2].x;
                                newTx.y = that.uNodes[i2].y;
                                that.links.push({'target': newTx.oNumber, 'source': that.uNodes[i2].oNumber});
                                that.nodes.push(newTx);
                                that.newUNodes.push(newTx);
                                asyncExpandInner(i2, ++j);
                            }, function (errorResult) {
                                console.log('error: ' + errorResult);
                            });
                        else {
                            console.log('bingo ended');
                            that.uNodes[i2].ended = true;
                            asyncExpandInner(i2, ++j);
                        }
                    }
                }

                asyncExpandInner(i1, 0);
            }
        }

        asyncExpand(0);

    }

    if (that.rparam.length === 64) {
        TxData.get({hashValue: that.rparam}, function (tx) {
            that.tx = tx;
            that.tx.oNumber = 0;
            that.tx.initNode = true;
            that.tx.x = 200;
            that.tx.y = 200;
            that.nodes.push(tx);
            that.newUNodes.push(tx);
        }, function (errorResult) {
            that.reqFail = true;
        });
    } else {
        that.reqFail = true;
    }

}]);<|endoftext|>


<commit_before>const path = require('path');
const nodeExternals = require('webpack-node-externals');
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');

const getScripts = function () {
    let script = [{src: `${process.env.CLIENT_STATIC_URL}/polyfill.min.js`}];
    if (process.env.NODE_ENV === 'production') {
        script.push({
            src: `https://www.googletagmanager.com/gtag/js?id=AW-773868544`, async: true
        });
        script.push({
            innerHTML: "window.dataLayer = window.dataLayer || []; " +
                "function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'AW-773868544');"
        });
    }
    return script;
};

module.exports = {
    head: {
        title: 'DumondaMe',
        meta: [
            {charset: 'utf-8'},
            {name: 'viewport', content: 'width=device-width, initial-scale=1'},
            {hid: 'mobile-web-app-capable', name: 'mobile-web-app-capable', content: 'yes'},
            {hid: 'theme-color', name: 'theme-color', content: '#009e97'},
            {hid: 'og:type', property: 'og:type', content: 'website'},
            {hid: 'og:url', property: 'og:url', content: 'https://www.dumonda.me/'},
            {hid: 'og:site_name', property: 'og:site_name', content: 'Dumonda Me'},
            {
                hid: 'og:image', property: 'og:image',
                content: `${process.env.CLIENT_STATIC_URL}/img/socialMedia/preview.jpg`
            },
            {hid: 'twitter:card', property: 'twitter:card', content: 'summary'},
            {hid: 'twitter:url', property: 'twitter:url', content: 'https://www.dumonda.me/'},
            {
                hid: 'twitter:image', property: 'twitter:image',
                content: `${process.env.CLIENT_STATIC_URL}/img/socialMedia/preview.jpg`
            }
        ],
        noscript: [{innerHTML: "This website requires JavaScript", body: true}],
        link: [
            {rel: 'icon', type: 'image/x-icon', href: `${process.env.CLIENT_STATIC_URL}/favicon.ico`},
            {rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto:300,400,500'}
        ],
        script: getScripts(),
        __dangerouslyDisableSanitizers: ['script']
    },
    dev: (process.env.NODE_ENV !== 'production'),
    env: {
        staticUrl: process.env.CLIENT_STATIC_URL,
        isProduction: process.env.NODE_ENV === 'production',
        oAuthGoogleClientUrl: process.env.OAUTH_GOOGLE_CLIENT_URL,
        oAuthOutlookClientUrl: process.env.OAUTH_OUTLOOK_CLIENT_URL
    },
    router: {
        scrollBehavior: function () {
            return {x: 0, y: 0}
        }
    },
    modules: [
        ['@nuxtjs/pwa', {meta: false, oneSignal: false}],
        '@nuxtjs/proxy',
        '@nuxtjs/axios',
        ['nuxt-matomo', {matomoUrl: process.env.MATOMO_URL, siteId: process.env.MATOMO_SIDE_ID}],
        'nuxt-sass-resources-loader'
    ],
    sassResources: [
        path.resolve(__dirname, 'assets/style/variables.scss'),
        path.resolve(__dirname, 'assets/style/card.scss'),
        path.resolve(__dirname, 'assets/style/layout.scss')
    ],
    loading: {
        color: '#009e97'
    },
    transition: {
        name: 'page',
        mode: 'out-in',
        css: false,
        duration: 0
    },
    axios: {
        prefix: '/api/',
        proxy: true
    },
    render: {
        resourceHints: false
    },
    manifest: {
        name: 'DumondaMe',
        "short_name": 'DumondaMe',
        lang: 'de'
    },
    build: {
        transpile: [/^vuetify/],
        plugins: [
            new VuetifyLoaderPlugin()
        ],
        optimizeCSS: true,
        extend(config, {isServer}) {
            if (isServer) {
                config.externals = [
                    nodeExternals({
                        whitelist: [/^vuetify/]
                    })
                ]
            }
        }
    },
    plugins: ['~/plugins/i18n.js',
        '~/plugins/moment.js',
        '~/plugins/vuetify.js',
        '~/plugins/axios.js'],
    css: [
        '~/assets/style/app.styl',
        'cropperjs/dist/cropper.min.css',
        '@mdi/font/css/materialdesignicons.min.css'
    ]
};
<commit_msg>Added apple-mobile-web-app-capable and start url to manifest.<commit_after>const path = require('path');
const nodeExternals = require('webpack-node-externals');
const VuetifyLoaderPlugin = require('vuetify-loader/lib/plugin');

const getScripts = function () {
    let script = [{src: `${process.env.CLIENT_STATIC_URL}/polyfill.min.js`}];
    if (process.env.NODE_ENV === 'production') {
        script.push({
            src: `https://www.googletagmanager.com/gtag/js?id=AW-773868544`, async: true
        });
        script.push({
            innerHTML: "window.dataLayer = window.dataLayer || []; " +
                "function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'AW-773868544');"
        });
    }
    return script;
};

module.exports = {
    head: {
        title: 'DumondaMe',
        meta: [
            {charset: 'utf-8'},
            {name: 'viewport', content: 'width=device-width, initial-scale=1'},
            {hid: 'mobile-web-app-capable', name: 'mobile-web-app-capable', content: 'yes'},
            {hid: 'apple-mobile-web-app-capable', name: 'apple-mobile-web-app-capable', content: 'yes'},
            {hid: 'apple-mobile-web-app-status-bar-style', name: 'apple-mobile-web-app-status-bar-style',
                content: 'default'},
            {hid: 'theme-color', name: 'theme-color', content: '#009e97'},
            {hid: 'og:type', property: 'og:type', content: 'website'},
            {hid: 'og:url', property: 'og:url', content: 'https://www.dumonda.me/'},
            {hid: 'og:site_name', property: 'og:site_name', content: 'Dumonda Me'},
            {
                hid: 'og:image', property: 'og:image',
                content: `${process.env.CLIENT_STATIC_URL}/img/socialMedia/preview.jpg`
            },
            {hid: 'twitter:card', property: 'twitter:card', content: 'summary'},
            {hid: 'twitter:url', property: 'twitter:url', content: 'https://www.dumonda.me/'},
            {
                hid: 'twitter:image', property: 'twitter:image',
                content: `${process.env.CLIENT_STATIC_URL}/img/socialMedia/preview.jpg`
            }
        ],
        noscript: [{innerHTML: "This website requires JavaScript", body: true}],
        link: [
            {rel: 'icon', type: 'image/x-icon', href: `${process.env.CLIENT_STATIC_URL}/favicon.ico`},
            {rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto:300,400,500'}
        ],
        script: getScripts(),
        __dangerouslyDisableSanitizers: ['script']
    },
    dev: (process.env.NODE_ENV !== 'production'),
    env: {
        staticUrl: process.env.CLIENT_STATIC_URL,
        isProduction: process.env.NODE_ENV === 'production',
        oAuthGoogleClientUrl: process.env.OAUTH_GOOGLE_CLIENT_URL,
        oAuthOutlookClientUrl: process.env.OAUTH_OUTLOOK_CLIENT_URL
    },
    router: {
        scrollBehavior: function () {
            return {x: 0, y: 0}
        }
    },
    modules: [
        ['@nuxtjs/pwa', {meta: false, oneSignal: false}],
        '@nuxtjs/proxy',
        '@nuxtjs/axios',
        ['nuxt-matomo', {matomoUrl: process.env.MATOMO_URL, siteId: process.env.MATOMO_SIDE_ID}],
        'nuxt-sass-resources-loader'
    ],
    sassResources: [
        path.resolve(__dirname, 'assets/style/variables.scss'),
        path.resolve(__dirname, 'assets/style/card.scss'),
        path.resolve(__dirname, 'assets/style/layout.scss')
    ],
    loading: {
        color: '#009e97'
    },
    transition: {
        name: 'page',
        mode: 'out-in',
        css: false,
        duration: 0
    },
    axios: {
        prefix: '/api/',
        proxy: true
    },
    render: {
        resourceHints: false
    },
    manifest: {
        name: 'DumondaMe',
        "short_name": 'DumondaMe',
        lang: 'de',
        "start_url": '/'
    },
    build: {
        transpile: [/^vuetify/],
        plugins: [
            new VuetifyLoaderPlugin()
        ],
        optimizeCSS: true,
        extend(config, {isServer}) {
            if (isServer) {
                config.externals = [
                    nodeExternals({
                        whitelist: [/^vuetify/]
                    })
                ]
            }
        }
    },
    plugins: ['~/plugins/i18n.js',
        '~/plugins/moment.js',
        '~/plugins/vuetify.js',
        '~/plugins/axios.js'],
    css: [
        '~/assets/style/app.styl',
        'cropperjs/dist/cropper.min.css',
        '@mdi/font/css/materialdesignicons.min.css'
    ]
};
<|endoftext|>


<commit_before>"use strict"

function callHandler (event, handler, next, reject) {
    setImmediate(() => {
        try {
            handler[0](event, handler[1], handler[2], next);
        } catch (err) {
            reject(err);
        }
    });
}

function extendEvent (event, call, args, data) {
    event.flow = call;
    event.data = data;
    event.args = args;
    return event;
}

module.exports = (args) => {
    return new Promise((resolve, reject) => {

        const call = args[0]
        const sequence = args[1];
        const event = args[2];
        let data = args[3];
        let index = 0;
        let handler = sequence[0][index];

        const next = (err, chunk, stream) => {

            if (err) {
                return reject(err);
            }

            if (chunk !== undefined && chunk !== null) {
                data = chunk;
            }

            event.output = extendEvent(stream || event.output, call, data, sequence[1].A);

            // emit stream errors on event
            if (stream.listenerCount('error') < 1) {
                stream.on('error', (err) => event.emit('error', err));
            }

            handler = sequence[0][++index];
            if (!handler) {
                return resolve(stream);
            }

            callHandler(stream, handler, next, reject);
        };

        event.output = extendEvent(event.output, call, data, sequence[1].A);
        callHandler(event.output, handler, next, reject);
    });
};
<commit_msg>fix args order for extendEvent<commit_after>"use strict"

function callHandler (event, handler, next, reject) {
    setImmediate(() => {
        try {
            handler[0](event, handler[1], handler[2], next);
        } catch (err) {
            reject(err);
        }
    });
}

function extendEvent (event, call, args, data) {
    event.flow = call;
    event.data = data;
    event.args = args;
    return event;
}

module.exports = (args) => {
    return new Promise((resolve, reject) => {

        const call = args[0]
        const sequence = args[1];
        const event = args[2];
        let data = args[3];
        let index = 0;
        let handler = sequence[0][index];

        const next = (err, chunk, stream) => {

            if (err) {
                return reject(err);
            }

            if (chunk !== undefined && chunk !== null) {
                data = chunk;
            }

            event.output = extendEvent(stream || event.output, call, sequence[1].A, data);

            // emit stream errors on event
            if (stream.listenerCount('error') < 1) {
                stream.on('error', (err) => event.emit('error', err));
            }

            handler = sequence[0][++index];
            if (!handler) {
                return resolve(stream);
            }

            callHandler(stream, handler, next, reject);
        };

        event.output = extendEvent(event.output, call, sequence[1].A, data);
        callHandler(event.output, handler, next, reject);
    });
};
<|endoftext|>


<commit_before>//<![CDATA[
var browser     = '';
var version     = '';
var entrance    = '';
var cond        = '';

// BROWSER?
if (browser == '') {
	if (navigator.appName.indexOf('Microsoft') != -1)
		browser = 'IE'
	else if (navigator.appName.indexOf('Netscape') != -1)
		browser = 'Netscape'
	else
		browser = 'IE';
}
if (version == '') {
	version= navigator.appVersion;
	paren = version.indexOf('(');
	whole_version = navigator.appVersion.substring(0,paren-1);
	version = parseInt(whole_version);
}

if (browser == 'IE' && version < 7) {
	document.write('');
}

document.write('');

///////////////////////////////////////////
// jQuery code for columns / widgets part 1
///////////////////////////////////////////

var noCols = 2;
var printed3 = false;
var printed4 = false;
var printed5 = false;
var printed6 = false;
var printed7 = false;
var printed8 = false;
var printed9 = false;
var printed10 = false;

function correctWidgetDisplay(noCols){
	var percent = ( 100 / noCols ) - 0.1;
	var percentStr = percent.toString() + '%';

	// set all column widths
	jQuery('.ui-sortable').width(percentStr);
}

// function to insert a new column we can place content into (from saved state)
function printColumn(newNum){
	if(newNum > noCols)
		noCols = newNum;

	document.write("

");
	correctWidgetDisplay(noCols);

	// connect new column with other columns
	jQuery('.ui-sortable').sortable({connectWith: '.ui-sortable', dropOnEmpty: true, handle: '.widgetheader', change: showSave});
}

function createColumn(colPos){
	if (colpos == "col3" && printed3 == false){
		printColumn(3);
		printed3=true;
	}
	else if (colpos == "col4" && printed4 == false){
		printColumn(4);
		printed4=true;
	}
	else if (colpos == "col5" && printed5 == false){
		printColumn(5);
		printed5=true;
	}
	else if (colpos == "col6" && printed6 == false){
		printColumn(6);
		printed6=true;
	}
	else if (colpos == "col7" && printed7 == false){
		printColumn(7);
		printed7=true;
	}
	else if (colpos == "col8" && printed8 == false){
		printColumn(8);
		printed8=true;
	}
	else if (colpos == "col9" && printed9 == false){
		printColumn(9);
		printed9=true;
	}
	else if (colpos == "col10" && printed10 == false){
		printColumn(10);
		printed10=true;
	}
}
///////////////// end widget code part 1 /////////////////////////

// jQuery function to define dropdown menu size
jQuery(document).ready(function () {
    var hwindow  = '';
    hwindow = (jQuery(window).height()-35);
    // Force the size dropdown menu
    jQuery('#navigation ul li ul').css('max-height', hwindow);

    ///////////////////////////////////////////
	// jQuery code for columns / widgets part 2
	///////////////////////////////////////////

	jQuery('#col2').css("float","left");
	jQuery('

 Add column

 Delete column

 ').insertBefore('#niftyOutter.fakeClass');

	// on click add a new column and change column widths
	jQuery('#addCol').click(function(){
		if( noCols < 10 ){
			var colAfter = noCols;
			noCols++;

			// insert new column
			jQuery('#col' + (colAfter).toString() ).after("

");

			correctWidgetDisplay(noCols);

			// connect new column with other columns
			jQuery('.ui-sortable').sortable({connectWith: '.ui-sortable', dropOnEmpty: true, handle: '.widgetheader', change: showSave});
		}
	});

	// on click delete a columns and change column widths
	jQuery('#delCol').click(function(){
		if( noCols > 2 ){
			var colToDel = noCols;
			noCols -= 1;

			correctWidgetDisplay(noCols);

			// get column contents before deletion
			var colContent = jQuery('#col' + colToDel ).html();

			// remove column
			jQuery('#col' + colToDel ).remove();

			// append deleted columns content to preceeding column
			jQuery(colContent).appendTo('#col' + noCols );

			showSave();
		}
	});
});
//]]>
<commit_msg>add user messages and change cursor for theme pfsense_ng_fs<commit_after>//<![CDATA[
var browser     = '';
var version     = '';
var entrance    = '';
var cond        = '';

// BROWSER?
if (browser == '') {
	if (navigator.appName.indexOf('Microsoft') != -1)
		browser = 'IE'
	else if (navigator.appName.indexOf('Netscape') != -1)
		browser = 'Netscape'
	else
		browser = 'IE';
}
if (version == '') {
	version= navigator.appVersion;
	paren = version.indexOf('(');
	whole_version = navigator.appVersion.substring(0,paren-1);
	version = parseInt(whole_version);
}

if (browser == 'IE' && version < 7) {
	document.write('');
}

document.write('');

///////////////////////////////////////////
// jQuery code for columns / widgets part 1
///////////////////////////////////////////

var noCols = 2;
var printed3 = false;
var printed4 = false;
var printed5 = false;
var printed6 = false;
var printed7 = false;
var printed8 = false;
var printed9 = false;
var printed10 = false;

function correctWidgetDisplay(noCols){
	var percent = ( 100 / noCols ) - 0.1;
	var percentStr = percent.toString() + '%';

	// set all column widths
	jQuery('.ui-sortable').width(percentStr);
}

// function to insert a new column we can place content into (from saved state)
function printColumn(newNum){
	if(newNum > noCols)
		noCols = newNum;

	document.write("

");
	correctWidgetDisplay(noCols);

	// connect new column with other columns
	jQuery('.ui-sortable').sortable({connectWith: '.ui-sortable', dropOnEmpty: true, handle: '.widgetheader', change: showSave});
}

function createColumn(colPos){
	if (colpos == "col3" && printed3 == false){
		printColumn(3);
		printed3=true;
	}
	else if (colpos == "col4" && printed4 == false){
		printColumn(4);
		printed4=true;
	}
	else if (colpos == "col5" && printed5 == false){
		printColumn(5);
		printed5=true;
	}
	else if (colpos == "col6" && printed6 == false){
		printColumn(6);
		printed6=true;
	}
	else if (colpos == "col7" && printed7 == false){
		printColumn(7);
		printed7=true;
	}
	else if (colpos == "col8" && printed8 == false){
		printColumn(8);
		printed8=true;
	}
	else if (colpos == "col9" && printed9 == false){
		printColumn(9);
		printed9=true;
	}
	else if (colpos == "col10" && printed10 == false){
		printColumn(10);
		printed10=true;
	}
}
///////////////// end widget code part 1 /////////////////////////

// jQuery function to define dropdown menu size
jQuery(document).ready(function () {
    var hwindow  = '';
    hwindow = (jQuery(window).height()-35);
    // Force the size dropdown menu
    jQuery('#navigation ul li ul').css('max-height', hwindow);

    ///////////////////////////////////////////
	// jQuery code for columns / widgets part 2
	///////////////////////////////////////////

	jQuery('#col2').css("float","left");
	jQuery('

 Add column

 Delete column

').insertBefore('#niftyOutter.fakeClass');

	// on click add a new column and change column widths
	jQuery('#addCol').click(function(){
		if( noCols < 10 ){
			var colAfter = noCols;
			noCols++;

			// insert new column
			jQuery('#col' + (colAfter).toString() ).after("

");

			correctWidgetDisplay(noCols);

			// connect new column with other columns
			jQuery('.ui-sortable').sortable({connectWith: '.ui-sortable', dropOnEmpty: true, handle: '.widgetheader', change: showSave});
		}
		else{
			jQuery('#columnWarningText').html('Maximum number of columns reached').show().delay(1000).fadeOut(1000);
		}
	});

	// on click delete a columns and change column widths
	jQuery('#delCol').click(function(){
		if( noCols > 2 ){
			var colToDel = noCols;
			noCols -= 1;

			correctWidgetDisplay(noCols);

			// get column contents before deletion
			var colContent = jQuery('#col' + colToDel ).html();

			// remove column
			jQuery('#col' + colToDel ).remove();

			// append deleted columns content to preceeding column
			jQuery(colContent).appendTo('#col' + noCols );

			showSave();
		}
		else{
			jQuery('#columnWarningText').html('Minimum number of columns reached').show().delay(1000).fadeOut(1000);
		}
	});
});
//]]>
<|endoftext|>


<commit_before>/**
 * localize.js
 */

/* api */
const {i18n} = browser;

/* constants */
import {EXT_LOCALE} from "./constant.js";
const DATA_I18N = "data-i18n";

/**
 * localize attribute value
 * @param {Object} elm - element
 * @returns {void}
 */
export const localizeAttr = async elm => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE &&
      elm.hasAttribute(DATA_I18N)) {
    const [id] = elm.getAttribute(DATA_I18N).split(/\s*,\s*/);
    if (id) {
      const attrs = {
        alt: "alt",
        ariaLabel: "aria-label",
        href: "href",
        placeholder: "placeholder",
        title: "title",
      };
      const items = Object.entries(attrs);
      for (const item of items) {
        const [key, value] = item;
        if (elm.hasAttribute(value)) {
          elm.setAttribute(value, i18n.getMessage(`${id}_${key}`));
        }
      }
    }
  }
};

/**
 * localize html
 * @returns {void}
 */
export const localizeHtml = async () => {
  const lang = i18n.getMessage(EXT_LOCALE);
  if (lang) {
    const nodes = document.querySelectorAll(`[${DATA_I18N}]`);
    if (nodes instanceof NodeList) {
      for (const node of nodes) {
        const [id, ph] = node.getAttribute(DATA_I18N).split(/\s*,\s*/);
        const data = i18n.getMessage(id, ph);
        if (data) {
          node.textContent = data;
        }
        if (node.hasAttributes()) {
          localizeAttr(node);
        }
      }
    }
    document.documentElement.setAttribute("lang", EXT_LOCALE);
  }
};
<commit_msg>Update src/mjs/localize.js<commit_after>/**
 * localize.js
 */

/* api */
const {i18n} = browser;

/* constants */
import {EXT_LOCALE} from "./constant.js";
const DATA_I18N = "data-i18n";

/**
 * localize attribute value
 * @param {Object} elm - element
 * @returns {void}
 */
export const localizeAttr = async elm => {
  if (elm && elm.nodeType === Node.ELEMENT_NODE &&
      elm.hasAttribute(DATA_I18N)) {
    const [id] = elm.getAttribute(DATA_I18N).split(/\s*,\s*/);
    if (id) {
      const attrs = {
        alt: "alt",
        ariaLabel: "aria-label",
        href: "href",
        placeholder: "placeholder",
        title: "title",
      };
      const items = Object.entries(attrs);
      for (const item of items) {
        const [key, value] = item;
        if (elm.hasAttribute(value)) {
          elm.setAttribute(value, i18n.getMessage(`${id}_${key}`));
        }
      }
    }
  }
};

/**
 * localize html
 * @returns {void}
 */
export const localizeHtml = async () => {
  const lang = i18n.getMessage(EXT_LOCALE);
  if (lang) {
    const nodes = document.querySelectorAll(`[${DATA_I18N}]`);
    for (const node of nodes) {
      const [id, ph] = node.getAttribute(DATA_I18N).split(/\s*,\s*/);
      const data = i18n.getMessage(id, ph);
      if (data) {
        node.textContent = data;
      }
      localizeAttr(node);
    }
    document.documentElement.setAttribute("lang", lang);
  }
};
<|endoftext|>


<commit_before>/**
 * Created by dreamarts on 2014/03/30.
 */

var should = require('should')
  , log = require('log')
  , fs = require('fs')
  , async = require('async')
  , mail = require('../../lib/mail')
  , mongo = require('../../lib/db')
  , test = require('../test_util')
  , Searcher = require('node-searcher')
  ;

var COLLS = ['mails', 'mails.files', 'mails.chunks', 'mails.df'];

var FIELD = ['k', 'c', 'w'];

var FREQ = {'tf': 'mails.of'};

describe('mail', function () {

  var db;

  before(function (done) {
    // テストが始まる前の処理
    test.open(function (err, _db) {
      db = _db;
      done();
    });
  });

  after(function (done) {
    // テストが終わった後の処理
    db.close();
    done();
  });

  it('追加 1', function (done) {
    test.remove(db, COLLS, function (err) {
      var path = 'test/mail/data/test_1.eml';
      mail.add(path, function (err, mailInfo) {
        mail.get({'messageId': '1397023383.498516.1.1000481@moe.dreamarts.co.jp'}, function (err, result) {
          should.not.exist(err);
          result.length.should.eql(1);
          done();
        });
      });
    });
  });

  // 上記の「追加」がテストOKなので、ここではライブラリ的に使います。
  function add(array, callback) {
    async.each(array, function (item, next) {
      mail.add(item, function (err) {
        next(err);
      });
    }, function (err) {
      callback(err);
    });
  }

  it('追加 2', function (done) {
    test.remove(db, COLLS, function (err) {
      var data = [
        'test/mail/data/test_1.eml', // '1397023383.498516.1.1000481@moe.dreamarts.co.jp'
        'test/mail/data/test_2.eml'  // 'EBEBFB71-96DD-4FF0-9787-49B4D8A684E4@dreamarts.co.jp'
      ];
      add(data, function (err) {
        mail.get({'messageId': '1397023383.498516.1.1000481@moe.dreamarts.co.jp'}, function (err, result) {
          should.not.exist(err);
          result.length.should.eql(1);
          done();
        });
      });
    });
  });

  it('Index作成', function (done) {

    var target = {
      collection: 'mails',
      attribute: 'tf',
      option: {
        condition: {}
      }
    };

    var source = {
      collection: 'mails.files',
      attribute: 'metadata.tf',
      key: 'metadata.parent',
      option: {
        condition: {}
      }
    };

    var searcher = new Searcher(mongo.url(), FIELD, FREQ);

    searcher.indexing(target, source, function (err) {
      done();
    });

  });

  it('検索実行', function (done) {

    var collection = db.collection('mails');

    var option = {
      copy: ['subject'],
      out: 'mails.search.result'
    };

    var condition = {
      'tf': '先日フジテレビでラーメン'
    };

    var searcher = new Searcher(mongo.url(), FIELD, FREQ);

    searcher.search(collection, condition, option, function (err) {
      done();
    });

  });

});

<commit_msg>searcher.coutup テスト追加<commit_after>/**
 * Created by dreamarts on 2014/03/30.
 */

var should = require('should')
  , log = require('log')
  , fs = require('fs')
  , async = require('async')
  , mail = require('../../lib/mail')
  , mongo = require('../../lib/db')
  , test = require('../test_util')
  , Searcher = require('node-searcher')
  ;

var COLLS = ['mails', 'mails.files', 'mails.chunks', 'mails.df'];

var FIELD = ['k', 'c', 'w'];

var FREQ = {'tf': 'mails.of'};

describe('mail', function () {

  var db;

  before(function (done) {
    // テストが始まる前の処理
    test.open(function (err, _db) {
      db = _db;
      done();
    });
  });

  after(function (done) {
    // テストが終わった後の処理
    db.close();
    done();
  });

  it('追加 1', function (done) {
    test.remove(db, COLLS, function (err) {
      var path = 'test/mail/data/test_1.eml';
      mail.add(path, function (err, mailInfo) {
        mail.get({'messageId': '1397023383.498516.1.1000481@moe.dreamarts.co.jp'}, function (err, result) {
          should.not.exist(err);
          result.length.should.eql(1);
          done();
        });
      });
    });
  });

  // 上記の「追加」がテストOKなので、ここではライブラリ的に使います。
  function add(array, callback) {
    async.each(array, function (item, next) {
      mail.add(item, function (err) {
        next(err);
      });
    }, function (err) {
      callback(err);
    });
  }

  it('追加 2', function (done) {
    test.remove(db, COLLS, function (err) {
      var data = [
        'test/mail/data/test_1.eml', // '1397023383.498516.1.1000481@moe.dreamarts.co.jp'
        'test/mail/data/test_2.eml'  // 'EBEBFB71-96DD-4FF0-9787-49B4D8A684E4@dreamarts.co.jp'
      ];
      add(data, function (err) {
        mail.get({'messageId': '1397023383.498516.1.1000481@moe.dreamarts.co.jp'}, function (err, result) {
          should.not.exist(err);
          result.length.should.eql(1);
          done();
        });
      });
    });
  });

  it('Index作成', function (done) {

    var target = {
      collection: 'mails',
      attribute: 'tf',
      option: {
        condition: {}
      }
    };

    var source = {
      collection: 'mails.files',
      attribute: 'metadata.tf',
      key: 'metadata.parent',
      option: {
        condition: {}
      }
    };

    var searcher = new Searcher(mongo.url(), FIELD, FREQ);

    searcher.indexing(target, source, function (err) {
      done();
    });

  });

  it('検索実行', function (done) {

    var collection = db.collection('mails');

    var option = {
      copy: ['subject'],
      out: 'mails.search.result'
    };

    var condition = {
      'tf': '先日フジテレビでラーメン'
    };

    var target = {
      collection: 'mails',
      option: {
        condition: {
          'tf': '先日フジテレビでラーメン'
        },
        copy: ['subject'],
        out: 'mails.search.result'
      }
    };

    var searcher = new Searcher(mongo.url(), FIELD, FREQ);

    searcher.search(target, function (err) {
      done();
    });

  });

});

<|endoftext|>


<commit_before>/*globals freedom:true, fdom, WebSocket, console*/
/*jslint sloppy:true*/

/**
 * A WebSocket core provider.
 * @param {port.Module} module The Module requesting this provider
 * @param {Function} dispatchEvent Function to dispatch events.
 * @param {String} url The Remote URL to connect with.
 * @param {String[]} protocols SubProtocols to open.
 * @param {WebSocket?} socket An alternative socket class to use.
 */
var WS = function (module, dispatchEvent, url, protocols, socket) {
  var WSImplementation = socket || WebSocket;

  this.dispatchEvent = dispatchEvent;
  try {
    if (protocols) {
      this.websocket = new WSImplementation(url, protocols);
    } else {
      this.websocket = new WSImplementation(url);
    }
  } catch (e) {
    var error = {};
    if (e instanceof SyntaxError) {
      error.errcode = 'SYNTAX';
    } else {
      error.errcode = e.name;
    }
    error.message = e.message;
    dispatchEvent('onError', error);
    return;
  }

  this.websocket.onopen = this.onOpen.bind(this);
  this.websocket.onclose = this.onClose.bind(this);
  this.websocket.onmessage = this.onMessage.bind(this);
  this.websocket.onerror = this.onError.bind(this);
};

WS.prototype.send = function(data, continuation) {
  var toSend = data.text || data.binary || data.buffer;
  var errcode, message;

  if (toSend) {
    try {
      this.websocket.send(toSend);
    } catch (e) {
      if (e instanceof SyntaxError) {
        errcode = "SYNTAX";
      } else {
        errcode = "INVALID_STATE";
      }
      message = e.message;
    }
  } else {
    errcode = "BAD_SEND";
    message = "No text, binary, or buffer data found.";
  }

  if (errcode) {
    continuation(undefined, {
      errcode: errcode,
      message: message
    });
  } else {
    continuation();
  }
};

WS.prototype.getReadyState = function(continuation) {
  continuation(this.websocket.readyState);
};

WS.prototype.getBufferedAmount = function(continuation) {
  continuation(this.websocket.bufferedAmount);
};

WS.prototype.close = function(code, reason, continuation) {
  try {
    if (code && reason) {
      this.websocket.close(code, reason);
    } else {
      this.websocket.close();
    }
    continuation();
  } catch (e) {
    var errorCode;
    if (e instanceof SyntaxError) {
      errorCode = "SYNTAX";
    } else {
      errorCode = "INVALID_ACCESS";
    }
    continuation(undefined,{
      errcode: errorCode,
      message: e.message
    });
  }
};

WS.prototype.onOpen = function(event) {
  this.dispatchEvent('onOpen');
};

WS.prototype.onMessage = function(event) {
  var data = {};
  if (event.data instanceof ArrayBuffer) {
    data.buffer = data;
  } else if (event.data instanceof Blob) {
    data.binary = data;
  } else if (typeof event.data === 'string') {
    data.text = event.data;
  }
  this.dispatchEvent('onMessage', data);
};

WS.prototype.onError = function(event) {
  // Nothing to pass on
  // See: http://stackoverflow.com/a/18804298/300539
  this.dispatchEvent('onError');
};

WS.prototype.onClose = function(event) {
  this.dispatchEvent('onClose',
                     {code: event.code,
                      reason: event.reason,
                      wasClean: event.wasClean});
};

fdom.apis.register('core.websocket', WS);
<commit_msg>Updating core.websocket provider to support node.js<commit_after>/*globals freedom:true, fdom, WebSocket, console, require*/
/*jslint sloppy:true*/

/**
 * A WebSocket core provider.
 * @param {port.Module} module The Module requesting this provider
 * @param {Function} dispatchEvent Function to dispatch events.
 * @param {String} url The Remote URL to connect with.
 * @param {String[]} protocols SubProtocols to open.
 * @param {WebSocket?} socket An alternative socket class to use.
 */
var WS = function (module, dispatchEvent, url, protocols, socket) {
  var WSImplementation = null;
  if (typeof socket !== 'undefined') {
    WSImplementation = socket;
  } else if (typeof WebSocket !== 'undefined') {
    WSImplementation = WebSocket;
  } else if (typeof require !== 'undefined') {
    WSImplementation = require('ws');
  } else {
    console.error('Platform does not support WebSocket');
  }

  this.dispatchEvent = dispatchEvent;
  try {
    if (protocols) {
      this.websocket = new WSImplementation(url, protocols);
    } else {
      this.websocket = new WSImplementation(url);
    }
  } catch (e) {
    var error = {};
    if (e instanceof SyntaxError) {
      error.errcode = 'SYNTAX';
    } else {
      error.errcode = e.name;
    }
    error.message = e.message;
    dispatchEvent('onError', error);
    return;
  }

  this.websocket.onopen = this.onOpen.bind(this);
  this.websocket.onclose = this.onClose.bind(this);
  this.websocket.onmessage = this.onMessage.bind(this);
  this.websocket.onerror = this.onError.bind(this);
};

WS.prototype.send = function(data, continuation) {
  var toSend = data.text || data.binary || data.buffer;
  var errcode, message;

  if (toSend) {
    try {
      this.websocket.send(toSend);
    } catch (e) {
      if (e instanceof SyntaxError) {
        errcode = "SYNTAX";
      } else {
        errcode = "INVALID_STATE";
      }
      message = e.message;
    }
  } else {
    errcode = "BAD_SEND";
    message = "No text, binary, or buffer data found.";
  }

  if (errcode) {
    continuation(undefined, {
      errcode: errcode,
      message: message
    });
  } else {
    continuation();
  }
};

WS.prototype.getReadyState = function(continuation) {
  continuation(this.websocket.readyState);
};

WS.prototype.getBufferedAmount = function(continuation) {
  continuation(this.websocket.bufferedAmount);
};

WS.prototype.close = function(code, reason, continuation) {
  try {
    if (code && reason) {
      this.websocket.close(code, reason);
    } else {
      this.websocket.close();
    }
    continuation();
  } catch (e) {
    var errorCode;
    if (e instanceof SyntaxError) {
      errorCode = "SYNTAX";
    } else {
      errorCode = "INVALID_ACCESS";
    }
    continuation(undefined,{
      errcode: errorCode,
      message: e.message
    });
  }
};

WS.prototype.onOpen = function(event) {
  this.dispatchEvent('onOpen');
};

WS.prototype.onMessage = function(event) {
  var data = {};
  if (typeof ArrayBuffer !== 'undefined' && event.data instanceof ArrayBuffer) {
    data.buffer = data;
  } else if (typeof Blob !== 'undefined' && event.data instanceof Blob) {
    data.binary = data;
  } else if (typeof event.data === 'string') {
    data.text = event.data;
  }
  this.dispatchEvent('onMessage', data);
};

WS.prototype.onError = function(event) {
  // Nothing to pass on
  // See: http://stackoverflow.com/a/18804298/300539
  this.dispatchEvent('onError');
};

WS.prototype.onClose = function(event) {
  this.dispatchEvent('onClose',
                     {code: event.code,
                      reason: event.reason,
                      wasClean: event.wasClean});
};

fdom.apis.register('core.websocket', WS);
<|endoftext|>


<commit_before>/* global $ firebase*/

var database = firebase.database();

var getCode = function getCode(callback) {
    var datalist = database.ref('code');
    datalist.on('value', function(snapshot) {
        callback(snapshot.val());
    });
};

$(document).ready(function() {
    $(".noQuery").hide();
    getCode(function(data) {
        var tc = Math.floor(Math.random() * (data.length));
        $("#faketestcode").attr("placeholder",data[tc]);
        $("#testcode").val(data[tc]);
    });
});<commit_msg>Updated Firebase Snapshot function<commit_after>/* global $ firebase*/

var database = firebase.database();

var getCode = function getCode(callback) {
    var datalist = database.ref('code');
    datalist.once('value', function(snapshot) {
        callback(snapshot.val());
    });
};

$(document).ready(function() {
    $(".noQuery").hide();
    getCode(function(data) {
        var tc = Math.floor(Math.random() * (data.length));
        $("#faketestcode").attr("placeholder",data[tc]);
        $("#testcode").val(data[tc]);
    });
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import autoBind from 'react-autobind';
import classnames from 'classnames';
import debounce from 'throttle-debounce/debounce';
import { graphql, gql } from 'react-apollo';

import Utils from '/imports/lib/utils';
import Authors from '/imports/api/collections/authors';
import TextNodes from '/imports/api/collections/textNodes';
import Works from '/imports/api/collections/works';

import AnnotateWidget from '/imports/ui/components/annotations/AnnotateWidget';
import CommentaryPanel from '/imports/ui/components/commentary/CommentaryPanel';
import DefinitionsPanel from '/imports/ui/components/definitions/DefinitionsPanel';
import HeaderReading from '/imports/ui/components/header/HeaderReading';
import LoadingDoubleWell from '/imports/ui/components/spinkit/LoadingDoubleWell';
import ReadingEnvironment from '/imports/ui/components/reading/ReadingEnvironment';
import SearchModal from '/imports/ui/components/search/SearchModal';

class ReadingLayout extends React.Component {
	static defaultProps = {
		textNodes: [],
	}

	static propTypes = {
		id: PropTypes.number,
		slug: PropTypes.number,
		textNodes: PropTypes.array,
	}

	constructor(props) {
		super(props);
		let location = [];

		this.state = {
			toggleCommentary: false,
			toggleDefinitions: false,
			toggleTranslations: false,
			toggleScansion: false,
			toggleMedia: false,
			toggleEntities: false,
			toggleAnnotations: false,
			toggleRelatedPassages: false,
			filters: [],
			limit: 30,
			annotationCheckList: [],
			searchModalVisible: false,
			AuthModalLowered: false,
			modalSignupLowered: false,
			location,
			textNodesDepths: [],
			searchParams: {
				filters: [],
				limit: 21,
				offset: 0,
			},
		};

		autoBind(this);
	}

	loadMorePrev() {
		const { work } = this.props;
		const textLocationPrev = work.text_location_prev;
		this.props.history.push(`/works/${work.id}/${work.slug}/${textLocationPrev.join('.')}`);
	}

	loadMoreNext() {
		const { work } = this.props;
		const textLocationNext = work.text_location_next;
		this.props.history.push(`/works/${work.id}/${work.slug}/${textLocationNext.join('.')}`);
	}

	toggleSidePanel(metadata) {
		if (metadata === 'definitions') {
			const toggle = !this.state.toggleDefinitions;
			this.setState({
				toggleDefinitions: toggle,
			});
		}
		if (metadata === 'commentary') {
			const toggle = !this.state.toggleCommentary;
			this.setState({
				toggleCommentary: toggle,
			});
		}
		if (metadata === 'translations') {
			const toggle = !this.state.toggleTranslations;
			this.setState({
				toggleTranslations: toggle,
			});
		}
		if (metadata === 'entities') {
			const toggle = !this.state.toggleEntities;
			this.setState({
				toggleEntities: toggle,
			});
		}
		if (metadata === 'media') {
			const toggle = !this.state.toggleMedia;
			this.setState({
				toggleMedia: toggle,
			});
		}
		if (metadata === 'scansion') {
			const toggle = !this.state.toggleScansion;
			this.setState({
				toggleScansion: toggle,
			});
		}
	}

	addAnnotationCheckList(textNodeId, isChecked) {
		const annotationCheckList = this.state.annotationCheckList;
		if (isChecked) {
			annotationCheckList.push(textNodeId);
		} else {
			const index = annotationCheckList.indexOf(textNodeId);
			if (index > -1) {
				annotationCheckList.splice(index, 1);
			}
		}
		this.setState({
			annotationCheckList,
		});
	}

	resetAnnotationCheckList() {
		this.setState({
			annotationCheckList: [],
		});
	}

	showSearchModal() {
		this.setState({
			searchModalVisible: true,
		});
	}

	closeSearchModal() {
		this.setState({
			searchModalVisible: false,
		});
	}

	changeSearchParams(searchParams) {
		this.setState({
			...this.state.searchParams,
			...searchParams
		});
	}

	showLoginModal() {
		this.setState({
			AuthModalLowered: true,
		});
	}

	showSignupModal() {
		this.setState({
			modalSignupLowered: true,
		});
	}

	closeLoginModal() {
		this.setState({
			AuthModalLowered: false,
		});
	}

	closeSignupModal() {
		this.setState({
			modalSignupLowered: false,
		});
	}

	toggleReadingMeta(metaType) {
		if (metaType === 'annotations') {
			this.setState({
				toggleAnnotations: !this.state.toggleAnnotations,
			});
		} else if (metaType === 'relatedPassages') {
			this.setState({
				toggleRelatedPassages: !this.state.toggleRelatedPassages,
			});
		}
	}

	renderReadingEnvironment() {
		const { work, textNodes } = this.props;
		let textLocation = this.props.location || [];

		// If data is loaded
		if (work && textNodes) {
			return (
				<ReadingEnvironment
					work={work}
					textNodes={textNodes}
					loadMorePrev={this.loadMorePrev}
					loadMoreNext={this.loadMoreNext}
					toggleReadingMeta={this.toggleReadingMeta}
					showLoginModal={this.showLoginModal}
					showSignupModal={this.showSignupModal}
					closeLoginModal={this.closeLoginModal}
					closeSignupModal={this.closeSignupModal}
				/>
			);
		}
		return null;
	}

	render() {
		const readingClassName = classnames('clearfix', {
			'with-entities': this.state.toggleEntities,
			'with-left-panel': this.state.toggleDefinitions,
			'with-media': this.state.toggleMedia,
			'with-right-panel': this.state.toggleCommentary || this.state.toggleTranslations,
			'with-right-metadata': (
				this.state.toggleMedia ||
				this.state.toggleEntities ||
				this.state.toggleAnnotations ||
				this.state.toggleRelatedPassages
			),
			'with-scansion': this.state.toggleScansion,
		});

		return (

				{this.props.work ?

						<HeaderReading
							author={this.props.work.author}
							corpus={this.props.work.corpus}
							workId={this.props.work.id}
							workSlug={this.props.work.slug}
							workForm={this.props.work.form}
							englishTitle={this.props.work.english_title}
							loc={this.props.match.params.loc}
							showSearchModal={this.showSearchModal}
							toggleSidePanel={this.toggleSidePanel}
							toggleDefinitions={this.state.toggleDefinitions}
							toggleCommentary={this.state.toggleCommentary}
							toggleTranslations={this.state.toggleTranslations}
							toggleScansion={this.state.toggleScansion}
							toggleMedia={this.state.toggleMedia}
							toggleEntities={this.state.toggleEntities}
							toggleAnnotations={this.state.toggleAnnotations}
						/>

								{this.renderReadingEnvironment()}

						<DefinitionsPanel
							toggleDefinitions={this.state.toggleDefinitions}
							textNodes={this.props.textNodes}
						/>
						<CommentaryPanel
							toggleCommentary={this.state.toggleCommentary}
							toggleTranslations={this.state.toggleTranslations}
							work={(this.props.work && 'title' in this.props.work) ? this.props.work.title : ''}
							textNodes={this.props.textNodes}
						/>
						{/*
						<AnnotateWidget
							annotationCheckList={this.state.annotationCheckList}
							work={this.props.work || {}}
							submitAnnotation={this.submitAnnotation}
						/>
						*/}
						<SearchModal
							changeSearchParams={this.changeSearchParams}
							closeSearchModal={this.closeSearchModal}
							visible={this.state.searchModalVisible}
							{...this.state.searchParams}
						/>

				:

							<LoadingDoubleWell />

				}
				{this.state.AuthModalLowered ?
					<AuthModal
						lowered={this.state.AuthModalLowered}
						closeModal={this.closeLoginModal}
					/>
					: ''
				}
				{this.state.modalSignupLowered ?
					<ModalSignup
						lowered={this.state.modalSignupLowered}
						closeModal={this.closeSignupModal}
					/>
					: ''
				}

		);
	}
}

const withData = graphql(gql`
	query TextForReadingEnv($workId: ID!, $loc: [Int]) {
		work_by_id(id: $workId) {
			id
			slug
			original_title
			english_title
			author {
				id
				name
				slug
			}
			corpus {
				id
				title
			}
			text_nodes(location: $loc) {
				id
				index
				location
				text
			}
			text_location_next(location: $loc)
			text_location_prev(location: $loc)
		}
	}
`, {
  options: ({ match: { params } }) => {
		const workId = params.id;
		const loc = params.loc ?
								params.loc.split('.')
								: null ;

		if (loc) {
			loc.forEach((n, i) => {
				loc[i] = parseInt(n, 10);
			});
		}

		return {
	    variables: {
				workId,
				loc,
			},
		};
	},
  props: ({ data }) => {

		return {
			work: data.work_by_id,
		};
  },
});

export default withData(ReadingLayout);
<commit_msg>fix text search handling on reading layout for the moment before we move the form to redux<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import autoBind from 'react-autobind';
import classnames from 'classnames';
import debounce from 'throttle-debounce/debounce';
import { graphql, gql } from 'react-apollo';

import Utils from '/imports/lib/utils';
import Authors from '/imports/api/collections/authors';
import TextNodes from '/imports/api/collections/textNodes';
import Works from '/imports/api/collections/works';

import AnnotateWidget from '/imports/ui/components/annotations/AnnotateWidget';
import CommentaryPanel from '/imports/ui/components/commentary/CommentaryPanel';
import DefinitionsPanel from '/imports/ui/components/definitions/DefinitionsPanel';
import HeaderReading from '/imports/ui/components/header/HeaderReading';
import LoadingDoubleWell from '/imports/ui/components/spinkit/LoadingDoubleWell';
import ReadingEnvironment from '/imports/ui/components/reading/ReadingEnvironment';
import SearchModal from '/imports/ui/components/search/SearchModal';

class ReadingLayout extends React.Component {
	static defaultProps = {
		textNodes: [],
	}

	static propTypes = {
		id: PropTypes.number,
		slug: PropTypes.number,
		textNodes: PropTypes.array,
	}

	constructor(props) {
		super(props);
		let location = [];

		this.state = {
			toggleCommentary: false,
			toggleDefinitions: false,
			toggleTranslations: false,
			toggleScansion: false,
			toggleMedia: false,
			toggleEntities: false,
			toggleAnnotations: false,
			toggleRelatedPassages: false,
			filters: [],
			limit: 30,
			annotationCheckList: [],
			searchModalVisible: false,
			AuthModalLowered: false,
			modalSignupLowered: false,
			location,
			textNodesDepths: [],
			textsearch: '',
			limit: 21,
			offset: 0,
		};

		autoBind(this);
	}

	loadMorePrev() {
		const { work } = this.props;
		const textLocationPrev = work.text_location_prev;
		this.props.history.push(`/works/${work.id}/${work.slug}/${textLocationPrev.join('.')}`);
	}

	loadMoreNext() {
		const { work } = this.props;
		const textLocationNext = work.text_location_next;
		this.props.history.push(`/works/${work.id}/${work.slug}/${textLocationNext.join('.')}`);
	}

	toggleSidePanel(metadata) {
		if (metadata === 'definitions') {
			const toggle = !this.state.toggleDefinitions;
			this.setState({
				toggleDefinitions: toggle,
			});
		}
		if (metadata === 'commentary') {
			const toggle = !this.state.toggleCommentary;
			this.setState({
				toggleCommentary: toggle,
			});
		}
		if (metadata === 'translations') {
			const toggle = !this.state.toggleTranslations;
			this.setState({
				toggleTranslations: toggle,
			});
		}
		if (metadata === 'entities') {
			const toggle = !this.state.toggleEntities;
			this.setState({
				toggleEntities: toggle,
			});
		}
		if (metadata === 'media') {
			const toggle = !this.state.toggleMedia;
			this.setState({
				toggleMedia: toggle,
			});
		}
		if (metadata === 'scansion') {
			const toggle = !this.state.toggleScansion;
			this.setState({
				toggleScansion: toggle,
			});
		}
	}

	addAnnotationCheckList(textNodeId, isChecked) {
		const annotationCheckList = this.state.annotationCheckList;
		if (isChecked) {
			annotationCheckList.push(textNodeId);
		} else {
			const index = annotationCheckList.indexOf(textNodeId);
			if (index > -1) {
				annotationCheckList.splice(index, 1);
			}
		}
		this.setState({
			annotationCheckList,
		});
	}

	resetAnnotationCheckList() {
		this.setState({
			annotationCheckList: [],
		});
	}

	showSearchModal() {
		this.setState({
			searchModalVisible: true,
		});
	}

	closeSearchModal() {
		this.setState({
			searchModalVisible: false,
		});
	}

	handleChangeTextsearch(newValue) {
		this.setState({
			textsearch: newValue.textsearch,
		});
	}

	showLoginModal() {
		this.setState({
			AuthModalLowered: true,
		});
	}

	showSignupModal() {
		this.setState({
			modalSignupLowered: true,
		});
	}

	closeLoginModal() {
		this.setState({
			AuthModalLowered: false,
		});
	}

	closeSignupModal() {
		this.setState({
			modalSignupLowered: false,
		});
	}

	toggleReadingMeta(metaType) {
		if (metaType === 'annotations') {
			this.setState({
				toggleAnnotations: !this.state.toggleAnnotations,
			});
		} else if (metaType === 'relatedPassages') {
			this.setState({
				toggleRelatedPassages: !this.state.toggleRelatedPassages,
			});
		}
	}

	loadMore() {
		this.setState({
			limit: this.state.limit + 21,
		});
	}

	renderReadingEnvironment() {
		const { work, textNodes } = this.props;
		let textLocation = this.props.location || [];

		// If data is loaded
		if (work && textNodes) {
			return (
				<ReadingEnvironment
					work={work}
					textNodes={textNodes}
					loadMorePrev={this.loadMorePrev}
					loadMoreNext={this.loadMoreNext}
					toggleReadingMeta={this.toggleReadingMeta}
					showLoginModal={this.showLoginModal}
					showSignupModal={this.showSignupModal}
					closeLoginModal={this.closeLoginModal}
					closeSignupModal={this.closeSignupModal}
				/>
			);
		}
		return null;
	}

	render() {
		const readingClassName = classnames('clearfix', {
			'with-entities': this.state.toggleEntities,
			'with-left-panel': this.state.toggleDefinitions,
			'with-media': this.state.toggleMedia,
			'with-right-panel': this.state.toggleCommentary || this.state.toggleTranslations,
			'with-right-metadata': (
				this.state.toggleMedia ||
				this.state.toggleEntities ||
				this.state.toggleAnnotations ||
				this.state.toggleRelatedPassages
			),
			'with-scansion': this.state.toggleScansion,
		});

		return (

				{this.props.work ?

						<HeaderReading
							author={this.props.work.author}
							corpus={this.props.work.corpus}
							workId={this.props.work.id}
							workSlug={this.props.work.slug}
							workForm={this.props.work.form}
							englishTitle={this.props.work.english_title}
							loc={this.props.match.params.loc}
							showSearchModal={this.showSearchModal}
							toggleSidePanel={this.toggleSidePanel}
							toggleDefinitions={this.state.toggleDefinitions}
							toggleCommentary={this.state.toggleCommentary}
							toggleTranslations={this.state.toggleTranslations}
							toggleScansion={this.state.toggleScansion}
							toggleMedia={this.state.toggleMedia}
							toggleEntities={this.state.toggleEntities}
							toggleAnnotations={this.state.toggleAnnotations}
						/>

								{this.renderReadingEnvironment()}

						<DefinitionsPanel
							toggleDefinitions={this.state.toggleDefinitions}
							textNodes={this.props.textNodes}
						/>
						<CommentaryPanel
							toggleCommentary={this.state.toggleCommentary}
							toggleTranslations={this.state.toggleTranslations}
							work={(this.props.work && 'title' in this.props.work) ? this.props.work.title : ''}
							textNodes={this.props.textNodes}
						/>
						{/*
						<AnnotateWidget
							annotationCheckList={this.state.annotationCheckList}
							work={this.props.work || {}}
							submitAnnotation={this.submitAnnotation}
						/>
						*/}
						<SearchModal
							handleChangeTextsearch={this.handleChangeTextsearch}
							closeSearchModal={this.closeSearchModal}
							visible={this.state.searchModalVisible}
							textsearch={this.state.textsearch}
							loadMore={this.loadMore}
							limit={this.state.limit}
							offset={this.state.offset}
						/>

				:

							<LoadingDoubleWell />

				}
				{this.state.AuthModalLowered ?
					<AuthModal
						lowered={this.state.AuthModalLowered}
						closeModal={this.closeLoginModal}
					/>
					: ''
				}
				{this.state.modalSignupLowered ?
					<ModalSignup
						lowered={this.state.modalSignupLowered}
						closeModal={this.closeSignupModal}
					/>
					: ''
				}

		);
	}
}

const withData = graphql(gql`
	query TextForReadingEnv($workId: ID!, $loc: [Int]) {
		work_by_id(id: $workId) {
			id
			slug
			original_title
			english_title
			author {
				id
				name
				slug
			}
			corpus {
				id
				title
			}
			text_nodes(location: $loc) {
				id
				index
				location
				text
			}
			text_location_next(location: $loc)
			text_location_prev(location: $loc)
		}
	}
`, {
  options: ({ match: { params } }) => {
		const workId = params.id;
		const loc = params.loc ?
								params.loc.split('.')
								: null ;

		if (loc) {
			loc.forEach((n, i) => {
				loc[i] = parseInt(n, 10);
			});
		}

		return {
	    variables: {
				workId,
				loc,
			},
		};
	},
  props: ({ data }) => {

		return {
			work: data.work_by_id,
		};
  },
});

export default withData(ReadingLayout);
<|endoftext|>


<commit_before>import React from 'react';

import ActionSheet, { ActionItem } from './ActionSheet';

import {
  DatePickerIOS,
  Platform
} from 'react-native';

class DatePicker extends React.Component {
  static defaultProps = {
    date: new Date(),
    mode: 'datetime'
  }

  static propTypes = {
    date: React.PropTypes.object.isRequired,
    onDateSelected: React.PropTypes.func
  }

  constructor(props) {
    super(props);

    this.state = {
      date: this.props.date,
      mode: this.props.mode
    }
  }

  open() {
    // for ios, we use actionsheet
    this._actionSheet.open();
  }

  handleOnDateChange = (date) => {
    this.setState({
      date
    });

    this.props.onDateSelected(date);
  }

  render() {
    return (
      <ActionSheet ref={component => this._actionSheet = component} >
        {
          Platform === 'ios' &&
          <DatePickerIOS
            date={this.state.date}
            mode={this.state.mode}
            onDateChange={this.handleOnDateChange}
          />
        }
        <ActionItem title="Done" destructive />
      </ActionSheet>
    );
  }
}

export default DatePicker;<commit_msg>bug fix<commit_after>import React from 'react';

import ActionSheet, { ActionItem } from './ActionSheet';

import {
  DatePickerIOS,
  Platform
} from 'react-native';

class DatePicker extends React.Component {
  static defaultProps = {
    date: new Date(),
    mode: 'datetime'
  }

  static propTypes = {
    date: React.PropTypes.object.isRequired,
    onDateSelected: React.PropTypes.func
  }

  constructor(props) {
    super(props);

    this.state = {
      date: this.props.date,
      mode: this.props.mode
    }
  }

  open() {
    // for ios, we use actionsheet
    this._actionSheet.open();
  }

  handleOnDateChange = (date) => {
    this.setState({
      date
    });

    this.props.onDateSelected(date);
  }

  render() {
    return (
      <ActionSheet ref={component => this._actionSheet = component} >
        {
          Platform.OS === 'ios' &&
          <DatePickerIOS
            date={this.state.date}
            mode={this.state.mode}
            onDateChange={this.handleOnDateChange}
          />
        }
        <ActionItem title="Done" destructive />
      </ActionSheet>
    );
  }
}

export default DatePicker;<|endoftext|>


<commit_before>angular.module('team-task')
    .controller('ProjectController', ['$scope', '$rootScope', 'Projeto', 'Atividade', 'Time',
        'DTOptionsBuilder', '$resource', '$uibModal', '$stateParams', 'Pessoa', '$window',
        function ($scope, $rootScope, Projeto, Atividade, Time, DTOptionsBuilder, $resource, $uibModal,
                  $stateParams, Pessoa, $window) {
            $scope.showLoading = false;
            $scope.dtOptions = DTOptionsBuilder.newOptions();//.withLanguage($resource('js/dtOptions.json').get().$promise);
            $scope.dtOptions.withOption('order', [[3,"asc"]]);
            /*
            timer futuro
            $interval(function () {
                loadProject();
                $rootScope.$emit("CallLoadMenus", {});
            }, 30000);
            */

            $scope.initWorkspaceProject = function () {
                loadProject();
            };

            function loadProject() {
                $scope.showLoading = true;

                Projeto.getById($stateParams.id).then(function (projeto) {
                    if(projeto) {
                        angular.forEach(projeto.atividades, function (atividade, idAtividade) {
                            if(atividade.designado) {
                                Pessoa.getById(atividade.designado).then(function (pessoa) {
                                    if (pessoa) {
                                        var nomes = pessoa.nome.split(" ");
                                        var iniciais = nomes[0].substring(0, 1);
                                        var nomeSimples = nomes[0];
                                        if (nomes.length > 1) {
                                            iniciais += nomes[1].substring(0, 1);
                                        }
                                        pessoa.iniciais = iniciais.toUpperCase();
                                        pessoa.nomeSimples = nomeSimples;

                                        atividade.pessoaDesignado = pessoa;
                                        atividade.nomeDesignado = pessoa.nome;
                                    }
                                });
                            }
                            if(atividade.time) {
                                Time.getById(atividade.time).then(function (time) {
                                    if(time) {
                                        atividade.nomeTime = time.nome;
                                    }
                                });
                            }
                        });
                        $scope.projeto = projeto;
                        $scope.showLoading = false;
                    }
                });
            }

            $scope.copiarAtividade = function (indice) {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/copy-activity.html',
                        controller: 'ModalCopyProjectActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            },
                            indice : function () {
                                return indice;
                            }
                        }
                    }).result.then(function () {
                        loadProject();
                        $rootScope.$emit("CallLoadMenus", {});
                    }, function () {
                    });
            };

            $scope.moverAtividade = function (indice) {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/cut-activity.html',
                        controller: 'ModalCutProjectActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            },
                            indice : function () {
                                return indice;
                            }
                        }
                    }).result.then(function () {
                        loadProject();
                        $rootScope.$emit("CallLoadMenus", {});
                    }, function () {
                    });
            };

            $scope.editarAtividade = function (indice) {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/edit-activity.html',
                        controller: 'ModalEditActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            },
                            indice : function () {
                                return indice;
                            }
                        }
                    }).result.then(function () {
                        loadProject();
                        $rootScope.$emit("CallLoadMenus", {});
                    }, function () {
                    });
            };

            $scope.novaAtividade = function () {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/new-activity.html',
                        controller: 'ModalNewActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            }
                        }
                    }).result.then(function () {
                        loadProject();
                        $rootScope.$emit("CallLoadMenus", {});
                    }, function () {
                    });
            };

            $scope.mostrarDetalheAtividade = function (indice) {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/view-activity.html',
                        controller: 'ModalViewActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            },
                            indice : function () {
                                return indice;
                            }
                        }
                    }).result.then(function () {
                    }, function () {
                    });
            };
        }]);
<commit_msg>inicio da implementacao do export<commit_after>angular.module('team-task')
    .controller('ProjectController', ['$scope', '$rootScope', 'Projeto', 'Atividade', 'Time',
        'DTOptionsBuilder', '$resource', '$uibModal', '$stateParams', 'Pessoa', '$window',
        function ($scope, $rootScope, Projeto, Atividade, Time, DTOptionsBuilder, $resource, $uibModal,
                  $stateParams, Pessoa, $window) {
            $scope.showLoading = false;
            $scope.dtOptions = DTOptionsBuilder.newOptions();//.withLanguage($resource('js/dtOptions.json').get().$promise);
            $scope.dtOptions.withOption('order', [[3,"asc"]]);
            /*
            timer futuro
            $interval(function () {
                loadProject();
                $rootScope.$emit("CallLoadMenus", {});
            }, 30000);
            */

            $scope.initWorkspaceProject = function () {
                loadProject();
            };

            $scope.exportarTemplate = function () {
                if($scope.projeto.atividades.length > 0) {
                    for (var i = 0; i < $scope.projeto.atividades; i++) {

                    }
                }
            };

            function loadProject() {
                $scope.showLoading = true;

                Projeto.getById($stateParams.id).then(function (projeto) {
                    if(projeto) {
                        angular.forEach(projeto.atividades, function (atividade, idAtividade) {
                            if(atividade.designado) {
                                Pessoa.getById(atividade.designado).then(function (pessoa) {
                                    if (pessoa) {
                                        var nomes = pessoa.nome.split(" ");
                                        var iniciais = nomes[0].substring(0, 1);
                                        var nomeSimples = nomes[0];
                                        if (nomes.length > 1) {
                                            iniciais += nomes[1].substring(0, 1);
                                        }
                                        pessoa.iniciais = iniciais.toUpperCase();
                                        pessoa.nomeSimples = nomeSimples;

                                        atividade.pessoaDesignado = pessoa;
                                        atividade.nomeDesignado = pessoa.nome;
                                    }
                                });
                            }
                            if(atividade.time) {
                                Time.getById(atividade.time).then(function (time) {
                                    if(time) {
                                        atividade.nomeTime = time.nome;
                                    }
                                });
                            }
                        });
                        $scope.projeto = projeto;
                        $scope.showLoading = false;
                    }
                });
            }

            $scope.copiarAtividade = function (indice) {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/copy-activity.html',
                        controller: 'ModalCopyProjectActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            },
                            indice : function () {
                                return indice;
                            }
                        }
                    }).result.then(function () {
                        loadProject();
                        $rootScope.$emit("CallLoadMenus", {});
                    }, function () {
                    });
            };

            $scope.moverAtividade = function (indice) {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/cut-activity.html',
                        controller: 'ModalCutProjectActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            },
                            indice : function () {
                                return indice;
                            }
                        }
                    }).result.then(function () {
                        loadProject();
                        $rootScope.$emit("CallLoadMenus", {});
                    }, function () {
                    });
            };

            $scope.editarAtividade = function (indice) {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/edit-activity.html',
                        controller: 'ModalEditActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            },
                            indice : function () {
                                return indice;
                            }
                        }
                    }).result.then(function () {
                        loadProject();
                        $rootScope.$emit("CallLoadMenus", {});
                    }, function () {
                    });
            };

            $scope.novaAtividade = function () {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/new-activity.html',
                        controller: 'ModalNewActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            }
                        }
                    }).result.then(function () {
                        loadProject();
                        $rootScope.$emit("CallLoadMenus", {});
                    }, function () {
                    });
            };

            $scope.mostrarDetalheAtividade = function (indice) {
                $uibModal
                    .open({
                        templateUrl: 'views/modal/view-activity.html',
                        controller: 'ModalViewActivityController',
                        resolve: {
                            projetoSelecionado: function () {
                                return $scope.projeto;
                            },
                            indice : function () {
                                return indice;
                            }
                        }
                    }).result.then(function () {
                    }, function () {
                    });
            };
        }]);
<|endoftext|>