<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';

import ReactSwipeableViews from 'react-swipeable-views';
import { links, getIndex, getLink } from './tabs_bar';
import { Link } from 'react-router-dom';

import BundleContainer from '../containers/bundle_container';
import ColumnLoading from './column_loading';
import DrawerLoading from './drawer_loading';
import BundleColumnError from './bundle_column_error';
import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, DirectTimeline, FavouritedStatuses, ListTimeline } from '../../ui/util/async-components';

import detectPassiveEvents from 'detect-passive-events';
import { scrollRight } from '../../../scroll';

const componentMap = {
  'COMPOSE': Compose,
  'HOME': HomeTimeline,
  'NOTIFICATIONS': Notifications,
  'PUBLIC': PublicTimeline,
  'COMMUNITY': CommunityTimeline,
  'HASHTAG': HashtagTimeline,
  'DIRECT': DirectTimeline,
  'FAVOURITES': FavouritedStatuses,
  'LIST': ListTimeline,
};

const shouldHideFAB = path => path.match(/^\/statuses\//);

@component => injectIntl(component, { withRef: true })
export default class ColumnsArea extends ImmutablePureComponent {

  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  static propTypes = {
    intl: PropTypes.object.isRequired,
    columns: ImmutablePropTypes.list.isRequired,
    isModalOpen: PropTypes.bool.isRequired,
    singleColumn: PropTypes.bool,
    children: PropTypes.node,
  };

  state = {
    shouldAnimate: false,
  }

  componentWillReceiveProps() {
    this.setState({ shouldAnimate: false });
  }

  componentDidMount() {
    if (!this.props.singleColumn) {
      this.node.addEventListener('wheel', this.handleWheel,  detectPassiveEvents.hasSupport ? { passive: true } : false);
    }

    this.lastIndex   = getIndex(this.context.router.history.location.pathname);
    this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl');

    this.setState({ shouldAnimate: true });
  }

  componentWillUpdate(nextProps) {
    if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) {
      this.node.removeEventListener('wheel', this.handleWheel);
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) {
      this.node.addEventListener('wheel', this.handleWheel,  detectPassiveEvents.hasSupport ? { passive: true } : false);
    }
    this.lastIndex = getIndex(this.context.router.history.location.pathname);
    this.setState({ shouldAnimate: true });
  }

  componentWillUnmount () {
    if (!this.props.singleColumn) {
      this.node.removeEventListener('wheel', this.handleWheel);
    }
  }

  handleChildrenContentChange() {
    if (!this.props.singleColumn) {
      const modifier = this.isRtlLayout ? -1 : 1;
      this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier);
    }
  }

  handleSwipe = (index) => {
    this.pendingIndex = index;

    const nextLinkTranslationId = links[index].props['data-preview-title-id'];
    const currentLinkSelector = '.tabs-bar__link.active';
    const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`;

    // HACK: Remove the active class from the current link and set it to the next one
    // React-router does this for us, but too late, feeling laggy.
    document.querySelector(currentLinkSelector).classList.remove('active');
    document.querySelector(nextLinkSelector).classList.add('active');
  }

  handleAnimationEnd = () => {
    if (typeof this.pendingIndex === 'number') {
      this.context.router.history.push(getLink(this.pendingIndex));
      this.pendingIndex = null;
    }
  }

  handleWheel = () => {
    if (typeof this._interruptScrollAnimation !== 'function') {
      return;
    }

    this._interruptScrollAnimation();
  }

  setRef = (node) => {
    this.node = node;
  }

  renderView = (link, index) => {
    const columnIndex = getIndex(this.context.router.history.location.pathname);
    const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] });
    const icon = link.props['data-preview-icon'];

    const view = (index === columnIndex) ?
      React.cloneElement(this.props.children) :
      <ColumnLoading title={title} icon={icon} />;

    return (

        {view}

    );
  }

  renderLoading = columnId => () => {
    return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />;
  }

  renderError = (props) => {
    return <BundleColumnError {...props} />;
  }

  render () {
    const { columns, children, singleColumn, isModalOpen } = this.props;
    const { shouldAnimate } = this.state;

    const columnIndex = getIndex(this.context.router.history.location.pathname);
    this.pendingIndex = null;

    if (singleColumn) {
      const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/statuses/new' className='floating-action-button'></Link>;

      return columnIndex !== -1 ? [
        <ReactSwipeableViews key='content' index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}>
          {links.map(this.renderView)}
        </ReactSwipeableViews>,

        floatingActionButton,
      ] : [

{children}
,

        floatingActionButton,
      ];
    }

    return (
      <div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}>
        {columns.map(column => {
          const params = column.get('params', null) === null ? null : column.get('params').toJS();
          const other  = params && params.other ? params.other : {};

          return (
            <BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}>
              {SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn {...other} />}
            </BundleContainer>
          );
        })}

        {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))}

    );
  }

}
<commit_msg>Add aria-label to floatingActionButton (#8574)<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';

import ReactSwipeableViews from 'react-swipeable-views';
import { links, getIndex, getLink } from './tabs_bar';
import { Link } from 'react-router-dom';

import BundleContainer from '../containers/bundle_container';
import ColumnLoading from './column_loading';
import DrawerLoading from './drawer_loading';
import BundleColumnError from './bundle_column_error';
import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, DirectTimeline, FavouritedStatuses, ListTimeline } from '../../ui/util/async-components';

import detectPassiveEvents from 'detect-passive-events';
import { scrollRight } from '../../../scroll';

const componentMap = {
  'COMPOSE': Compose,
  'HOME': HomeTimeline,
  'NOTIFICATIONS': Notifications,
  'PUBLIC': PublicTimeline,
  'COMMUNITY': CommunityTimeline,
  'HASHTAG': HashtagTimeline,
  'DIRECT': DirectTimeline,
  'FAVOURITES': FavouritedStatuses,
  'LIST': ListTimeline,
};

const messages = defineMessages({
  publish: { id: 'compose_form.publish', defaultMessage: 'Toot' },
});

const shouldHideFAB = path => path.match(/^\/statuses\//);

@component => injectIntl(component, { withRef: true })
export default class ColumnsArea extends ImmutablePureComponent {

  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  static propTypes = {
    intl: PropTypes.object.isRequired,
    columns: ImmutablePropTypes.list.isRequired,
    isModalOpen: PropTypes.bool.isRequired,
    singleColumn: PropTypes.bool,
    children: PropTypes.node,
  };

  state = {
    shouldAnimate: false,
  }

  componentWillReceiveProps() {
    this.setState({ shouldAnimate: false });
  }

  componentDidMount() {
    if (!this.props.singleColumn) {
      this.node.addEventListener('wheel', this.handleWheel,  detectPassiveEvents.hasSupport ? { passive: true } : false);
    }

    this.lastIndex   = getIndex(this.context.router.history.location.pathname);
    this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl');

    this.setState({ shouldAnimate: true });
  }

  componentWillUpdate(nextProps) {
    if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) {
      this.node.removeEventListener('wheel', this.handleWheel);
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) {
      this.node.addEventListener('wheel', this.handleWheel,  detectPassiveEvents.hasSupport ? { passive: true } : false);
    }
    this.lastIndex = getIndex(this.context.router.history.location.pathname);
    this.setState({ shouldAnimate: true });
  }

  componentWillUnmount () {
    if (!this.props.singleColumn) {
      this.node.removeEventListener('wheel', this.handleWheel);
    }
  }

  handleChildrenContentChange() {
    if (!this.props.singleColumn) {
      const modifier = this.isRtlLayout ? -1 : 1;
      this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier);
    }
  }

  handleSwipe = (index) => {
    this.pendingIndex = index;

    const nextLinkTranslationId = links[index].props['data-preview-title-id'];
    const currentLinkSelector = '.tabs-bar__link.active';
    const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`;

    // HACK: Remove the active class from the current link and set it to the next one
    // React-router does this for us, but too late, feeling laggy.
    document.querySelector(currentLinkSelector).classList.remove('active');
    document.querySelector(nextLinkSelector).classList.add('active');
  }

  handleAnimationEnd = () => {
    if (typeof this.pendingIndex === 'number') {
      this.context.router.history.push(getLink(this.pendingIndex));
      this.pendingIndex = null;
    }
  }

  handleWheel = () => {
    if (typeof this._interruptScrollAnimation !== 'function') {
      return;
    }

    this._interruptScrollAnimation();
  }

  setRef = (node) => {
    this.node = node;
  }

  renderView = (link, index) => {
    const columnIndex = getIndex(this.context.router.history.location.pathname);
    const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] });
    const icon = link.props['data-preview-icon'];

    const view = (index === columnIndex) ?
      React.cloneElement(this.props.children) :
      <ColumnLoading title={title} icon={icon} />;

    return (

        {view}

    );
  }

  renderLoading = columnId => () => {
    return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />;
  }

  renderError = (props) => {
    return <BundleColumnError {...props} />;
  }

  render () {
    const { columns, children, singleColumn, isModalOpen, intl } = this.props;
    const { shouldAnimate } = this.state;

    const columnIndex = getIndex(this.context.router.history.location.pathname);
    this.pendingIndex = null;

    if (singleColumn) {
      const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/statuses/new' className='floating-action-button' aria-label={intl.formatMessage(messages.publish)}></Link>;

      return columnIndex !== -1 ? [
        <ReactSwipeableViews key='content' index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}>
          {links.map(this.renderView)}
        </ReactSwipeableViews>,

        floatingActionButton,
      ] : [

{children}
,

        floatingActionButton,
      ];
    }

    return (
      <div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}>
        {columns.map(column => {
          const params = column.get('params', null) === null ? null : column.get('params').toJS();
          const other  = params && params.other ? params.other : {};

          return (
            <BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}>
              {SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn {...other} />}
            </BundleContainer>
          );
        })}

        {React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))}

    );
  }

}
<|endoftext|>


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

Class.create("CartManager", FetchedResultPane, {

    __maxChildren: 100,
    __label:null,

    initialize: function($super, element, options){

        options = Object.extend({
            displayMode: 'detail',
            selectable: true
        }, options);
        $super(element, options);

        if(options.label) this.__label = options.label;
        else this.__label = MessageHash["action.cart.9"];
        element.ajxpNode = this._rootNode;
        element.applyDragMove = this.applyDragMove.bind(this);
        AjxpDroppables.add(element, this._rootNode);

        ajaxplorer.observe("server_message", function(event){
            var newValue = XPathSelectSingleNode(event, "nodes_diff/update|nodes_diff/remove");
            if(newValue && this._dataLoaded){
                // Remove or update selection if node has been removed!
            }
        }.bind(this));

        this.updateTitle();

    },

    updateTitle: function(){
        if(this.htmlElement) this.htmlElement.fire("widget:updateTitle", this.__label+' ('+this._rootNode.getChildren().size()+')');
    },

    triggerEvent: function(){
        var oEl = this.htmlElement;
        if(this.stateChangeBuffer) window.clearTimeout(this.stateChangeBuffer);
        this.stateChangeBuffer = window.setTimeout(function(){
            oEl.fire("widget:updateState");
        }, 1500);
        this.reload();
        if(this.options.fit && this.options.fit=="content"){
            this.htmlElement.up('[ajxpClass="AjxpPane"]').ajxpPaneObject.resize();
        }
    },

    clearContent: function(){
        this._rootNode.clear();
        this.updateTitle();
        this.triggerEvent();
    },

    downloadFetchedPaneContent:function(fetchedResultPane, paneLabel){

        if(!$("download_form")) return;
        var props = Object.clone(fetchedResultPane.options.nodeProviderProperties);

        // Replace "search" by "search-cart-download"
        delete props['get_action'];
        if(paneLabel) props["archive_name"] = slugString(paneLabel)+".zip";

        var form = $('download_form');
        form.action = window.ajxpServerAccessPath;
        form.secure_token.value = Connexion.SECURE_TOKEN;
        var gAction;
        form.select("input").each(function(input){
            if(input.name!='get_action' && input.name!='secure_token') input.remove();
            if(input.name == 'get_action') input.value = 'search-cart-download';
        });

        $H(props).each(function(pair){
            form.insert(new Element('input', {type:'hidden', name:pair.key, value:pair.value}));
        });
        try{
            form.submit();
        }catch(e){

        }
        // Reset download form to initial value
        form.down('input[name="get_action"]').setValue('download');

    },

    downloadContent: function(){
        var h = this.getLocalSelectionForPosting();
        if(h.size() == 0) return;

        if(!$("download_form")) return;

        var form = $('download_form');
        form.action = window.ajxpServerAccessPath;
        form.secure_token.value = Connexion.SECURE_TOKEN;
        form.select("input").each(function(input){
            if(input.name!='get_action' && input.name!='secure_token') input.remove();
        });
        h.set('dir', '__AJXP_ZIP_FLAT__/');
        h.set('archive_name', slugString(this.__label)+".zip");
        h.each(function(pair){
            form.insert(new Element('input', {type:'hidden', name:pair.key, value:pair.value}));
        });
        try{
            form.submit();
        }catch(e){

        }
    },

    compressContentAndShare: function(){

        var h = this.getLocalSelectionForPosting();
        if(h.size() == 0) return;
        if((zipEnabled && multipleFilesDownloadEnabled))
        {

            var zipName = window.prompt(MessageHash['action.cart.14'], this.__label);
            if(!zipName) return;
            var index=1;
            var buff = zipName;
            while(ajaxplorer.getContextHolder().fileNameExists(zipName + ".zip", true, ajaxplorer.getContextHolder().getRootNode())){
                zipName = buff + "-" + index; index ++ ;
            }
            h.set('get_action', 'compress');
            h.set('compress_flat', 'true');
            h.set('dir', '/');
            h.set('archive_name', zipName + ".zip");
            var conn = new Connexion();
            conn.setMethod("POST");
            conn.setParameters(h);
            conn.onComplete = function(transport){
                var success = ajaxplorer.actionBar.parseXmlMessage(transport.responseXML);
                if(success){
                    ajaxplorer.goTo('/'+zipName+'.zip');
                    window.setTimeout(function(){
                        ajaxplorer.actionBar.fireAction('share');
                    }, 500);
                }
            }.bind(this);
            conn.sendAsync();
        }

    },

    addCurrentSelection: function(){

        ajaxplorer.getContextHolder().getSelectedNodes().each(function(n){
            if(n.isLeaf()){
                this.localNodeFromRemoteNode(n);
            }else{
                this.recurseLeafs(n);
            }
            this.updateTitle();
            this.triggerEvent();
        }.bind(this));

    },

    getLocalSelectionForPosting:function(){

        var sel = new $H();
        var i = 0;
        this._rootNode.getChildren().each(function(n){
            var key = "file_" + i;
            sel.set(key, n.getPath());
            i++;
        });
        return sel;

    },

    getRootNode: function(){
        return this._rootNode;
    },

    /**
     * Can be overriden by the children.
     * @param ajxpOptions
     * @returns {AjxpDataModel}
     */
    initDataModel: function(ajxpOptions){

        var dataModel = new AjxpDataModel(true);
        var rNodeProvider = new LocalCartNodeProvider();
        dataModel.setAjxpNodeProvider(rNodeProvider);
        rNodeProvider.initProvider(ajxpOptions.nodeProviderProperties);
        this._rootNode = new AjxpNode("/ajxp-local-cart", false, "Cart", "folder.png", rNodeProvider);
        dataModel.setRootNode(this._rootNode);
        return dataModel;

    },

    localNodeFromRemoteNode: function(n){

        if(this._rootNode.findChildByPath(n.getPath())) return;
        var newNode = new AjxpNode(n.getPath(), n.isLeaf(), n.getLabel(), n.getIcon());
        newNode.setMetadata($H(Object.clone(n.getMetadata().toObject())));
        this._rootNode.addChild(newNode);
        this.reload();

    },

    applyDragMove: function(srcName, targetName, nodeId, copy){

        if(srcName != 'ajxp-user-selection') return;
        this.addCurrentSelection();

    },

    recurseLeafs: function(node){

        if(this._rootNode.getChildren().length > this.__maxChildren) {
            this.updateTitle();
            this.triggerEvent();
            ajaxplorer.displayMessage('ERROR', 'Stopping recursion: please do not select more than ' + this.__maxChildren + ' at once!');
            throw $break;
        }

        if(node.isLoaded()){
            node.getChildren().each(function(n){
                if(n.isLeaf()){
                    this.localNodeFromRemoteNode(n);
                }else{
                    this.recurseLeafs(n);
                }
            }.bind(this));
        }else{
            node.observeOnce("loaded", function(){
                this.recurseLeafs(node);
            }.bind(this));
            node.load();
        }

        this.updateTitle();
        this.triggerEvent();

    },

    getStateData: function(){
        var pathes = $A();
        this._rootNode.getChildren().each(function(el){
            pathes.push([el.getPath(), el.getLabel(), el.getIcon()]);
        });
        return pathes;
    },

    loadStateData: function(data){
        window.setTimeout(function(){
            $A(data).each(function(nodeData){
                try{
                    var n = new AjxpNode(nodeData[0], true, nodeData[1], nodeData[2]);
                    n.getMetadata().set('filename', nodeData[0]);
                    this._rootNode.addChild(n);
                }catch(e){}
            }.bind(this));
            this.updateTitle();
        }.bind(this), 4000);
    },

    clearStateData: function(){
        this._rootNode.clear();
        this.updateTitle();
    }

});
<commit_msg>Disable addToCart action in minisite (fix #533)<commit_after>/*
 * Copyright 2007-2013 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
 * This file is part of Pydio.
 *
 * Pydio is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Pydio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Pydio.  If not, see <http://www.gnu.org/licenses/>.
 *
 * The latest code can be found at <http://pyd.io/>.
 */

Class.create("CartManager", FetchedResultPane, {

    __maxChildren: 100,
    __label:null,

    initialize: function($super, element, options){

        options = Object.extend({
            displayMode: 'detail',
            selectable: true
        }, options);
        $super(element, options);

        if(options.label) this.__label = options.label;
        else this.__label = MessageHash["action.cart.9"];
        element.ajxpNode = this._rootNode;
        element.applyDragMove = this.applyDragMove.bind(this);
        AjxpDroppables.add(element, this._rootNode);

        ajaxplorer.observe("server_message", function(event){
            var newValue = XPathSelectSingleNode(event, "nodes_diff/update|nodes_diff/remove");
            if(newValue && this._dataLoaded){
                // Remove or update selection if node has been removed!
            }
        }.bind(this));

        this.updateTitle();

    },

    updateTitle: function(){
        if(this.htmlElement) this.htmlElement.fire("widget:updateTitle", this.__label+' ('+this._rootNode.getChildren().size()+')');
    },

    triggerEvent: function(){
        var oEl = this.htmlElement;
        if(this.stateChangeBuffer) window.clearTimeout(this.stateChangeBuffer);
        this.stateChangeBuffer = window.setTimeout(function(){
            oEl.fire("widget:updateState");
        }, 1500);
        this.reload();
        if(this.options.fit && this.options.fit=="content"){
            this.htmlElement.up('[ajxpClass="AjxpPane"]').ajxpPaneObject.resize();
        }
    },

    clearContent: function(){
        this._rootNode.clear();
        this.updateTitle();
        this.triggerEvent();
    },

    downloadFetchedPaneContent:function(fetchedResultPane, paneLabel){

        if(!$("download_form")) return;
        var props = Object.clone(fetchedResultPane.options.nodeProviderProperties);

        // Replace "search" by "search-cart-download"
        delete props['get_action'];
        if(paneLabel) props["archive_name"] = slugString(paneLabel)+".zip";

        var form = $('download_form');
        form.action = window.ajxpServerAccessPath;
        form.secure_token.value = Connexion.SECURE_TOKEN;
        var gAction;
        form.select("input").each(function(input){
            if(input.name!='get_action' && input.name!='secure_token') input.remove();
            if(input.name == 'get_action') input.value = 'search-cart-download';
        });

        $H(props).each(function(pair){
            form.insert(new Element('input', {type:'hidden', name:pair.key, value:pair.value}));
        });
        try{
            form.submit();
        }catch(e){

        }
        // Reset download form to initial value
        form.down('input[name="get_action"]').setValue('download');

    },

    downloadContent: function(){
        var h = this.getLocalSelectionForPosting();
        if(h.size() == 0) return;

        if(!$("download_form")) return;

        var form = $('download_form');
        form.action = window.ajxpServerAccessPath;
        form.secure_token.value = Connexion.SECURE_TOKEN;
        form.select("input").each(function(input){
            if(input.name!='get_action' && input.name!='secure_token') input.remove();
        });
        h.set('dir', '__AJXP_ZIP_FLAT__/');
        h.set('archive_name', slugString(this.__label)+".zip");
        h.each(function(pair){
            form.insert(new Element('input', {type:'hidden', name:pair.key, value:pair.value}));
        });
        try{
            form.submit();
        }catch(e){

        }
    },

    compressContentAndShare: function(){

        var h = this.getLocalSelectionForPosting();
        if(h.size() == 0) return;
        if((zipEnabled && multipleFilesDownloadEnabled))
        {

            var zipName = window.prompt(MessageHash['action.cart.14'], this.__label);
            if(!zipName) return;
            var index=1;
            var buff = zipName;
            while(ajaxplorer.getContextHolder().fileNameExists(zipName + ".zip", true, ajaxplorer.getContextHolder().getRootNode())){
                zipName = buff + "-" + index; index ++ ;
            }
            h.set('get_action', 'compress');
            h.set('compress_flat', 'true');
            h.set('dir', '/');
            h.set('archive_name', zipName + ".zip");
            var conn = new Connexion();
            conn.setMethod("POST");
            conn.setParameters(h);
            conn.onComplete = function(transport){
                var success = ajaxplorer.actionBar.parseXmlMessage(transport.responseXML);
                if(success){
                    ajaxplorer.goTo('/'+zipName+'.zip');
                    window.setTimeout(function(){
                        ajaxplorer.actionBar.fireAction('share');
                    }, 500);
                }
            }.bind(this);
            conn.sendAsync();
        }

    },

    addCurrentSelection: function(){

        ajaxplorer.getContextHolder().getSelectedNodes().each(function(n){
            if(n.isLeaf()){
                this.localNodeFromRemoteNode(n);
            }else{
                this.recurseLeafs(n);
            }
            this.updateTitle();
            this.triggerEvent();
        }.bind(this));

    },

    getLocalSelectionForPosting:function(){

        var sel = new $H();
        var i = 0;
        this._rootNode.getChildren().each(function(n){
            var key = "file_" + i;
            sel.set(key, n.getPath());
            i++;
        });
        return sel;

    },

    getRootNode: function(){
        return this._rootNode;
    },

    /**
     * Can be overriden by the children.
     * @param ajxpOptions
     * @returns {AjxpDataModel}
     */
    initDataModel: function(ajxpOptions){

        var dataModel = new AjxpDataModel(true);
        var rNodeProvider = new LocalCartNodeProvider();
        dataModel.setAjxpNodeProvider(rNodeProvider);
        rNodeProvider.initProvider(ajxpOptions.nodeProviderProperties);
        this._rootNode = new AjxpNode("/ajxp-local-cart", false, "Cart", "folder.png", rNodeProvider);
        dataModel.setRootNode(this._rootNode);
        return dataModel;

    },

    localNodeFromRemoteNode: function(n){

        if(this._rootNode.findChildByPath(n.getPath())) return;
        var newNode = new AjxpNode(n.getPath(), n.isLeaf(), n.getLabel(), n.getIcon());
        newNode.setMetadata($H(Object.clone(n.getMetadata().toObject())));
        this._rootNode.addChild(newNode);
        this.reload();

    },

    applyDragMove: function(srcName, targetName, nodeId, copy){

        if(srcName != 'ajxp-user-selection') return;
        this.addCurrentSelection();

    },

    recurseLeafs: function(node){

        if(this._rootNode.getChildren().length > this.__maxChildren) {
            this.updateTitle();
            this.triggerEvent();
            ajaxplorer.displayMessage('ERROR', 'Stopping recursion: please do not select more than ' + this.__maxChildren + ' at once!');
            throw $break;
        }

        if(node.isLoaded()){
            node.getChildren().each(function(n){
                if(n.isLeaf()){
                    this.localNodeFromRemoteNode(n);
                }else{
                    this.recurseLeafs(n);
                }
            }.bind(this));
        }else{
            node.observeOnce("loaded", function(){
                this.recurseLeafs(node);
            }.bind(this));
            node.load();
        }

        this.updateTitle();
        this.triggerEvent();

    },

    getStateData: function(){
        var pathes = $A();
        this._rootNode.getChildren().each(function(el){
            pathes.push([el.getPath(), el.getLabel(), el.getIcon()]);
        });
        return pathes;
    },

    loadStateData: function(data){
        window.setTimeout(function(){
            $A(data).each(function(nodeData){
                try{
                    var n = new AjxpNode(nodeData[0], true, nodeData[1], nodeData[2]);
                    n.getMetadata().set('filename', nodeData[0]);
                    this._rootNode.addChild(n);
                }catch(e){}
            }.bind(this));
            this.updateTitle();
        }.bind(this), 4000);
    },

    clearStateData: function(){
        this._rootNode.clear();
        this.updateTitle();
    }

});

if(window.ajxpMinisite){
    document.observe("ajaxplorer:actions_loaded", function(){
        ajaxplorer.actionBar.actions.unset("send-selection-to-cart");
    });
}
<|endoftext|>


<commit_before>'use strict'

angular.module('flashcardModule.services')
    .service('flashcardListDetailsService', function(Flashcards, FlashcardLists) {
        this.getListDetails = function(listId) {
            return FlashcardLists.get( { flashcardListId: listId } );
        };

        this.getFlashcards = function(listId) {
            return Flashcards.query( { flashcard_list_id: listId } );
        };

        this.removeFlashcardFromList = function(flashcard, flashcards) {
            var params = {
                flashcard_list_id: flashcard.flashcard_list_id,
                id: flashcard.id
            };

            var createNewListWithoutElement = function(response) {
                var result = flashcards.slice(0);
                for (var f in flashcards) {
                    if (flashcards[f].id === flashcard.id) {
                        result.splice(f, 1);
                        return result;
                    }
                }
            };

            return Flashcards
                .remove(params)
                .$promise
                .then(createNewListWithoutElement);
        };

        this.updateFlashcard = function(flashcard) {
            return Flashcards
                .update(flashcard)
                .$promise;
        }

        this.createNewFlashcard = function(listId) {
            var newFlashcard = new Flashcards({
                flashcard_list_id: listId
            });

            return Flashcards
                .save(newFlashcard);
        }
    }); <commit_msg>Fix test after update<commit_after>'use strict'

angular.module('flashcardModule.services')
    .service('flashcardListDetailsService', function(Flashcards, FlashcardLists) {
        this.getListDetails = function(listId) {
            return FlashcardLists.get( { flashcardListId: listId } );
        };

        this.getFlashcards = function(listId) {
            return Flashcards.query( { flashcard_list_id: listId } );
        };

        this.removeFlashcardFromList = function(flashcard, flashcards) {
            var params = {
                flashcard_list_id: flashcard.flashcard_list_id,
                id: flashcard.id
            };

            var createNewListWithoutElement = function(response) {
                var result = flashcards.slice(0);
                for (var f in flashcards) {
                    if (flashcards[f].id === flashcard.id) {
                        result.splice(f, 1);
                        return result;
                    }
                }
            };

            return Flashcards
                .remove(params)
                .$promise
                .then(createNewListWithoutElement);
        };

        this.updateFlashcard = function(flashcard) {
            return Flashcards
                .update(flashcard)
                .$promise;
        }

        this.createNewFlashcard = function(listId) {
            var newFlashcard = new Flashcards({
                flashcard_list_id: listId
            });

            return Flashcards
                .save(newFlashcard)
                .$promise;
        }
    }); <|endoftext|>


<commit_before>"use strict";
const path = require("path");
const { Menu, app, shell, BrowserWindow } = require('electron');
const defaultMenu = require('electron-default-menu');
const URL = process.env.FAAO_URL || "https://azu.github.io/faao/";
// context-menu for window
require('electron-context-menu')();
// Standard stuff
app.on("gpu-process-crashed", (event) => {
    console.log("gpu-process-crashed", event);
});
app.on('ready', () => {
    const menu = defaultMenu(app, shell);
    Menu.setApplicationMenu(Menu.buildFromTemplate(menu));
    // browser-window
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            javascript: true,
            plugins: true,
            nodeIntegration: true,  // We will disable this?
            nativeWindowOpen: true,
            webviewTag: true
        }
    });
    mainWindow.maximize();
    mainWindow.loadURL(URL);
});
// https://github.com/electron/electron/blob/master/docs/tutorial/security.md#checklist
app.on('web-contents-created', (event, contents) => {
    contents.on('will-attach-webview', (event, webPreferences, params) => {
        // Strip away preload scripts if unused or verify their location is legitimate
        delete webPreferences.preload;
        delete webPreferences.preloadURL;
        // Disable node integration
        webPreferences.nodeIntegration = false;
    });
});<commit_msg>feat(electron): stop navigation in main webview<commit_after>"use strict";
const url = require("url");
const { Menu, app, shell, BrowserWindow } = require('electron');
const defaultMenu = require('electron-default-menu');
const URL = process.env.FAAO_URL || "https://azu.github.io/faao/";
// context-menu for window
require('electron-context-menu')();
// Standard stuff
app.on("gpu-process-crashed", (event) => {
    console.log("gpu-process-crashed", event);
});
app.on('ready', () => {
    const menu = defaultMenu(app, shell);
    Menu.setApplicationMenu(Menu.buildFromTemplate(menu));
    // browser-window
    const mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            javascript: true,
            plugins: true,
            nodeIntegration: true,  // We will disable this?
            nativeWindowOpen: true,
            webviewTag: true
        }
    });
    mainWindow.maximize();
    mainWindow.loadURL(URL);

    // prevent navigation in main webview
    mainWindow.webContents.on('dom-ready', function(e) {
        mainWindow.webContents.on('will-navigate', (event, URL) => {
            const { protocol } = url.parse(URL);
            if (protocol === "http:" || protocol === "https:") {
                event.preventDefault();
                shell.openExternal(URL);
                console.log("Stop navigation:" + URL);
            }
        });
    });
});
// https://github.com/electron/electron/blob/master/docs/tutorial/security.md#checklist
app.on('web-contents-created', (event, contents) => {
    contents.on('will-attach-webview', (event, webPreferences, params) => {
        // Strip away preload scripts if unused or verify their location is legitimate
        delete webPreferences.preload;
        delete webPreferences.preloadURL;
        // Disable node integration
        webPreferences.nodeIntegration = false;
    });
});<|endoftext|>


<commit_before>// 2D list of chemical elements' symbols along with their full name
var elements = [
	["Ac","Actinium"],
	["Ag","Silver"],
	["Al","Aluminum"],
	["Am","Americium"],
	["Ar","Argon"],
	["As","Arsenic"],
	["At","Astatine"],
	["Au","Gold"],
	["B","Boron"],
	["Ba","Barium"],
	["Be","Beryllium"],
	["Bh","Bohrium"],
	["Bi","Bismuth"],
	["Bk","Berkelium"],
	["Br","Bromine"],
	["C","Carbon"],
	["Ca","Calcium"],
	["Cd","Cadmium"],
	["Ce","Cerium"],
	["Cf","Californium"],
	["Cl","Chlorine"],
	["Cm","Curium"],
	["Co","Cobalt"],
	["Cr","Chromium"],
	["Cs","Cesium"],
	["Cu","Copper"],
	["Db","Dubnium"],
	["Ds","Darmastadtium"],
	["Dy","Dysprosium"],
	["Er","Erbium"],
	["Es","Einsteinium"],
	["Eu","Europium"],
	["F","Fluorine"],
	["Fe","Iron"],
	["Fm","Fermium"],
	["Fr","Francium"],
	["Ga","Gallium"],
	["Gd","Gadolinium"],
	["Ge","Germanium"],
	["H","Hydrogen"],
	["He","Helium"],
	["Hf","Hafnium"],
	["Hg","Mercury"],
	["Ho","Holmium"],
	["Hs","Hassium"],
	["I","Iodine"],
	["In","Indium"],
	["Ir","Iridium"],
	["K","Potassium"],
	["Kr","Krypton"],
	["La","Lathanum"],
	["Li","Lithium"],
	["Lr","Lawrencium"],
	["Lu","Lutetium"],
	["Md","Mendelevium"],
	["Mg","Magnesium"],
	["Mn","Manganese"],
	["Mo","Molybdenum"],
	["Mt","Meitnerium"],
	["N","Nitrogen"],
	["Na","Sodium"],
	["Nb","Niobium"],
	["Nd","Neodymium"],
	["Ne","Neon"],
	["Ni","Nickel"],
	["No","Nobelium"],
	["Np","Neptunium"],
	["O","Oxygen"],
	["Os","Osmium"],
	["P","Phosphorus"],
	["Pa","Protactinium"],
	["Pb","Lead"],
	["Pd","Palladium"],
	["Pm","Promethium"],
	["Po","Polonium"],
	["Pr","Praseodymium"],
	["Pt","Platinum"],
	["Pu","Plutonium"],
	["Ra","Radium"],
	["Rb","Rubidium"],
	["Re","Rhenium"],
	["Rf","Rutherfordium"],
	["Rg","Roentgenium"],
	["Rh","Rhodium"],
	["Rn","Radon"],
	["Ru","Ruthenium"],
	["S","Sulfur"],
	["Sb","Antimony"],
	["Sc","Scandium"],
	["Se","Selenium"],
	["Sg","Seaborgium"],
	["Si","Silicon"],
	["Sm","Samarium"],
	["Sn","Tin"],
	["Sr","Strontium"],
	["Ta","Tantalum"],
	["Tb","Terbium"],
	["Tc","Technetium"],
	["Te","Tellurium"],
	["Th","Thorium"],
	["Ti","Titanium"],
	["Tl","Thallium"],
	["Tm","Thulium"],
	["U","Uranium"],
	["Uub","Ununbium"],
	["Uuh","Ununhexium"],
	["Uuo","Ununoctium"],
	["Uup","Ununpentium"],
	["Uuq","Ununquadium"],
	["Uus","Ununseptium"],
	["Uut","Ununtrium"],
	["V","Vanadium"],
	["W","Tungsten"],
	["Xe","Xenon"],
	["Y","Yttrium"],
	["Yb","Ytterbium"],
	["Zn","Zinc"],
	["Zr","Zirconium"]
];<commit_msg>Updated Elements list<commit_after>// 2D list of chemical elements' symbols along with their full name
var elements = [
	["Ac","Actinium"],
	["Ag","Silver"],
	["Al","Aluminum"],
	["Am","Americium"],
	["Ar","Argon"],
	["As","Arsenic"],
	["At","Astatine"],
	["Au","Gold"],
	["B","Boron"],
	["Ba","Barium"],
	["Be","Beryllium"],
	["Bh","Bohrium"],
	["Bi","Bismuth"],
	["Bk","Berkelium"],
	["Br","Bromine"],
	["C","Carbon"],
	["Ca","Calcium"],
	["Cd","Cadmium"],
	["Ce","Cerium"],
	["Cf","Californium"],
	["Cl","Chlorine"],
	["Cm","Curium"],
	["Co","Cobalt"],
	["Cr","Chromium"],
	["Cs","Cesium"],
	["Cu","Copper"],
	["Db","Dubnium"],
	["Ds","Darmastadtium"],
	["Dy","Dysprosium"],
	["Er","Erbium"],
	["Es","Einsteinium"],
	["Eu","Europium"],
	["F","Fluorine"],
	["Fe","Iron"],
	["Fm","Fermium"],
	["Fr","Francium"],
	["Ga","Gallium"],
	["Gd","Gadolinium"],
	["Ge","Germanium"],
	["H","Hydrogen"],
	["He","Helium"],
	["Hf","Hafnium"],
	["Hg","Mercury"],
	["Ho","Holmium"],
	["Hs","Hassium"],
	["I","Iodine"],
	["In","Indium"],
	["Ir","Iridium"],
	["K","Potassium"],
	["Kr","Krypton"],
	["La","Lathanum"],
	["Li","Lithium"],
	["Lr","Lawrencium"],
	["Lu","Lutetium"],
	["Mc", "Moscovium"],
	["Md","Mendelevium"],
	["Mg","Magnesium"],
	["Mn","Manganese"],
	["Mo","Molybdenum"],
	["Mt","Meitnerium"],
	["N","Nitrogen"],
	["Na","Sodium"],
	["Nb","Niobium"],
	["Nd","Neodymium"],
	["Ne","Neon"],
	["Nh", "Nihonium"],
	["Ni","Nickel"],
	["No","Nobelium"],
	["Np","Neptunium"],
	["O","Oxygen"],
	["Og", "Oganesson"],
	["Os","Osmium"],
	["P","Phosphorus"],
	["Pa","Protactinium"],
	["Pb","Lead"],
	["Pd","Palladium"],
	["Pm","Promethium"],
	["Po","Polonium"],
	["Pr","Praseodymium"],
	["Pt","Platinum"],
	["Pu","Plutonium"],
	["Ra","Radium"],
	["Rb","Rubidium"],
	["Re","Rhenium"],
	["Rf","Rutherfordium"],
	["Rg","Roentgenium"],
	["Rh","Rhodium"],
	["Rn","Radon"],
	["Ru","Ruthenium"],
	["S","Sulfur"],
	["Sb","Antimony"],
	["Sc","Scandium"],
	["Se","Selenium"],
	["Sg","Seaborgium"],
	["Si","Silicon"],
	["Sm","Samarium"],
	["Sn","Tin"],
	["Sr","Strontium"],
	["Ta","Tantalum"],
	["Tb","Terbium"],
	["Tc","Technetium"],
	["Te","Tellurium"],
	["Th","Thorium"],
	["Ti","Titanium"],
	["Tl","Thallium"],
	["Tm","Thulium"],
	["Ts", "Tennessine"],
	["U","Uranium"],
	["Uub","Ununbium"],
	["Uuh","Ununhexium"],
	["Uuo","Ununoctium"],
	["Uup","Ununpentium"],
	["Uuq","Ununquadium"],
	["Uus","Ununseptium"],
	["Uut","Ununtrium"],
	["V","Vanadium"],
	["W","Tungsten"],
	["Xe","Xenon"],
	["Y","Yttrium"],
	["Yb","Ytterbium"],
	["Zn","Zinc"],
	["Zr","Zirconium"]
];
<|endoftext|>


<commit_before>/**
 * ui/EventDetailView.js
 * Event Detail View
 */

module.exports = function (o) {
	var g = this;

	var fontSize = g.config.load("font-size");

	var outer = Ti.UI.createView();

	var view = Ti.UI.createView({
		layout: 'vertical'
	});
	outer.add(view);

	var header = Ti.UI.createView({
		height: g.dip(50),
		backgroundColor: '#177bbd'
	});
	var headerLabel = Ti.UI.createLabel({
		height: g.dip(50),
		top: 0,
		left: g.dip(5),
		text: 'イベント詳細',
		color: '#fff',
		font: {fontSize: g.dip(18), fontWeight: 'bold'}
	});
	header.add(headerLabel);
	view.add(header);

	var menu = {
		"カレンダーへ登録": {
			click: function () {
				g.calendar.addEvent({
					title: o.title,
					location: o.where,
					description: o.content,
					beginTime: new Date(o.when.start),
					endTime: new Date(o.when.end),
					allDay: o.when.allday
				});
			}
		}
	};

	function createTextLine(keyStr, valStr) {
		var key = Ti.UI.createLabel({
			top: 0,
			left: g.dip(5),
			height: g.dip(32),
			text: keyStr,
			color: '#222',
			font: {fontSize: g.dip(16 + fontSize)}
		});
		view.add(key);
		var val = Ti.UI.createLabel({
			top: g.dip(-27),
			left: g.dip(50 + fontSize * 2),
			text: valStr,
			color: '#555',
			font: {fontSize: g.dip(16 + fontSize)}
		});
		view.add(val);

		return {
			key: key,
			val: val
		};
	}

	function label(str, parent) {
		var text = Ti.UI.createLabel({
			left: 0,
			width: Ti.UI.FILL,
			text: str,
			color: '#222',
			font: {fontSize: g.dip(16 + fontSize)}
		});
		(parent ? parent : view).add(text);
		return text;
	}

	// 2012-05-01T12:00:00.000+09:00 -> ['2012-05-01', '12:00'] OR 2012-05-01 -> ['2012-05-01', '']
	function dateFormat(date_str) {
		var date_arr = date_str.split('.')[0].split(':');
		date_arr = date_arr.length === 1
			? [date_arr, '']
			: date_arr.slice(0, -1).join(':').split('T');
		return date_arr;
	}

	var	d = {
			start: dateFormat(o.when.start),
			end: dateFormat(o.when.end)
		};

	if (o.when.allday)
		d.start[1] = d.end[1] = "";
	var timeLabel = String(d.start[0] + ' ' + d.start[1] + ' ~ ' + d.end[0] + ' ' + d.end[1]);

	var title = label(o.title);
	title.top = g.dip(3);
	title.font = {fontSize: g.dip(18 + fontSize)};
	title.backgroundColor = '#f9f9f9';

	var hr = Ti.UI.createView({
		top: g.dip(3),
		height: g.dip(3),
		backgroundColor: '#177bbd'
	});
	view.add(hr);

	var time = createTextLine('時間 :', timeLabel);
	time.val.font = {fontSize: g.dip(15)};
	time.val.color = '#555';
	var place = createTextLine('場所 :', o.where || " ");
	var content = createTextLine('内容 :', o.content || " ");
	content.val.height = 'auto';
	var link = label('Googleカレンダーへのリンク');
	link.top = g.dip(15);
	link.left = g.dip(5);
	link.color = '#04b';
	link.addEventListener('click', function () {
		Ti.Platform.openURL(o.link);
	});

	// share message
	var message = o.title + ' ' + o.link + ' #IT勉強会カレンダー';

	if (Ti.Platform.Android) {
		// Auto link
		content.val.autoLink = Titanium.UI.Android.LINKIFY_WEB_URLS;

		// 地図検索
		var intent = Ti.Android.createIntent({
			action: Ti.Android.ACTION_VIEW,
			data: 'geo:0,0?q=' + encodeURIComponent(o.where)
		});
		chooser = Ti.Android.createIntentChooser(intent, 'アプリケーションを選択');
		place.val.color = '#04b';
		place.val.addEventListener('click', function () {
			Ti.Android.currentActivity.startActivity(chooser);
		});

		// intent の多重発行防止
		var intent_enable = true;
		var intent_call = function (callback) {
			if (intent_enable) {
				intent_enable = false;
				setTimeout(function () {
					intent_enable = true;
				}, 500);
				callback();
			}
		};

		// 共有
		var intent_share = Ti.Android.createIntent({
			action: Ti.Android.ACTION_SEND,
			type: 'text/plain'
		});
		intent_share.putExtra(Ti.Android.EXTRA_TEXT, message);
		menu["共有"] = {
			click: function () {
				intent_call(function () {
					Ti.Android.currentActivity.startActivity(intent_share);
				});
			}
		};
	} else {
		menu["Twitter 共有"] = {
			click: function () {
				var canOpen = Ti.Platform.openURL('twitter://post?message=' + encodeURIComponent(message));
				if (! canOpen) {
					var dialog = g.alert('Twitter 共有', 'Twitter 公式アプリが必要です。');
					dialog.addEventListener("click", function () {
						Ti.Platform.openURL('https://itunes.apple.com/ja/app/twitter/id333903271');
					});
				}
			}
		};
	}

	// set menu
	g.createMenu(outer, menu, true);

	return outer;
};<commit_msg>Add content link for iOS<commit_after>/**
 * ui/EventDetailView.js
 * Event Detail View
 */

module.exports = function (o) {
	var g = this;

	var fontSize = g.config.load("font-size");

	var outer = Ti.UI.createView();

	var view = Ti.UI.createView({
		layout: 'vertical'
	});
	outer.add(view);

	var header = Ti.UI.createView({
		height: g.dip(50),
		backgroundColor: '#177bbd'
	});
	var headerLabel = Ti.UI.createLabel({
		height: g.dip(50),
		top: 0,
		left: g.dip(5),
		text: 'イベント詳細',
		color: '#fff',
		font: {fontSize: g.dip(18), fontWeight: 'bold'}
	});
	header.add(headerLabel);
	view.add(header);

	var menu = {
		"カレンダーへ登録": {
			click: function () {
				g.calendar.addEvent({
					title: o.title,
					location: o.where,
					description: o.content,
					beginTime: new Date(o.when.start),
					endTime: new Date(o.when.end),
					allDay: o.when.allday
				});
			}
		}
	};

	function createTextLine(keyStr, valStr) {
		var key = Ti.UI.createLabel({
			top: 0,
			left: g.dip(5),
			height: g.dip(32),
			text: keyStr,
			color: '#222',
			font: {fontSize: g.dip(16 + fontSize)}
		});
		view.add(key);
		var val = Ti.UI.createLabel({
			top: g.dip(-27),
			left: g.dip(50 + fontSize * 2),
			text: valStr,
			color: '#555',
			font: {fontSize: g.dip(16 + fontSize)}
		});
		view.add(val);

		return {
			key: key,
			val: val
		};
	}

	function label(str, parent) {
		var text = Ti.UI.createLabel({
			left: 0,
			width: Ti.UI.FILL,
			text: str,
			color: '#222',
			font: {fontSize: g.dip(16 + fontSize)}
		});
		(parent ? parent : view).add(text);
		return text;
	}

	// 2012-05-01T12:00:00.000+09:00 -> ['2012-05-01', '12:00'] OR 2012-05-01 -> ['2012-05-01', '']
	function dateFormat(date_str) {
		var date_arr = date_str.split('.')[0].split(':');
		date_arr = date_arr.length === 1
			? [date_arr, '']
			: date_arr.slice(0, -1).join(':').split('T');
		return date_arr;
	}

	var	d = {
			start: dateFormat(o.when.start),
			end: dateFormat(o.when.end)
		};

	if (o.when.allday)
		d.start[1] = d.end[1] = "";
	var timeLabel = String(d.start[0] + ' ' + d.start[1] + ' ~ ' + d.end[0] + ' ' + d.end[1]);

	var title = label(o.title);
	title.top = g.dip(3);
	title.font = {fontSize: g.dip(18 + fontSize)};
	title.backgroundColor = '#f9f9f9';

	var hr = Ti.UI.createView({
		top: g.dip(3),
		height: g.dip(3),
		backgroundColor: '#177bbd'
	});
	view.add(hr);

	var time = createTextLine('時間 :', timeLabel);
	time.val.font = {fontSize: g.dip(15)};
	time.val.color = '#555';
	var place = createTextLine('場所 :', o.where || " ");
	var content = createTextLine('内容 :', o.content || " ");
	content.val.height = 'auto';
	var link = label('Googleカレンダーへのリンク');
	link.top = g.dip(15);
	link.left = g.dip(5);
	link.color = '#04b';
	link.addEventListener('click', function () {
		Ti.Platform.openURL(o.link);
	});

	// share message
	var message = o.title + ' ' + o.link + ' #IT勉強会カレンダー';

	if (Ti.Platform.Android) {
		// Auto link
		content.val.autoLink = Titanium.UI.Android.LINKIFY_WEB_URLS;

		// 地図検索
		var intent = Ti.Android.createIntent({
			action: Ti.Android.ACTION_VIEW,
			data: 'geo:0,0?q=' + encodeURIComponent(o.where)
		});
		chooser = Ti.Android.createIntentChooser(intent, 'アプリケーションを選択');
		place.val.color = '#04b';
		place.val.addEventListener('click', function () {
			Ti.Android.currentActivity.startActivity(chooser);
		});

		// intent の多重発行防止
		var intent_enable = true;
		var intent_call = function (callback) {
			if (intent_enable) {
				intent_enable = false;
				setTimeout(function () {
					intent_enable = true;
				}, 500);
				callback();
			}
		};

		// 共有
		var intent_share = Ti.Android.createIntent({
			action: Ti.Android.ACTION_SEND,
			type: 'text/plain'
		});
		intent_share.putExtra(Ti.Android.EXTRA_TEXT, message);
		menu["共有"] = {
			click: function () {
				intent_call(function () {
					Ti.Android.currentActivity.startActivity(intent_share);
				});
			}
		};
	} else {
		// for iOS

		// URL チェック
		var urls = o.content.split(/\s/).filter(function (str) {
			return /^https?:\/\/.+\..+$/.test(str);
		});
		if (urls.length > 0) {
			// リンク追加
			content.val.color = '#04b';
			content.val.addEventListener('click', function () {
				Ti.Platform.openURL(urls[0]);
			});
		}

		menu["Twitter 共有"] = {
			click: function () {
				var canOpen = Ti.Platform.openURL('twitter://post?message=' + encodeURIComponent(message));
				if (! canOpen) {
					var dialog = g.alert('Twitter 共有', 'Twitter 公式アプリが必要です。');
					dialog.addEventListener("click", function () {
						Ti.Platform.openURL('https://itunes.apple.com/ja/app/twitter/id333903271');
					});
				}
			}
		};
	}

	// set menu
	g.createMenu(outer, menu, true);

	return outer;
};<|endoftext|>


<commit_before>var COMMCAREHQ_URLS = {};
hqDefine('hqwebapp/js/urllib.js', function () {
    // http://stackoverflow.com/a/21903119/240553
    var getUrlParameter = function (sParam) {
        return getUrlParameterFromString(sParam, window.location.search);
    };
    var getUrlParameterFromString = function (sParam, sSearch) {
        var sPageURL = decodeURIComponent(sSearch.substring(1)),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return sParameterName[1] === undefined ? true : sParameterName[1];
            }
        }
    };
    var registerUrl = function(name, url) {
        COMMCAREHQ_URLS[name] = url;
    };
    var reverse = function (name) {
        var args = arguments;
        var index = 1;
        return COMMCAREHQ_URLS[name].replace(/---/g, function () {
            return args[index++];
        });
    };
    return {
        getUrlParameter: getUrlParameter,
        getUrlParameterFromString: getUrlParameterFromString,
        registerUrl: registerUrl,
        reverse: reverse,
    };
});
<commit_msg>change getUrlParameter variable naming style<commit_after>var COMMCAREHQ_URLS = {};
hqDefine('hqwebapp/js/urllib.js', function () {
    // http://stackoverflow.com/a/21903119/240553
    var getUrlParameter = function (param) {
        return getUrlParameterFromString(param, window.location.search);
    };
    var getUrlParameterFromString = function (param, search) {
        var pageUrl = decodeURIComponent(search.substring(1)),
            urlVariables = pageUrl.split('&'),
            parameterName,
            i;

        for (i = 0; i < urlVariables.length; i++) {
            parameterName = urlVariables[i].split('=');

            if (parameterName[0] === param) {
                return parameterName[1] === undefined ? true : parameterName[1];
            }
        }
    };
    var registerUrl = function(name, url) {
        COMMCAREHQ_URLS[name] = url;
    };
    var reverse = function (name) {
        var args = arguments;
        var index = 1;
        return COMMCAREHQ_URLS[name].replace(/---/g, function () {
            return args[index++];
        });
    };
    return {
        getUrlParameter: getUrlParameter,
        getUrlParameterFromString: getUrlParameterFromString,
        registerUrl: registerUrl,
        reverse: reverse,
    };
});
<|endoftext|>


<commit_before>
var stream = require('stream');
var util = require('util');

function Endpoint(options, callback) {
  if (!(this instanceof Endpoint)) return new Endpoint(options, callback);

  // `options` defaults to {}
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }

  stream.Writable.call(this, options);
  var self = this;

  this._objectMode = !!options.objectMode;

  // will keep a long list of buffers
  this._buffers = [];

  // Cleanup event listeners
  var sources = [];
  function cleanup() {
    self.removeListener('pipe', onpipe);
    self.removeListener('error', error);
    self.removeListener('finish', finish);
    for (var i = 0, l = sources.length; i < l; i++) {
      sources[i].removeListener('error', error);
    }
  }

  // Either finish or error will be used to declare a done state
  function finish() {
    cleanup();
    callback(null, self.buffer);
  }

  function error(err) {
    cleanup();
    callback(err, self.buffer);
  }

  // Handle errors on source streams
  function onpipe(source) {
    sources.push(source);
    source.once('error', error);
  }
  function onunpipe(source) {
    var index = sources.indexOf(source);
    if (index !== -1) {
      sources.splice(index, 1);
      source.removeListener('error', error);
    }
  }

  this.once('finish', finish);
  this.once('error', error);
  this.on('pipe', onpipe);
  this.on('unpipe', onunpipe);
}
module.exports = Endpoint;
util.inherits(Endpoint, stream.Writable);

Endpoint.prototype._write = function (data, encodeing, callback) {
  this._buffers.push(data);

  return callback(null);
};

Object.defineProperty(Endpoint.prototype, "buffer", {
  get: function () {
    if (this._objectMode) {
      return this._buffers;
    } else {
      var total = Buffer.concat(this._buffers);
      this._buffers = [ total ];
      return total;
    }
  },
  enumerable: true,
  configurable: true
});
<commit_msg>[feature] try using readable-stream<commit_after>
var Writable = require('stream').Writable;
var util = require('util');

if (Writable === undefined) {
  try {
    Writable = require('readable-stream').Writable;
  } catch (e) {
    throw new Error('stream v2 is not supported by your node version, upgrade or install readable-stream');
  }
}

function Endpoint(options, callback) {
  if (!(this instanceof Endpoint)) return new Endpoint(options, callback);

  // `options` defaults to {}
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }

  Writable.call(this, options);
  var self = this;

  this._objectMode = !!options.objectMode;

  // will keep a long list of buffers
  this._buffers = [];

  // Cleanup event listeners
  var sources = [];
  function cleanup() {
    self.removeListener('pipe', onpipe);
    self.removeListener('error', error);
    self.removeListener('finish', finish);
    for (var i = 0, l = sources.length; i < l; i++) {
      sources[i].removeListener('error', error);
    }
  }

  // Either finish or error will be used to declare a done state
  function finish() {
    cleanup();
    callback(null, self.buffer);
  }

  function error(err) {
    cleanup();
    callback(err, self.buffer);
  }

  // Handle errors on source streams
  function onpipe(source) {
    sources.push(source);
    source.once('error', error);
  }
  function onunpipe(source) {
    var index = sources.indexOf(source);
    if (index !== -1) {
      sources.splice(index, 1);
      source.removeListener('error', error);
    }
  }

  this.once('finish', finish);
  this.once('error', error);
  this.on('pipe', onpipe);
  this.on('unpipe', onunpipe);
}
module.exports = Endpoint;
util.inherits(Endpoint, Writable);

Endpoint.prototype._write = function (data, encodeing, callback) {
  this._buffers.push(data);

  return callback(null);
};

Object.defineProperty(Endpoint.prototype, "buffer", {
  get: function () {
    if (this._objectMode) {
      return this._buffers;
    } else {
      var total = Buffer.concat(this._buffers);
      this._buffers = [ total ];
      return total;
    }
  },
  enumerable: true,
  configurable: true
});
<|endoftext|>


<commit_before>var guiStatus;

function setupGUI() {
  guiStatus =  new GuiStatus();
  resizeGUI();

  var fiberSelector = document.getElementById("fiberSelector");
  var regionSelector = document.getElementById("regionSelector");
  // Empty them - this function might be called for GUIupdating
  fiberSelector.innerHTML = "";
  regionSelector.innerHTML = "";

  if (phantom.fibers.source.length > 0) {
    // Add *none* option
    var option = document.createElement("option");
    option.text = '*none*'
    option.selected = true;
    // If any fiber is being edited, move to non-edit mode
    option.onclick = function() {
      if (guiStatus.editingRegion === undefined) {
        guiStatus.unediting();
        guiStatus.retrieve();
      };
      resizeGUI();
    };
    fiberSelector.options.add(option);
    fiberSelector.disabled = false;

    // Add the rest of the options
    phantom.fibers.source.forEach( function(fiber, index) {
      var backgroundColor = fiber.color;

      var option = document.createElement("option");
      var selectColorSpan = document.createElement("span");
      var selectTextSpan = document.createElement("span");
      selectColorSpan.style.color = backgroundColor.getStyle();
      selectColorSpan.innerHTML = '■ ';

      selectTextSpan.innerHTML = fiber.controlPoints.length.toString() + " points";

      option.appendChild(selectColorSpan);
      option.appendChild(selectTextSpan);

      option.onmouseover = function() {phantom.fiberHighlight(index);};
      option.onclick = function() {fiberSelectClick(index);};
      fiberSelector.options.add(option);
    });
  } else {
    fiberSelector.disabled = true;
  }

  if (phantom.isotropicRegions.source.length > 0) {
    // Add *none* option
    var option = document.createElement("option");
    option.text = '*none*'
    option.selected = true;
    // If any fiber is being edited, move to non-edit mode
    option.onclick = function() {
      if (guiStatus.editingFiber === undefined) {
        guiStatus.unediting();
        guiStatus.retrieve();
      };
      resizeGUI();
    };
    regionSelector.options.add(option);
    regionSelector.disabled = false;

    // Add the rest of the options
    phantom.isotropicRegions.source.forEach( function(region, index) {
      var backgroundColor = region.color;

      var option = document.createElement("option");
      var selectColorSpan = document.createElement("span");
      var selectTextSpan = document.createElement("span");
      selectColorSpan.style.color = backgroundColor.getStyle();
      selectColorSpan.innerHTML = '■ ';

      selectTextSpan.innerHTML = "radius " + region.radius.toString();

      option.appendChild(selectColorSpan);
      option.appendChild(selectTextSpan);

      option.onmouseover = function() {phantom.regionHighlight(index);};
      option.onclick = function() {regionSelectClick(index);};
      regionSelector.options.add(option);
    });
  } else {
    regionSelector.disabled = true;
  }

  editExit();
}

// Add element buttons are only available when no element is being edited
function editExit() {
  var editGUI = document.getElementById('editGUI');
  editGUI.innerHTML = ""

  var newfiberbutton = document.createElement("BUTTON");
  var newregionbutton = document.createElement("BUTTON");
  editGUI.appendChild(newfiberbutton);
  editGUI.appendChild(newregionbutton);

  newfiberbutton.innerHTML = "New Fiber";
  newfiberbutton.onclick = function() { newFiberClick() };

  newregionbutton.innerHTML = "New Region";
  newregionbutton.onclick = function() { newIsotropicRegionClick() };
}
<commit_msg>New element buttons styled for right align<commit_after>var guiStatus;

function setupGUI() {
  guiStatus =  new GuiStatus();
  resizeGUI();

  var fiberSelector = document.getElementById("fiberSelector");
  var regionSelector = document.getElementById("regionSelector");
  // Empty them - this function might be called for GUIupdating
  fiberSelector.innerHTML = "";
  regionSelector.innerHTML = "";

  if (phantom.fibers.source.length > 0) {
    // Add *none* option
    var option = document.createElement("option");
    option.text = '*none*'
    option.selected = true;
    // If any fiber is being edited, move to non-edit mode
    option.onclick = function() {
      if (guiStatus.editingRegion === undefined) {
        guiStatus.unediting();
        guiStatus.retrieve();
      };
      resizeGUI();
    };
    fiberSelector.options.add(option);
    fiberSelector.disabled = false;

    // Add the rest of the options
    phantom.fibers.source.forEach( function(fiber, index) {
      var backgroundColor = fiber.color;

      var option = document.createElement("option");
      var selectColorSpan = document.createElement("span");
      var selectTextSpan = document.createElement("span");
      selectColorSpan.style.color = backgroundColor.getStyle();
      selectColorSpan.innerHTML = '■ ';

      selectTextSpan.innerHTML = fiber.controlPoints.length.toString() + " points";

      option.appendChild(selectColorSpan);
      option.appendChild(selectTextSpan);

      option.onmouseover = function() {phantom.fiberHighlight(index);};
      option.onclick = function() {fiberSelectClick(index);};
      fiberSelector.options.add(option);
    });
  } else {
    fiberSelector.disabled = true;
  }

  if (phantom.isotropicRegions.source.length > 0) {
    // Add *none* option
    var option = document.createElement("option");
    option.text = '*none*'
    option.selected = true;
    // If any fiber is being edited, move to non-edit mode
    option.onclick = function() {
      if (guiStatus.editingFiber === undefined) {
        guiStatus.unediting();
        guiStatus.retrieve();
      };
      resizeGUI();
    };
    regionSelector.options.add(option);
    regionSelector.disabled = false;

    // Add the rest of the options
    phantom.isotropicRegions.source.forEach( function(region, index) {
      var backgroundColor = region.color;

      var option = document.createElement("option");
      var selectColorSpan = document.createElement("span");
      var selectTextSpan = document.createElement("span");
      selectColorSpan.style.color = backgroundColor.getStyle();
      selectColorSpan.innerHTML = '■ ';

      selectTextSpan.innerHTML = "radius " + region.radius.toString();

      option.appendChild(selectColorSpan);
      option.appendChild(selectTextSpan);

      option.onmouseover = function() {phantom.regionHighlight(index);};
      option.onclick = function() {regionSelectClick(index);};
      regionSelector.options.add(option);
    });
  } else {
    regionSelector.disabled = true;
  }

  editExit();
}

// Add element buttons are only available when no element is being edited
function editExit() {
  var editGUI = document.getElementById('editGUI');
  editGUI.innerHTML = ""

  var newfiberbutton = document.createElement("BUTTON");
  newfiberbutton.style.float = "right";
  newfiberbutton.innerHTML = "New Fiber";
  newfiberbutton.onclick = function() { newFiberClick() };

  var newregionbutton = document.createElement("BUTTON");
  newregionbutton.style.float = "right";
  newregionbutton.innerHTML = "New Region";
  newregionbutton.onclick = function() { newIsotropicRegionClick() };

  // As style is float, must be appended from right to left
  editGUI.appendChild(newregionbutton);
  editGUI.appendChild(newfiberbutton);
}
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2016 Zachery Sogolow

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

(function () {
    EntitizeNamespace = {
        types: {},
        settings: {}
    };

    // pass the Entitize function a serialized object, and
    // the entityType as defined in the settings
    Entitize = function (jsObject, entitytype) {

        if (jsObject && entitytype) {
            var jEntity = new JEntity(jsObject, entitytype);
            return jEntity;
        }

        this.entitize = function () {
            // the accumulator
            var objToSave = {};
            // the object mappings based on the entityType
            var mappings = EntitizeNamespace.settings[this.entityType];

            // loop through each property mapping, checking each one first
            // to see if there is a nav property defined for it
            for (var prop in mappings) {
                var mapping = mappings[prop];
                // if nav = true, we need to recurse on the child
                // object(s) by calling entitize() on them, storing
                // the results as we go
                if (mapping.nav) {
                    // get the relationship
                    var relationship = mapping.relationship;
                    if (relationship === "one-to-many") {
                        // one to many relationship, the nav property must be of
                        // type array. copy the array into navChildren
                        var navChildren = this[mapping.propName];
                        // clear out property, store new objects here
                        objToSave[mapping.propName] = [];

                        // loop through each child object in the array
                        // of children, entitizing each one along the way
                        // and storing them in the objToSave array
                        for (var prop in navChildren) {
                            var obj = navChildren[prop].entitize();
                            objToSave[mapping.propName].push(obj);
                        }
                    } else if (relationship === "one-to-one") {
                        // the relationship is one to one, save the individual
                        // object, if it exists
                        if (this[mapping.propName]) {
                            objToSave[mapping.propName] = this[mapping.propName].entitize();
                        } else {
                            // todo?? how to handle deletion of objects
                            objToSave[mapping.propName] = null;
                        }
                    }
                } else {
                    // there is no nav property defined, copy the value type to the
                    // object being returned
                    objToSave[mapping.propName] = this[mapping.propName];
                }
            }

            // finally, return the object we were accumulating
            return objToSave;
        }
    }

    // initialize with constructors OR settings object
    Entitize.initialize = function (settings) {
        if (typeof (settings) === 'function') {
            var constructor = settings;
            constructor.prototype = new Entitize();
            constructor.prototype.constructor = constructor;
            var baseObj = new constructor();
            //baseObj.__proto__ = new Entitize();
            EntitizeNamespace.types[baseObj.type] = baseObj;
            EntitizeNamespace.settings[baseObj.type] = baseObj.mappings;
        } else {
            var types = {};
            for (var type in settings) {
                if (typeof (settings[type]) === 'function') {
                    var mappingContructor = settings[type];
                    mappingContructor.prototype = new Entitize();
                    mappingContructor.prototype.constructor = mappingContructor;
                    var baseObj = new mappingContructor();
                    //baseObj.__proto__ = new Entitize();
                    EntitizeNamespace.types[baseObj.type] = baseObj;
                    EntitizeNamespace.settings[baseObj.type] = baseObj.mappings;
                } else if (typeof (settings[type]) === 'object') {
                    var mappings = settings[type];
                    for (var prop in mappings) {
                        var dynamicConstructor = eval(prop + " = function() { }")
                        dynamicConstructor.prototype = new Entitize();
                        dynamicConstructor.prototype.constructor = dynamicConstructor;
                        var baseObj = new dynamicConstructor();
                        baseObj.type = prop;
                        baseObj.mappings = mappings;
                        //baseObj.__proto__ = new Entitize();
                        EntitizeNamespace.types[baseObj.type] = baseObj;
                        EntitizeNamespace.settings[baseObj.type] = baseObj.mappings[baseObj.type];
                    }
                }
            }
        }
        return EntitizeNamespace;
    }

    // extends all of the properties and functions
    // from object => target if object.hasOwnProp
    Entitize.extend = function (target, object) {
        for (var prop in object) {
            if (object.hasOwnProperty(prop)) {
                target[prop] = object[prop];
            }
        }
    }

    // extends all of the properties and functions from
    // object => all objects that have been created or will be
    // created with the given entityType
    Entitize.extendType = function (entityType, object) {
        Entitize.extend(EntitizeNamespace.types[entityType], object);
    }

    Entitize.create = function (entityType) {
        if (!entityType || entityType === "Entitize") return new Entitize();
        var accumulator = {};
        var baseObj = EntitizeNamespace.types[entityType];
        var mappings = baseObj.mappings;
        for (var i = 0; i < baseObj.mappings.length; i++) {
            var mapping = baseObj.mappings[i];
            if (mapping.nav) {
                accumulator[mapping.propName] = null; //Entitize.create(mapping.childType);
            } else {
                accumulator[mapping.propName] = null;
            }
        }
        return Entitize(accumulator, entityType);
    }

    var isArrayLike = function (obj) {
        return obj && typeof obj === "object" && (obj.length === 0 || typeof obj.length === "number" && obj.length > 0 && obj.length - 1 in obj);
    };

    // JEntity Base Constructor. Every object is a JEntity.
    // Configure the new object we are creating based on the
    // mappings for that object
    JEntity = function (jsObject, entityType) {
        var mappings = EntitizeNamespace.settings[entityType];
        this.entityType = entityType;
        var newEntity = {};
        Entitize.extend(newEntity, jsObject);

        // first try to configure all of the mappings
        for (var i = 0; i < mappings.length; i++) {
            var mapping = mappings[i];
            // if there is a nav property for this object,
            // we need to create JEntity's for them as well
            if (mapping.nav) {
                var navProp = mapping.propName; // propName
                var relation = mapping.relationship; // nav relationship
                var childType = mapping.childType; // nav childType
                // check the type of relationship
                if (relation === "one-to-many") {
                    // one to many, we need to Entitize each object in the relation
                    var relationObjects = newEntity[navProp];
                    newEntity[navProp] = []; // we will be adding to jsObject[navProp]
                    for (var obj in relationObjects) {
                        var entitizeMe = relationObjects[obj];
                        var entitized = Entitize(entitizeMe, childType)
                        newEntity[navProp].push(entitized);
                    }
                } else if (relation === "one-to-one") {
                    // one to one relation, Entitize the object
                    var entitizeMe = newEntity[navProp];
                    var entitized = Entitize(entitizeMe, childType);
                    newEntity[navProp] = entitized;
                }
            }
        }

        // extend all of the properties in the jsObject, including the newly created
        // relation JEntity objects
        Entitize.extend(this, newEntity);

        // set the proto to the base object as all other types
        this.__proto__ = EntitizeNamespace.types[this.entityType];
    }

})();

<commit_msg>changed way objects are constructed<commit_after>/*
The MIT License (MIT)

Copyright (c) 2016 Zachery Sogolow

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

(function () {
    EntitizeNamespace = {
        types: {},
        settings: {}
    };

    // pass the Entitize function a serialized object, and
    // the entityType as defined in the settings
    Entitize = function (jsObject, entitytype) {

        if (jsObject && entitytype) {
            // was necessary to set prototype of newly created objects
            // mutating the [[Prototype]] of an object will cause your code to run very slowly, Firefox 44.0.2
            // before, was setting __proto__ in the JEntity constructor
            function Entity() { }
            Entity.prototype = EntitizeNamespace.types[entitytype];
            Entity.prototype.constructor = Entity;
            var anon = new Entity();
            JEntity.call(anon, jsObject, entitytype)
            return anon;
        }

        this.entitize = function () {
            // the accumulator
            var objToSave = {};
            // the object mappings based on the entityType
            var mappings = EntitizeNamespace.settings[this.entityType];

            // loop through each property mapping, checking each one first
            // to see if there is a nav property defined for it
            for (var prop in mappings) {
                var mapping = mappings[prop];
                // if nav = true, we need to recurse on the child
                // object(s) by calling entitize() on them, storing
                // the results as we go
                if (mapping.nav) {
                    // get the relationship
                    var relationship = mapping.relationship;
                    if (relationship === "one-to-many") {
                        // one to many relationship, the nav property must be of
                        // type array. copy the array into navChildren
                        var navChildren = this[mapping.propName];
                        // clear out property, store new objects here
                        objToSave[mapping.propName] = [];

                        // loop through each child object in the array
                        // of children, entitizing each one along the way
                        // and storing them in the objToSave array
                        for (var prop in navChildren) {
                            var obj = navChildren[prop].entitize();
                            objToSave[mapping.propName].push(obj);
                        }
                    } else if (relationship === "one-to-one") {
                        // the relationship is one to one, save the individual
                        // object, if it exists
                        if (this[mapping.propName]) {
                            objToSave[mapping.propName] = this[mapping.propName].entitize();
                        } else {
                            // todo?? how to handle deletion of objects
                            objToSave[mapping.propName] = null;
                        }
                    }
                } else {
                    // there is no nav property defined, copy the value type to the
                    // object being returned
                    objToSave[mapping.propName] = this[mapping.propName];
                }
            }

            // finally, return the object we were accumulating
            return objToSave;
        }
    }

    // initialize with constructors OR settings object
    Entitize.initialize = function (settings) {
        if (typeof (settings) === 'function') {
            var constructor = settings;
            constructor.prototype = new Entitize();
            constructor.prototype.constructor = constructor;
            var baseObj = new constructor();
            //baseObj.__proto__ = new Entitize();
            EntitizeNamespace.types[baseObj.type] = baseObj;
            EntitizeNamespace.settings[baseObj.type] = baseObj.mappings;
        } else {
            var types = {};
            for (var type in settings) {
                if (typeof (settings[type]) === 'function') {
                    var mappingContructor = settings[type];
                    mappingContructor.prototype = new Entitize();
                    mappingContructor.prototype.constructor = mappingContructor;
                    var baseObj = new mappingContructor();
                    //baseObj.__proto__ = new Entitize();
                    EntitizeNamespace.types[baseObj.type] = baseObj;
                    EntitizeNamespace.settings[baseObj.type] = baseObj.mappings;
                } else if (typeof (settings[type]) === 'object') {
                    var mappings = settings[type];
                    for (var prop in mappings) {
                        var dynamicConstructor = eval(prop + " = function() { }")
                        dynamicConstructor.prototype = new Entitize();
                        dynamicConstructor.prototype.constructor = dynamicConstructor;
                        var baseObj = new dynamicConstructor();
                        baseObj.type = prop;
                        baseObj.mappings = mappings;
                        //baseObj.__proto__ = new Entitize();
                        EntitizeNamespace.types[baseObj.type] = baseObj;
                        EntitizeNamespace.settings[baseObj.type] = baseObj.mappings[baseObj.type];
                    }
                }
            }
        }

        return EntitizeNamespace;
    }

    // extends all of the properties and functions
    // from object => target if object.hasOwnProp
    Entitize.extend = function (target, object) {
        for (var prop in object) {
            if (object.hasOwnProperty(prop)) {
                target[prop] = object[prop];
            }
        }
    }

    // extends all of the properties and functions from
    // object => all objects that have been created or will be
    // created with the given entityType
    Entitize.extendType = function (entityType, object) {
        Entitize.extend(EntitizeNamespace.types[entityType], object);
    }

    Entitize.create = function (entityType) {
        if (!entityType || entityType === "Entitize") return new Entitize();
        var accumulator = {};
        var baseObj = EntitizeNamespace.types[entityType];
        var mappings = baseObj.mappings;
        for (var i = 0; i < baseObj.mappings.length; i++) {
            var mapping = baseObj.mappings[i];
            if (mapping.nav) {
                accumulator[mapping.propName] = null; //Entitize.create(mapping.childType);
            } else {
                accumulator[mapping.propName] = null;
            }
        }
        return Entitize(accumulator, entityType);
    }

    var isArrayLike = function (obj) {
        return obj && typeof obj === "object" && (obj.length === 0 || typeof obj.length === "number" && obj.length > 0 && obj.length - 1 in obj);
    };

    // JEntity Base Constructor. Every object is a JEntity.
    // Configure the new object we are creating based on the
    // mappings for that object
    JEntity = function (jsObject, entityType) {
        var mappings = EntitizeNamespace.settings[entityType];
        this.entityType = entityType;
        var newEntity = {};
        Entitize.extend(newEntity, jsObject);

        // first try to configure all of the mappings
        for (var i = 0; i < mappings.length; i++) {
            var mapping = mappings[i];
            // if there is a nav property for this object,
            // we need to create JEntity's for them as well
            if (mapping.nav) {
                var navProp = mapping.propName; // propName
                var relation = mapping.relationship; // nav relationship
                var childType = mapping.childType; // nav childType
                // check the type of relationship
                if (relation === "one-to-many") {
                    // one to many, we need to Entitize each object in the relation
                    var relationObjects = newEntity[navProp];
                    newEntity[navProp] = []; // we will be adding to jsObject[navProp]
                    for (var obj in relationObjects) {
                        var entitizeMe = relationObjects[obj];
                        var entitized = Entitize(entitizeMe, childType)
                        newEntity[navProp].push(entitized);
                    }
                } else if (relation === "one-to-one") {
                    // one to one relation, Entitize the object
                    var entitizeMe = newEntity[navProp];
                    var entitized = Entitize(entitizeMe, childType);
                    newEntity[navProp] = entitized;
                }
            }
        }

        // extend all of the properties in the jsObject, including the newly created
        // relation JEntity objects
        Entitize.extend(this, newEntity);

        // now done in Entitize...
        // set the proto to the base object as all other types
        //this.__proto__ = EntitizeNamespace.types[this.entityType];
    }

})();
<|endoftext|>


<commit_before>'use strict';

var chalk = require('chalk');
var gulp = require('gulp');
var path = require('path');
var rump = require('rump');
var pkg = require('../package');

gulp.task(rump.taskName('info:server'), function() {
  var destination = path.join(rump.configs.main.paths.destination.root,
                              rump.configs.main.paths.destination.static);

  console.log();
  console.log(chalk.magenta('--- Server', 'v' + pkg.version));
  console.log('Static files from', chalk.green(destination), 'are served',
              'on port', chalk.yellow(rump.configs.browserSync.port));
  console.log();
});

gulp.tasks[rump.taskName('info')].dep.push(rump.taskName('info:server'));
<commit_msg>simplify destination path<commit_after>'use strict';

var chalk = require('chalk');
var gulp = require('gulp');
var rump = require('rump');
var pkg = require('../package');

gulp.task(rump.taskName('info:server'), function() {
  var destination = rump.configs.main.paths.destination.root;

  console.log();
  console.log(chalk.magenta('--- Server', 'v' + pkg.version));
  console.log('Static files from', chalk.green(destination), 'are served',
              'on port', chalk.yellow(rump.configs.browserSync.port));
  console.log();
});

gulp.tasks[rump.taskName('info')].dep.push(rump.taskName('info:server'));
<|endoftext|>