<commit_before>window.onload = function animateJSON() {

    var animator = JSON.parse(localStorage.getItem('stringJSON'));
    var mainDiv = document.getElementById("outputJSON");

    const processDivClassName = "processes";
    const frameDivClassName = "frame"
    const frameTitleClassName = "frameTitle"
    const lifelines = "lifeLine";
    const activatorClassName = "activator"
    const arrowDivClassName = "arrowLtoR";
    const arrowDivClassName2 = "arrowRtoL"
    const messageDivClassName = "messages";

    for(var i = 0; i < animator.processes.length; i++) {

        var div = document.createElement("div");
        div.className = processDivClassName;
        div.innerHTML =
            animator.processes[i].name.toString() + ": " +
            animator.processes[i].class.toString();
        mainDiv.appendChild(div);

        var lifeLineDiv = document.createElement("div");
        lifeLineDiv.className = lifelines;
        lifeLineDiv.id = animator.processes[i].name.toString();
        var activatorDiv = document.createElement("div");
        activatorDiv.className = activatorClassName;
        div.appendChild(lifeLineDiv);
        lifeLineDiv.appendChild(activatorDiv);
    }

    var superArray = Object.keys(animator.diagram);
     //if (superArray.hasOwnProperty('node'))
    for (var i = 0; i < superArray.length; i++) {
        if (superArray[i] === 'node') {
            var frameDiv = document.createElement("div");
            frameDiv.className = frameDivClassName;
            frameDiv.id = animator.diagram.node.toString();
            var frameTitle = document.createElement("div");
            frameTitle.className = frameTitleClassName;
            frameTitle.id = animator.diagram.node.toString() + "Title";
            frameTitle.innerHTML = animator.diagram.node.toString();
            mainDiv.appendChild(frameDiv);
            frameDiv.appendChild(frameTitle);
        }
    }

    var a = 50;
    var counter = 0;

    for(var j = 0; j < animator.diagram.content.length; j++) {

        if(j != 0) {
            var lineBreak = document.createElement('hr');
          if (frameDiv != undefined) {
            //frameDiv.appendChild(lineBreak);
            }
        }

        for (var i = 0; i < animator.diagram.content[j].content.length; i++) {

        }
    }

createArrow(animator, 0, 0, 0, frameDiv, mainDiv);
createLog(animator, 0, 0, 0);

}

function createArrow(animator, j, i, counter, frameDiv,mainDiv){

     if(animator.diagram.content[j].content.length === i){
                i = 0;
                j++;

                var lineBreak = document.createElement('hr');
                if (frameDiv != undefined) {
                 frameDiv.appendChild(lineBreak);
                }
             }

const processDivClassName = "processes";
    const frameDivClassName = "frame"
    const frameTitleClassName = "frameTitle"
    const lifelines = "lifeLine";
    const activatorClassName = "activator"
    const arrowDivClassName = "arrowLtoR";
    const arrowDivClassName2 = "arrowRtoL"
    const messageDivClassName = "messages";

            var startPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].from.toString()));
            var endPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].to.toString()));

            var arrow = document.createElement("div");
            var svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
            var polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
            var message = document.createElement("div");
            message.className = messageDivClassName;
            svg.setAttribute("preserveAspectRatio", "xMaxYMid slice");

            svg.setAttribute("viewBox", "0 0 1400 14");
            // decides what direction the arrow will go, and makes the length of the arrows

            if (startPosition.x > endPosition.x) {
                arrow.className = arrowDivClassName2;
                var arrowLengthLeft = startPosition.x - endPosition.x;
                svg.setAttribute("width", arrowLengthLeft + "px");
                arrow.style.transform = "rotate(180deg)";
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthLeft / 2 + 'px';
                message.style.top = 40 + 'px';
                message.style.transform = "rotate(180deg)";
            }
            else {
                arrow.className = arrowDivClassName;
                var arrowLengthRight = endPosition.x - startPosition.x;
                svg.setAttribute("width", arrowLengthRight + "px");
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthRight / 2 + 'px';
            }

            svg.setAttribute("height", "14");
            polygon.setAttribute("points", "1400,7 1385,1 1390,6 0,6 0,8 1390,8 1385,13 1400,7");

            message.innerHTML =
                animator.diagram.content[j].content[i].message.toString();

            // making so every arrow is on their own line with 50px heigth difference
           // arrow.style.top = startPosition.y + counter * a - 20 + 'px';
            counter++;
            arrow.style.right = ((startPosition.x) - (startPosition.x - endPosition.x)) + 'px';

            // arrow.innerHTML =
            //     animator.diagram.content[0].content[i].message.toString();

            // arrow.style.position = "absolute";
            // arrow.style.left = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString() + 'px';
            // arrow.style.right = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().right.toString() + 'px';
            // arrow.style.top = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().top.toString() + 'px';
            // console.log(document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString());

            arrow.appendChild(message);
            svg.appendChild(polygon);
            arrow.appendChild(svg);
            if (frameDiv === undefined) {
                mainDiv.appendChild(arrow);
            }
            else {
                frameDiv.appendChild(arrow);
             }

            if(animator.diagram.content[j].content[i+1] === undefined && j+1 === animator.diagram.content.length){}

                else{

             setTimeout(function () {
            // Do Something Here
            // Then recall the parent function to
            // create a recursive loop.
            i++;

            createArrow(animator, j, i, counter, frameDiv, mainDiv);
            }, 1000);
         }
}

function createLog(animator, i, e, total){
var ul = document.getElementById("logList");
    if(animator.diagram.content[e].content.length === i){
    i = 0;
    e++;
}

            var li = document.createElement("li");
            li.setAttribute('id',((total+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            li.appendChild(document.createTextNode((total+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            ul.appendChild(li);

    if(animator.diagram.content.length > e){

    if(animator.diagram.content[e].content[i+1] === undefined && e+1 === animator.diagram.content.length){}

    else{

    setTimeout(function () {
        // Do Something Here
        // Then recall the parent function to
        // create a recursive loop.
        i++;
        total++;
        createLog(animator, i, e, total);
        }, 1000);
    }
     //setTimeout(createLog(animator), 1000);
   }

}

// var arrows = [];
//
// function Arrow(from, to, message) {
//     this.from = from;
//     this.to = to;
//     this.message = message;
// }
//
// function addArrow(from, to, message) {
//     var msg = new Arrow(from, to, message);
//     arrows.push(msg);
// }

// Helper function to get an element's exact position

function getPosition(el) {
    var xPos = 0;
    var yPos = 0;
    while (el) {
        if (el.tagName == "BODY") {
            // deal with browser quirks with body/window/document and page scroll
            var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
            var yScroll = el.scrollTop || document.documentElement.scrollTop;

            xPos += (el.offsetLeft - xScroll + el.clientLeft);
            yPos += (el.offsetTop - yScroll + el.clientTop);
        } else {
            // for all other non-BODY elements
            xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
            yPos += (el.offsetTop - el.scrollTop + el.clientTop);
        }

        el = el.offsetParent;
    }
    return {
        x: xPos,
        y: yPos
    };
}<commit_msg>Just increased the interval<commit_after>window.onload = function animateJSON() {

    var animator = JSON.parse(localStorage.getItem('stringJSON'));
    var mainDiv = document.getElementById("outputJSON");

    const processDivClassName = "processes";
    const frameDivClassName = "frame";
    const frameTitleClassName = "frameTitle";
    const lifelines = "lifeLine";
    const activatorClassName = "activator";
    const arrowDivClassName = "arrowLtoR";
    const arrowDivClassName2 = "arrowRtoL";
    const messageDivClassName = "messages";

    for(var i = 0; i < animator.processes.length; i++) {

        var div = document.createElement("div");
        div.className = processDivClassName;
        div.innerHTML =
            animator.processes[i].name.toString() + ": " +
            animator.processes[i].class.toString();
        mainDiv.appendChild(div);

        var lifeLineDiv = document.createElement("div");
        lifeLineDiv.className = lifelines;
        lifeLineDiv.id = animator.processes[i].name.toString();
        var activatorDiv = document.createElement("div");
        activatorDiv.className = activatorClassName;
        div.appendChild(lifeLineDiv);
        lifeLineDiv.appendChild(activatorDiv);
    }

    var superArray = Object.keys(animator.diagram);
     //if (superArray.hasOwnProperty('node'))
    for (var i = 0; i < superArray.length; i++) {
        if (superArray[i] === 'node') {
            var frameDiv = document.createElement("div");
            frameDiv.className = frameDivClassName;
            frameDiv.id = animator.diagram.node.toString();
            var frameTitle = document.createElement("div");
            frameTitle.className = frameTitleClassName;
            frameTitle.id = animator.diagram.node.toString() + "Title";
            frameTitle.innerHTML = animator.diagram.node.toString();
            mainDiv.appendChild(frameDiv);
            frameDiv.appendChild(frameTitle);
        }
    }

    var a = 50;
    var counter = 0;

    for(var j = 0; j < animator.diagram.content.length; j++) {

        if(j !== 0) {
            var lineBreak = document.createElement('hr');
          if (frameDiv !== undefined) {
            //frameDiv.appendChild(lineBreak);
            }
        }

        for (var i = 0; i < animator.diagram.content[j].content.length; i++) {

        }
    }

createArrow(animator, 0, 0, 0, frameDiv, mainDiv);
createLog(animator, 0, 0, 0);

};

function createArrow(animator, j, i, counter, frameDiv,mainDiv){

     if(animator.diagram.content[j].content.length === i){
                i = 0;
                j++;

                var lineBreak = document.createElement('hr');
                if (frameDiv != undefined) {
                 frameDiv.appendChild(lineBreak);
                }
             }

const processDivClassName = "processes";
    const frameDivClassName = "frame";
    const frameTitleClassName = "frameTitle";
    const lifelines = "lifeLine";
    const activatorClassName = "activator";
    const arrowDivClassName = "arrowLtoR";
    const arrowDivClassName2 = "arrowRtoL";
    const messageDivClassName = "messages";

            var startPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].from.toString()));
            var endPosition = getPosition(document.querySelector("#" + animator.diagram.content[j].content[i].to.toString()));

            var arrow = document.createElement("div");
            var svg = document.createElementNS('http://www.w3.org/2000/svg', "svg");
            var polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
            var message = document.createElement("div");
            message.className = messageDivClassName;
            svg.setAttribute("preserveAspectRatio", "xMaxYMid slice");

            svg.setAttribute("viewBox", "0 0 1400 14");
            // decides what direction the arrow will go, and makes the length of the arrows

            if (startPosition.x > endPosition.x) {
                arrow.className = arrowDivClassName2;
                var arrowLengthLeft = startPosition.x - endPosition.x;
                svg.setAttribute("width", arrowLengthLeft + "px");
                arrow.style.transform = "rotate(180deg)";
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthLeft / 2 + 'px';
                message.style.top = 40 + 'px';
                message.style.transform = "rotate(180deg)";
            }
            else {
                arrow.className = arrowDivClassName;
                var arrowLengthRight = endPosition.x - startPosition.x;
                svg.setAttribute("width", arrowLengthRight + "px");
                arrow.style.left = startPosition.x - 30 + 'px';
                message.style.left = arrowLengthRight / 2 + 'px';
            }

            svg.setAttribute("height", "14");
            polygon.setAttribute("points", "1400,7 1385,1 1390,6 0,6 0,8 1390,8 1385,13 1400,7");

            message.innerHTML =
                animator.diagram.content[j].content[i].message.toString();

            // making so every arrow is on their own line with 50px heigth difference
           // arrow.style.top = startPosition.y + counter * a - 20 + 'px';
            counter++;
            arrow.style.right = ((startPosition.x) - (startPosition.x - endPosition.x)) + 'px';

            // arrow.innerHTML =
            //     animator.diagram.content[0].content[i].message.toString();

            // arrow.style.position = "absolute";
            // arrow.style.left = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString() + 'px';
            // arrow.style.right = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().right.toString() + 'px';
            // arrow.style.top = document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().top.toString() + 'px';
            // console.log(document.getElementById(animator.diagram.content[0].content[i].from.toString()).getBoundingClientRect().left.toString());

            arrow.appendChild(message);
            svg.appendChild(polygon);
            arrow.appendChild(svg);
            if (frameDiv === undefined) {
                mainDiv.appendChild(arrow);
            }
            else {
                frameDiv.appendChild(arrow);
             }

            if(animator.diagram.content[j].content[i+1] === undefined && j+1 === animator.diagram.content.length){}

                else{

             setTimeout(function () {
            // Do Something Here
            // Then recall the parent function to
            // create a recursive loop.
            i++;

            createArrow(animator, j, i, counter, frameDiv, mainDiv);
            }, 1000);
         }
}

function createLog(animator, i, e, total){
var ul = document.getElementById("logList");
    if(animator.diagram.content[e].content.length === i){
    i = 0;
    e++;
}

            var li = document.createElement("li");
            li.setAttribute('id',((total+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            li.appendChild(document.createTextNode((total+1)+": Sending message From: " +
            animator.diagram.content[e].content[i].from.toString() +" To: "+
            animator.diagram.content[e].content[i].to.toString() +" || Message: "+
            animator.diagram.content[e].content[i].message.toString()));
            ul.appendChild(li);

    if(animator.diagram.content.length > e){

    if(animator.diagram.content[e].content[i+1] === undefined && e+1 === animator.diagram.content.length){}

    else{

    setTimeout(function () {
        // Do Something Here
        // Then recall the parent function to
        // create a recursive loop.
        i++;
        total++;
        createLog(animator, i, e, total);
        }, 1000);
    }
     //setTimeout(createLog(animator), 1000);
   }

}

// var arrows = [];
//
// function Arrow(from, to, message) {
//     this.from = from;
//     this.to = to;
//     this.message = message;
// }
//
// function addArrow(from, to, message) {
//     var msg = new Arrow(from, to, message);
//     arrows.push(msg);
// }

// Helper function to get an element's exact position

function getPosition(el) {
    var xPos = 0;
    var yPos = 0;
    while (el) {
        if (el.tagName == "BODY") {
            // deal with browser quirks with body/window/document and page scroll
            var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
            var yScroll = el.scrollTop || document.documentElement.scrollTop;

            xPos += (el.offsetLeft - xScroll + el.clientLeft);
            yPos += (el.offsetTop - yScroll + el.clientTop);
        } else {
            // for all other non-BODY elements
            xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
            yPos += (el.offsetTop - el.scrollTop + el.clientTop);
        }

        el = el.offsetParent;
    }
    return {
        x: xPos,
        y: yPos
    };
}<|endoftext|>


<commit_before>App.Directives.directive('previewMap', function($rootScope) {
	return {
		restrict: 'A',
		replace: true,
		scope: {dataset: '=previewMap'},
		template: '

',
		replace: true,
		link: function(scope, element, attrs) {

			// Any attribute that contains {{}} interpolation will be set to null in the attrs
			// parameter during the link function since the first $digest since the compilation
			// has yet to run to evaluate it! We can't run a $digest in the middle of compilation,
			// so using an $observe (or $watch) is the best way to get the values.
			attrs.$observe('id', function(newId) {
				//var map = L.map(scope.dataset.name, {
				var map = L.map(attrs.id, {
					zoom: 0,
					scrollWheelZoom: false,
					zoomControl: false,
					attributionControl: false,
				});

				//create a CloudMade tile layer and add it to the map
				L.tileLayer('http://{s}.tile.cloudmade.com/57cbb6ca8cac418dbb1a402586df4528/997/256/{z}/{x}/{y}.png', {}).addTo(map);

				// Zoom the map to the dataset bound regions (or at least try our best to do so)
				var datasetBounds = [[scope.dataset.latlonVals.latMax, scope.dataset.latlonVals.lonMin],
									 [scope.dataset.latlonVals.latMin, scope.dataset.latlonVals.lonMax]];
				map.fitBounds(datasetBounds, {});

				// Draw a colored overlay on the region of the map
				var maplatlon = scope.dataset.latlonVals;
				var bounds = [[maplatlon.latMax, maplatlon.lonMin], [maplatlon.latMin, maplatlon.lonMax]];

				var polygon = L.rectangle(bounds,{
					stroke: false,
					fillColor: $rootScope.fillColors[i],
					fillOpacity: 0.6
				});

				// Add layer to Group
				var rectangleGroup = L.layerGroup();
				rectangleGroup.addLayer(polygon);

				// Add the overlay to the map
				rectangleGroup.addTo(map);
			});
		}
	};
});
<commit_msg>CLIMATE-184 progress - Add ASF header to PreviewMap.js<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
**/

App.Directives.directive('previewMap', function($rootScope) {
	return {
		restrict: 'A',
		replace: true,
		scope: {dataset: '=previewMap'},
		template: '

',
		replace: true,
		link: function(scope, element, attrs) {

			// Any attribute that contains {{}} interpolation will be set to null in the attrs
			// parameter during the link function since the first $digest since the compilation
			// has yet to run to evaluate it! We can't run a $digest in the middle of compilation,
			// so using an $observe (or $watch) is the best way to get the values.
			attrs.$observe('id', function(newId) {
				//var map = L.map(scope.dataset.name, {
				var map = L.map(attrs.id, {
					zoom: 0,
					scrollWheelZoom: false,
					zoomControl: false,
					attributionControl: false,
				});

				//create a CloudMade tile layer and add it to the map
				L.tileLayer('http://{s}.tile.cloudmade.com/57cbb6ca8cac418dbb1a402586df4528/997/256/{z}/{x}/{y}.png', {}).addTo(map);

				// Zoom the map to the dataset bound regions (or at least try our best to do so)
				var datasetBounds = [[scope.dataset.latlonVals.latMax, scope.dataset.latlonVals.lonMin],
									 [scope.dataset.latlonVals.latMin, scope.dataset.latlonVals.lonMax]];
				map.fitBounds(datasetBounds, {});

				// Draw a colored overlay on the region of the map
				var maplatlon = scope.dataset.latlonVals;
				var bounds = [[maplatlon.latMax, maplatlon.lonMin], [maplatlon.latMin, maplatlon.lonMax]];

				var polygon = L.rectangle(bounds,{
					stroke: false,
					fillColor: $rootScope.fillColors[i],
					fillOpacity: 0.6
				});

				// Add layer to Group
				var rectangleGroup = L.layerGroup();
				rectangleGroup.addLayer(polygon);

				// Add the overlay to the map
				rectangleGroup.addTo(map);
			});
		}
	};
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 *
 * This is a controlled component version of RCTDatePickerIOS
 *
 * @format
 * @flow
 */

'use strict';

const NativeMethodsMixin = require('NativeMethodsMixin');
const React = require('React');
const invariant = require('fbjs/lib/invariant');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const View = require('View');
const ViewPropTypes = require('ViewPropTypes');

const createReactClass = require('create-react-class');
const requireNativeComponent = require('requireNativeComponent');

import type {ViewProps} from 'ViewPropTypes';
type DefaultProps = {
  mode: 'date' | 'time' | 'datetime',
};

type Event = Object;

type Props = $ReadOnly<{|
  ...ViewProps,
  date?: ?Date,
  initialDate?: ?Date,
  locale?: ?string,
  maximumDate?: ?Date,
  minimumDate?: ?Date,
  minuteInterval?: ?(1 | 2 | 3 | 4 | 5 | 6 | 10 | 12 | 15 | 20 | 30),
  mode?: ?('date' | 'time' | 'datetime'),
  onChange?: ?(event: Event) => void,
  onDateChange: (date: Date) => void,
  timeZoneOffsetInMinutes?: ?number,
|}>;

/**
 * Use `DatePickerIOS` to render a date/time picker (selector) on iOS.  This is
 * a controlled component, so you must hook in to the `onDateChange` callback
 * and update the `date` prop in order for the component to update, otherwise
 * the user's change will be reverted immediately to reflect `props.date` as the
 * source of truth.
 */
const DatePickerIOS = ((createReactClass({
  displayName: 'DatePickerIOS',
  // TOOD: Put a better type for _picker
  _picker: (undefined: ?$FlowFixMe),

  mixins: [NativeMethodsMixin],

  propTypes: {
    ...ViewPropTypes,
    /**
     * The currently selected date.
     */
    date: PropTypes.instanceOf(Date),

    /**
     * Provides an initial value that will change when the user starts selecting
     * a date. It is useful for simple use-cases where you do not want to deal
     * with listening to events and updating the date prop to keep the
     * controlled state in sync. The controlled state has known bugs which
     * causes it to go out of sync with native. The initialDate prop is intended
     * to allow you to have native be source of truth.
     */
    initialDate: PropTypes.instanceOf(Date),

    /**
     * Date change handler.
     *
     * This is called when the user changes the date or time in the UI.
     * The first and only argument is an Event. For getting the date the picker
     * was changed to, use onDateChange instead.
     */
    onChange: PropTypes.func,

    /**
     * Date change handler.
     *
     * This is called when the user changes the date or time in the UI.
     * The first and only argument is a Date object representing the new
     * date and time.
     */
    onDateChange: PropTypes.func.isRequired,

    /**
     * Maximum date.
     *
     * Restricts the range of possible date/time values.
     */
    maximumDate: PropTypes.instanceOf(Date),

    /**
     * Minimum date.
     *
     * Restricts the range of possible date/time values.
     */
    minimumDate: PropTypes.instanceOf(Date),

    /**
     * The date picker mode.
     */
    mode: PropTypes.oneOf(['date', 'time', 'datetime']),

    /**
     * The date picker locale.
     */
    locale: PropTypes.string,

    /**
     * The interval at which minutes can be selected.
     */
    minuteInterval: PropTypes.oneOf([1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30]),

    /**
     * Timezone offset in minutes.
     *
     * By default, the date picker will use the device's timezone. With this
     * parameter, it is possible to force a certain timezone offset. For
     * instance, to show times in Pacific Standard Time, pass -7 * 60.
     */
    timeZoneOffsetInMinutes: PropTypes.number,
  },

  getDefaultProps: function(): DefaultProps {
    return {
      mode: 'datetime',
    };
  },

  componentDidUpdate: function() {
    if (this.props.date) {
      const propsTimeStamp = this.props.date.getTime();
      if (this._picker) {
        this._picker.setNativeProps({
          date: propsTimeStamp,
        });
      }
    }
  },

  _onChange: function(event: Event) {
    const nativeTimeStamp = event.nativeEvent.timestamp;
    this.props.onDateChange &&
      this.props.onDateChange(new Date(nativeTimeStamp));
    this.props.onChange && this.props.onChange(event);
  },

  render: function() {
    const props = this.props;
    invariant(
      props.date || props.initialDate,
      'A selected date or initial date should be specified.',
    );
    return (
      <View style={props.style}>
        <RCTDatePickerIOS
          ref={picker => {
            this._picker = picker;
          }}
          style={styles.datePickerIOS}
          date={
            props.date
              ? props.date.getTime()
              : props.initialDate
                ? props.initialDate.getTime()
                : undefined
          }
          locale={props.locale ? props.locale : undefined}
          maximumDate={
            props.maximumDate ? props.maximumDate.getTime() : undefined
          }
          minimumDate={
            props.minimumDate ? props.minimumDate.getTime() : undefined
          }
          mode={props.mode}
          minuteInterval={props.minuteInterval}
          timeZoneOffsetInMinutes={props.timeZoneOffsetInMinutes}
          onChange={this._onChange}
          onStartShouldSetResponder={() => true}
          onResponderTerminationRequest={() => false}
        />
      </View>
    );
  },
}): any): React.ComponentType<Props>);

const styles = StyleSheet.create({
  datePickerIOS: {
    height: 216,
  },
});

const RCTDatePickerIOS = requireNativeComponent('RCTDatePicker');

module.exports = DatePickerIOS;
<commit_msg>DatePickerIOS ES6 Class<commit_after>/**
 * Copyright (c) 2015-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 *
 * This is a controlled component version of RCTDatePickerIOS
 *
 * @format
 * @flow
 */

'use strict';

const React = require('React');
const invariant = require('fbjs/lib/invariant');
const StyleSheet = require('StyleSheet');
const View = require('View');

const requireNativeComponent = require('requireNativeComponent');

import type {ViewProps} from 'ViewPropTypes';

type Event = Object;

type Props = $ReadOnly<{|
  ...ViewProps,

  /**
   * The currently selected date.
   */
  date?: ?Date,

  /**
   * Provides an initial value that will change when the user starts selecting
   * a date. It is useful for simple use-cases where you do not want to deal
   * with listening to events and updating the date prop to keep the
   * controlled state in sync. The controlled state has known bugs which
   * causes it to go out of sync with native. The initialDate prop is intended
   * to allow you to have native be source of truth.
   */
  initialDate?: ?Date,

  /**
   * The date picker locale.
   */
  locale?: ?string,

  /**
   * Maximum date.
   *
   * Restricts the range of possible date/time values.
   */
  maximumDate?: ?Date,

  /**
   * Minimum date.
   *
   * Restricts the range of possible date/time values.
   */
  minimumDate?: ?Date,

  /**
   * The interval at which minutes can be selected.
   */
  minuteInterval?: ?(1 | 2 | 3 | 4 | 5 | 6 | 10 | 12 | 15 | 20 | 30),

  /**
   * The date picker mode.
   */
  mode?: ?('date' | 'time' | 'datetime'),

  /**
   * Date change handler.
   *
   * This is called when the user changes the date or time in the UI.
   * The first and only argument is an Event. For getting the date the picker
   * was changed to, use onDateChange instead.
   */
  onChange?: ?(event: Event) => void,

  /**
   * Date change handler.
   *
   * This is called when the user changes the date or time in the UI.
   * The first and only argument is a Date object representing the new
   * date and time.
   */
  onDateChange: (date: Date) => void,

  /**
   * Timezone offset in minutes.
   *
   * By default, the date picker will use the device's timezone. With this
   * parameter, it is possible to force a certain timezone offset. For
   * instance, to show times in Pacific Standard Time, pass -7 * 60.
   */
  timeZoneOffsetInMinutes?: ?number,
|}>;

/**
 * Use `DatePickerIOS` to render a date/time picker (selector) on iOS.  This is
 * a controlled component, so you must hook in to the `onDateChange` callback
 * and update the `date` prop in order for the component to update, otherwise
 * the user's change will be reverted immediately to reflect `props.date` as the
 * source of truth.
 */
class DatePickerIOS extends React.Component<Props> {
  static DefaultProps = {
    mode: 'datetime',
  };

  // $FlowFixMe How to type a native component to be able to call setNativeProps
  _picker: ?React.ElementRef<typeof RCTDatePickerIOS> = null;

  componentDidUpdate() {
    if (this.props.date) {
      const propsTimeStamp = this.props.date.getTime();
      if (this._picker) {
        this._picker.setNativeProps({
          date: propsTimeStamp,
        });
      }
    }
  }

  _onChange = (event: Event) => {
    const nativeTimeStamp = event.nativeEvent.timestamp;
    this.props.onDateChange &&
      this.props.onDateChange(new Date(nativeTimeStamp));
    this.props.onChange && this.props.onChange(event);
  };

  render() {
    const props = this.props;
    invariant(
      props.date || props.initialDate,
      'A selected date or initial date should be specified.',
    );
    return (
      <View style={props.style}>
        <RCTDatePickerIOS
          ref={picker => {
            this._picker = picker;
          }}
          style={styles.datePickerIOS}
          date={
            props.date
              ? props.date.getTime()
              : props.initialDate
                ? props.initialDate.getTime()
                : undefined
          }
          locale={props.locale ? props.locale : undefined}
          maximumDate={
            props.maximumDate ? props.maximumDate.getTime() : undefined
          }
          minimumDate={
            props.minimumDate ? props.minimumDate.getTime() : undefined
          }
          mode={props.mode}
          minuteInterval={props.minuteInterval}
          timeZoneOffsetInMinutes={props.timeZoneOffsetInMinutes}
          onChange={this._onChange}
          onStartShouldSetResponder={() => true}
          onResponderTerminationRequest={() => false}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  datePickerIOS: {
    height: 216,
  },
});

const RCTDatePickerIOS = requireNativeComponent('RCTDatePicker');

module.exports = DatePickerIOS;
<|endoftext|>


<commit_before>/*
 * @author     Martin Høgh <mh@mapcentia.com>
 * @copyright  2013-2019 MapCentia ApS
 * @license    http://www.gnu.org/licenses/#AGPL  GNU AFFERO GENERAL PUBLIC LICENSE 3
 */

'use strict';

let urlparser = require('./urlparser');
let db = urlparser.db;
let schema = urlparser.schema;
let cloud, layers, setBaseLayer;
let _self = false;
let initMapParameters;
let utils;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init, getAnchor: module.exports.getAnchor}}
 */
module.exports = {
    set: function (o) {
        cloud = o.cloud;
        layers = o.layers;
        setBaseLayer = o.setBaseLayer;
        utils = o.utils;
        return this;
    },
    init: function () {
        _self = this;

        var param = [], paramStr, parr;

        $.each(this.urlVars(), function (i, v) {
            parr = v.split("#");
            if (parr.length > 1) {
                parr.pop();
            }
            param.push(i + "=" + parr.join());
        });
        var sr = urlparser.staticRoute !== "" && urlparser.staticRoute !== undefined  ? urlparser.staticRoute : null;
        paramStr = param.join("&");
        return "/app/" + db + "/" + (schema !== "" ? schema + "/" : "") + (sr ? sr + "/" : "") + ((paramStr === "") ? "" : "?" + paramStr) + this.anchor();
    },

    urlVars: function getUrlVars() {
        var mapvars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
            mapvars[key] = value;
        });
        return mapvars;
    },

    /**
     * Returns current map parameters, if the map have not been
     * initialized yet, then the "false" is returned
     *
     * @returns {Object|Boolean}
     */
    getCurrentMapParameters: () => {
        let p = geocloud.transformPoint(cloud.get().getCenter().x, cloud.get().getCenter().y, "EPSG:3857", "EPSG:4326");
        let result = false;
        if (cloud.get().getBaseLayerName()) {
            result = {
                layers: (layers.getLayers() ? layers.getLayers().split(",") : []),
                baseLayer: cloud.get().getBaseLayerName(),
                zoom: Math.round(cloud.get().getZoom()).toString(),
                x: (Math.round(p.x * 10000) / 10000).toString(),
                y: (Math.round(p.y * 10000) / 10000).toString()
            };
        }

        return result;
    },

    applyMapParameters: (parameters, ignoreInitZoomCenter) => {
        const arr = window.vidiConfig?.initZoomCenter ? utils.parseZoomCenter(window.vidiConfig.initZoomCenter) : null;
        if (arr && !ignoreInitZoomCenter) {
            parameters.zoom = arr.z;
            parameters.x = arr.x;
            parameters.y = arr.y;
        }
        let result = new Promise((resolve, reject) => {
            if (parameters.x && parameters.y && parameters.zoom) {
                cloud.get().setView(new L.LatLng(parseFloat(parameters.y), parseFloat(parameters.x)), parameters.zoom);
                initMapParameters = parameters
            } else {
                initMapParameters = null;
            }

            setBaseLayer.init(parameters.baseLayer).then(() => {
                resolve();
            }).catch(error => {
                console.error(error);
                reject();
            });
        });
        return result;
    },

    getInitMapParameters: () => {
        return initMapParameters;
    },

    /**
     * @private
     * @returns {string|boolean}
     */
    anchor: (scheme) => {
        let mapParameters = _self.getCurrentMapParameters();
        if (mapParameters) {
            var layerStr;
            if (layers.getLayers() && scheme) {
                let newArr = [];
                let arr = mapParameters.layers;
                $.each(arr, function (i, v) {
                    newArr.push(scheme + "." + v.split(".")[1])
                });
                layerStr = newArr.reverse().join(",");
            } else {
                layerStr = (mapParameters.layers) ? mapParameters.layers.reverse().join(",") : ""
            }

            return `#${mapParameters.baseLayer}/${mapParameters.zoom}/${mapParameters.x}/${mapParameters.y}/${layerStr}`;
        } else {
            return ``;
        }
    },

    /**
     * Get the URL anchor for current state
     * @returns {string}
     */
    getUri: function (s) {
        schema = s || schema;
        return "/app/" + db + "/" + (schema !== "" ? schema + "/" : "");
    },

    getParam: function () {
        var param = [], paramStr, parr;
        $.each(this.urlVars(), function (i, v) {
            parr = v.split("#");
            if (parr.length > 1) {
                parr.pop();
            }
            param.push(i + "=" + parr.join());
        });
        paramStr = param.join("&");
        return paramStr;
    },

    /**
     * Get the URL anchor for current state
     * @returns {string}
     */
    getAnchor: function (s) {
        return _self.anchor(s);
    }
};
<commit_msg>Inline var<commit_after>/*
 * @author     Martin Høgh <mh@mapcentia.com>
 * @copyright  2013-2019 MapCentia ApS
 * @license    http://www.gnu.org/licenses/#AGPL  GNU AFFERO GENERAL PUBLIC LICENSE 3
 */

'use strict';

let urlparser = require('./urlparser');
let db = urlparser.db;
let schema = urlparser.schema;
let cloud, layers, setBaseLayer;
let _self = false;
let initMapParameters;
let utils;

/**
 *
 * @type {{set: module.exports.set, init: module.exports.init, getAnchor: module.exports.getAnchor}}
 */
module.exports = {
    set: function (o) {
        cloud = o.cloud;
        layers = o.layers;
        setBaseLayer = o.setBaseLayer;
        utils = o.utils;
        return this;
    },
    init: function () {
        _self = this;

        var param = [], paramStr, parr;

        $.each(this.urlVars(), function (i, v) {
            parr = v.split("#");
            if (parr.length > 1) {
                parr.pop();
            }
            param.push(i + "=" + parr.join());
        });
        var sr = urlparser.staticRoute !== "" && urlparser.staticRoute !== undefined  ? urlparser.staticRoute : null;
        paramStr = param.join("&");
        return "/app/" + db + "/" + (schema !== "" ? schema + "/" : "") + (sr ? sr + "/" : "") + ((paramStr === "") ? "" : "?" + paramStr) + this.anchor();
    },

    urlVars: function getUrlVars() {
        var mapvars = {};
        var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
            mapvars[key] = value;
        });
        return mapvars;
    },

    /**
     * Returns current map parameters, if the map have not been
     * initialized yet, then the "false" is returned
     *
     * @returns {Object|Boolean}
     */
    getCurrentMapParameters: () => {
        let p = geocloud.transformPoint(cloud.get().getCenter().x, cloud.get().getCenter().y, "EPSG:3857", "EPSG:4326");
        let result = false;
        if (cloud.get().getBaseLayerName()) {
            result = {
                layers: (layers.getLayers() ? layers.getLayers().split(",") : []),
                baseLayer: cloud.get().getBaseLayerName(),
                zoom: Math.round(cloud.get().getZoom()).toString(),
                x: (Math.round(p.x * 10000) / 10000).toString(),
                y: (Math.round(p.y * 10000) / 10000).toString()
            };
        }

        return result;
    },

    applyMapParameters: (parameters, ignoreInitZoomCenter) => {
        const arr = window.vidiConfig?.initZoomCenter ? utils.parseZoomCenter(window.vidiConfig.initZoomCenter) : null;
        if (arr && !ignoreInitZoomCenter) {
            parameters.zoom = arr.z;
            parameters.x = arr.x;
            parameters.y = arr.y;
        }
        return new Promise((resolve, reject) => {
            if (parameters.x && parameters.y && parameters.zoom) {
                cloud.get().setView(new L.LatLng(parseFloat(parameters.y), parseFloat(parameters.x)), parameters.zoom);
                initMapParameters = parameters
            } else {
                initMapParameters = null;
            }

            setBaseLayer.init(parameters.baseLayer).then(() => {
                resolve();
            }).catch(error => {
                console.error(error);
                reject();
            });
        });
    },

    getInitMapParameters: () => {
        return initMapParameters;
    },

    /**
     * @private
     * @returns {string|boolean}
     */
    anchor: (scheme) => {
        let mapParameters = _self.getCurrentMapParameters();
        if (mapParameters) {
            var layerStr;
            if (layers.getLayers() && scheme) {
                let newArr = [];
                let arr = mapParameters.layers;
                $.each(arr, function (i, v) {
                    newArr.push(scheme + "." + v.split(".")[1])
                });
                layerStr = newArr.reverse().join(",");
            } else {
                layerStr = (mapParameters.layers) ? mapParameters.layers.reverse().join(",") : ""
            }

            return `#${mapParameters.baseLayer}/${mapParameters.zoom}/${mapParameters.x}/${mapParameters.y}/${layerStr}`;
        } else {
            return ``;
        }
    },

    /**
     * Get the URL anchor for current state
     * @returns {string}
     */
    getUri: function (s) {
        schema = s || schema;
        return "/app/" + db + "/" + (schema !== "" ? schema + "/" : "");
    },

    getParam: function () {
        var param = [], paramStr, parr;
        $.each(this.urlVars(), function (i, v) {
            parr = v.split("#");
            if (parr.length > 1) {
                parr.pop();
            }
            param.push(i + "=" + parr.join());
        });
        paramStr = param.join("&");
        return paramStr;
    },

    /**
     * Get the URL anchor for current state
     * @returns {string}
     */
    getAnchor: function (s) {
        return _self.anchor(s);
    }
};
<|endoftext|>


<commit_before>import gravity from '../../lib/loaders/gravity';
import { keys, map, sortBy, first, filter } from 'lodash';
import Artwork from '../artwork/index';
import {
  GraphQLList,
  GraphQLObjectType,
  GraphQLString,
  GraphQLBoolean,
  GraphQLInt,
} from 'graphql';

const RESULTS_SIZE = 15;

const featuredFair = () => {
  return gravity('fairs', { size: 5, status: 'running' }).then((fairs) => {
    if(fairs){
      return first(sortBy(fairs, ({ banner_size }) =>
        ['x-large', 'large', 'medium', 'small', 'x-small'].indexOf(banner_size)
      ));
    }
  });
}

const featuredAuction = () => {
  return gravity('sales', { live: true, size: 1 }).then((sales) => {
    if(sales){
      return first(sales);
    }
  });
}

const moduleTitle = {
  active_bids: () => "Your Active Bids",
  followed_artists: () => "Works by Artists you Follow",
  followed_galleries: () => "Works from Galleries you Follow",
  saved_works: () => "Recently Saved Works",
  recommended_works: () => "Recommended Works for You",
  live_auctions: () => {
    return featuredAuction().then(({name}) => {
      return `At auction: ${name}`;
    })
  },
  current_fairs: () =>  {
    return featuredFair().then(({name}) => {
      return `Art Fair: ${name}`;
    })
  },
  related_artists: () => "Works by Related Artists",
  genes: () => "Works from Gene you Follow",
}

const moduleResults = {
  active_bids: (accessToken) => [],
  followed_artists: (accessToken) => {
    return gravity.with(accessToken)('me/follow/artists/artworks', { for_sale: true, size: RESULTS_SIZE });
  },
  followed_galleries: (accessToken) => {
    return gravity.with(accessToken)('me/follow/profiles/artworks', { for_sale: true, size: RESULTS_SIZE });
  },
  saved_works: (accessToken) => {
    return gravity.with(accessToken)('me').then((user) => {
      return gravity.with(accessToken)('collection/saved-artwork/artworks', { size: RESULTS_SIZE, user_id: user.id });
    }).catch(() => {});
  },
  recommended_works: (accessToken) => {
    return gravity.with(accessToken)('me/suggested/artworks/homepage', { limit: RESULTS_SIZE });
  },
  live_auctions: () => {
    return featuredAuction().then(({id}) => {
      return gravity(`sale/${id}/sale_artworks`, { size: RESULTS_SIZE });
    })
  },
  current_fairs: () =>  {
    return featuredFair().then(({id}) => {
      return gravity('filter/artworks', {
        fair_id: id,
        for_sale: true,
        size: RESULTS_SIZE
      }).then(({ hits }) => hits);
    })
  },
  related_artists: () => [],
  genes: () => [],
}

export const HomePageModulesType = new GraphQLObjectType({
  name: 'HomePageModules',
  fields: () => ({
    key: {
      type: GraphQLString,
    },
    display: {
      type: GraphQLString,
    },
    title: {
      type: GraphQLString,
      resolve: ({ key, display }, options, { rootValue: { accessToken } }) => {
        if(display) return moduleTitle[key](accessToken);
      },
    },
    results: {
      type: new GraphQLList(Artwork.type),
      resolve: ({ key, display }, options, { rootValue: { accessToken } }) => {
        if(display) return moduleResults[key](accessToken);
      },
    },
  })
});

const HomePageModules = {
  type: new GraphQLList(HomePageModulesType),
  description: 'Modules to show on the home screen',
  resolve: (root, options, { rootValue: { accessToken } }) => {
    return gravity.with(accessToken)('me/modules').then((response) => {
      const modules = map(keys(response), (key) => {
        return { key: key, display: response[key] };
      });
      return filter(modules, [ 'display', true ]);
    })
  },
};

export default HomePageModules;
<commit_msg>adds include_keys arg<commit_after>import gravity from '../../lib/loaders/gravity';
import {
  keys,
  map,
  sortBy,
  first,
  filter
} from 'lodash';
import Artwork from '../artwork/index';
import {
  GraphQLList,
  GraphQLObjectType,
  GraphQLString,
  GraphQLBoolean,
  GraphQLInt,
} from 'graphql';

const RESULTS_SIZE = 15;

const featuredFair = () => {
  return gravity('fairs', { size: 5, status: 'running' }).then((fairs) => {
    if(fairs){
      return first(sortBy(fairs, ({ banner_size }) =>
        ['x-large', 'large', 'medium', 'small', 'x-small'].indexOf(banner_size)
      ));
    }
  });
}

const featuredAuction = () => {
  return gravity('sales', { live: true, size: 1 }).then((sales) => {
    if(sales){
      return first(sales);
    }
  });
}

const moduleTitle = {
  active_bids: () => "Your Active Bids",
  followed_artists: () => "Works by Artists you Follow",
  followed_galleries: () => "Works from Galleries you Follow",
  saved_works: () => "Recently Saved Works",
  recommended_works: () => "Recommended Works for You",
  live_auctions: () => {
    return featuredAuction().then(({name}) => {
      return `At auction: ${name}`;
    })
  },
  current_fairs: () =>  {
    return featuredFair().then(({name}) => {
      return `Art Fair: ${name}`;
    })
  },
  related_artists: () => "Works by Related Artists",
  genes: () => "Works from Gene you Follow",
}

const moduleResults = {
  active_bids: (accessToken) => [],
  followed_artists: (accessToken) => {
    return gravity.with(accessToken)('me/follow/artists/artworks', { for_sale: true, size: RESULTS_SIZE });
  },
  followed_galleries: (accessToken) => {
    return gravity.with(accessToken)('me/follow/profiles/artworks', { for_sale: true, size: RESULTS_SIZE });
  },
  saved_works: (accessToken) => {
    return gravity.with(accessToken)('me').then((user) => {
      return gravity.with(accessToken)('collection/saved-artwork/artworks', { size: RESULTS_SIZE, user_id: user.id });
    }).catch(() => {});
  },
  recommended_works: (accessToken) => {
    return gravity.with(accessToken)('me/suggested/artworks/homepage', { limit: RESULTS_SIZE });
  },
  live_auctions: () => {
    return featuredAuction().then(({id}) => {
      return gravity(`sale/${id}/sale_artworks`, { size: RESULTS_SIZE });
    })
  },
  current_fairs: () =>  {
    return featuredFair().then(({id}) => {
      return gravity('filter/artworks', {
        fair_id: id,
        for_sale: true,
        size: RESULTS_SIZE
      }).then(({ hits }) => hits);
    })
  },
  related_artists: () => [],
  genes: () => [],
}

export const HomePageModulesType = new GraphQLObjectType({
  name: 'HomePageModules',
  fields: () => ({
    key: {
      type: GraphQLString,
    },
    display: {
      type: GraphQLString,
    },
    title: {
      type: GraphQLString,
      resolve: ({ key, display }, options, { rootValue: { accessToken } }) => {
        if(display) return moduleTitle[key](accessToken);
      },
    },
    results: {
      type: new GraphQLList(Artwork.type),
      resolve: ({ key, display }, options, { rootValue: { accessToken } }) => {
        if(display) return moduleResults[key](accessToken);
      },
    },
  })
});

const HomePageModules = {
  type: new GraphQLList(HomePageModulesType),
  description: 'Modules to show on the home screen',
  args: {
    include_keys: {
      type: new GraphQLList(GraphQLString),
      description: 'A list of modules to return (by key)',
      defaultValue: false,
    },
  },
  resolve: (root, { include_keys }, { rootValue: { accessToken } }) => {
    return gravity.with(accessToken)('me/modules').then((response) => {
      const modules = map(keys(response), (key) => {
        return { key: key, display: response[key] };
      });
      if(include_keys){
        return filter(modules, (module) => {
          return include_keys.indexOf(module.key) > -1;
        });
      }else{
        return filter(modules, [ 'display', true ]);
      }
    })
  },
};

export default HomePageModules;
<|endoftext|>


<commit_before>function removeUserFromRole()
{
	$(this).closest('form').submit();
}<commit_msg>Role: remove unneeded JS<commit_after><|endoftext|>


<commit_before>/*******************************************************************************************************
 * File: about.js
 * Project: hootenanny-ui
 * @author Matt Putipong - matt.putipong@radiantsolutions.com on 7/11/18
 *******************************************************************************************************/

import API           from '../managers/api';
import HootOSM       from '../managers/hootOsm';
import { aboutForm } from '../config/formMetadata';
import FormFactory   from '../tools/formFactory';

export default class About {
    constructor() {
        this.form = aboutForm.call( this );

        this.appInfo = HootOSM.appInfo;
    }

    render() {
        this.formData = aboutForm.call( this );

        let metadata = {
            title: 'About Hootenanny',
            form: this.formData,
            button: {
                text: 'Download User Guide',
                id: 'downloadUserGuideBtn',
                onClick: () => this.handleSubmit()
            }
        };

        new FormFactory().generateForm( 'body', 'about-hootenanny', metadata );

        d3.select( '#downloadUserGuideBtn' ).property( 'disabled', false );
    }

    createTableFieldset( field ) {
        let table = field
            .selectAll( '.about-item' )
            .append( 'div' )
            .data( this.appInfo );

        let rows = table
            .enter()
            .append( 'div' )
            .classed( 'about-item fill-white keyline-bottom', true );

        rows
            .append( 'span' )
            .text( d => {
                let builtBy = d.buildBy || d.user;

                return `${ d.name } - Version: ${ d.version } - Built By: ${ builtBy }`;
            } );
    }

    handleSubmit() {
        let sUrl = `${ API.baseUrl }/info/document/export`,
            link = document.createElement( 'a' );

        link.href = sUrl;

        if ( link.download !== undefined ) {
            //Set HTML5 download attribute. This will prevent file from opening if supported.
            link.download = sUrl.substring( sUrl.lastIndexOf( '/' ) + 1, sUrl.length );
        }

        // dispatch click event
        if ( document.createEvent ) {
            let e = document.createEvent( 'MouseEvents' );
            e.initEvent( 'click', true, true );
            link.dispatchEvent( e );
            return true;
        }
    }
}<commit_msg>fix "Built by" field in about modal<commit_after>/*******************************************************************************************************
 * File: about.js
 * Project: hootenanny-ui
 * @author Matt Putipong - matt.putipong@radiantsolutions.com on 7/11/18
 *******************************************************************************************************/

import API           from '../managers/api';
import HootOSM       from '../managers/hootOsm';
import { aboutForm } from '../config/formMetadata';
import FormFactory   from '../tools/formFactory';

export default class About {
    constructor() {
        this.form = aboutForm.call( this );

        this.appInfo = HootOSM.appInfo;
    }

    render() {
        this.formData = aboutForm.call( this );

        let metadata = {
            title: 'About Hootenanny',
            form: this.formData,
            button: {
                text: 'Download User Guide',
                id: 'downloadUserGuideBtn',
                onClick: () => this.handleSubmit()
            }
        };

        new FormFactory().generateForm( 'body', 'about-hootenanny', metadata );

        d3.select( '#downloadUserGuideBtn' ).property( 'disabled', false );
    }

    createTableFieldset( field ) {
        let table = field
            .selectAll( '.about-item' )
            .append( 'div' )
            .data( this.appInfo );

        let rows = table
            .enter()
            .append( 'div' )
            .classed( 'about-item fill-white keyline-bottom', true );

        rows
            .append( 'span' )
            .text( d => {
                let builtBy = d.builtBy || d.user;

                return `${ d.name } - Version: ${ d.version } - Built By: ${ builtBy }`;
            } );
    }

    handleSubmit() {
        let sUrl = `${ API.baseUrl }/info/document/export`,
            link = document.createElement( 'a' );

        link.href = sUrl;

        if ( link.download !== undefined ) {
            //Set HTML5 download attribute. This will prevent file from opening if supported.
            link.download = sUrl.substring( sUrl.lastIndexOf( '/' ) + 1, sUrl.length );
        }

        // dispatch click event
        if ( document.createEvent ) {
            let e = document.createEvent( 'MouseEvents' );
            e.initEvent( 'click', true, true );
            link.dispatchEvent( e );
            return true;
        }
    }
}<|endoftext|>


<commit_before>var express = require('express') //carregando módulo do express para manipulação das views
  , app = express() //instanciando express na vairável app
  , server = require('http').createServer(app) //instanciando servidor HTTP na variável server
  , io = require('socket.io').listen(server); //carregando módulo socket.io e escutando as requisições do servidor HTTP

var url = require('url'); //carregando módulo para manipulação da url (parse de query string)
var crypto = require('crypto'); //carregando módulo ce criptografia para geração de hash

console.log("IO configurado"); //saída no console que o sockei.io está configurado corretamente

// Configurações de renderização do express
app.set('view engine', 'ejs'); //utilizando motor de renderização ejs
app.set('views', __dirname + '/views'); //definindo caminho das views
app.engine('html', require('ejs').renderFile); //definindo renderização de arquivos html

app.use("/assets", express.static(__dirname + '/assets')); //definindo caminho dos arquivos estáticos

//escutando requisições na raíz da aplicação
app.get("/", function(req, res) {

    //conexões ilimitadas
    req.setMaxListeners(0);

    //renderizando a página inicial
    res.render("index.html", {
        title: "Pagina browser" //passando variável para a view
    });
});

server.listen(5502, function(){
    console.log("Express e Socket.IO no ar.");
});

//todas as funções após a conexão do socket.io
io.sockets.on('connection', function (socket)
{
    //emitindo sinal após conexão
    socket.emit('conexao', { status: 'online', conexaoId: socket.id });

    //recebendo ação do clique
    socket.on('recebendo click', function(data){
        //aqui vai o código a ser processado quando o servidor receber este evento
    });
});
<commit_msg>-Adicionados comentários explicativos dos comandos<commit_after>var express = require('express') //carregando módulo do express para manipulação das views
  , app = express() //instanciando express na vairável app
  , server = require('http').createServer(app) //instanciando servidor HTTP na variável server
  , io = require('socket.io').listen(server); //carregando módulo socket.io e escutando as requisições do servidor HTTP

var url = require('url'); //carregando módulo para manipulação da url (parse de query string)
var crypto = require('crypto'); //carregando módulo ce criptografia para geração de hash

console.log("IO configurado"); //saída no console que o sockei.io está configurado corretamente

// Configurações de renderização do express
app.set('view engine', 'ejs'); //utilizando motor de renderização ejs
app.set('views', __dirname + '/views'); //definindo caminho das views
app.engine('html', require('ejs').renderFile); //definindo renderização de arquivos html

app.use("/assets", express.static(__dirname + '/assets')); //definindo caminho dos arquivos estáticos

//escutando requisições na raíz da aplicação
app.get("/", function(req, res) {

    //conexões ilimitadas
    req.setMaxListeners(0);

    //renderizando a página inicial
    res.render("index.html", {
        title: "Pagina browser" //passando variável para a view
    });
});

//servidor HTTP "escutando" porta 5502
server.listen(5502, function(){
    console.log("Express e Socket.IO no ar.");
});

//todas as funções após a conexão do socket.io
io.sockets.on('connection', function (socket)
{
    //emitindo sinal após conexão
    socket.emit('conexao', { status: 'online', conexaoId: socket.id });

    //recebendo ação do clique
    socket.on('recebendo click', function(data){
        //aqui vai o código a ser processado quando o servidor receber este evento
    });
});
<|endoftext|>


<commit_before>MODEL({
  name: 'AppController',

  properties: [
    {
      name: 'model'
    },
    {
      name: 'name',
      defaultValueFn: function() { return this.model.plural; },
    },
    {
      name: 'dao'
    },
    {
      name: 'sortChoices',
      help: 'Possible sorting options for the view.'
    },
    {
      name: 'citationView',
      defaultValueFn: function() { return this.model.name + 'CitationView'; }
    },
    {
      name: 'sortOrder',
      defaultValueFn: function() { return this.sortChoices ? this.sortChoices[0][0] : ''; }
    },
    {
      name: 'sortOrderView',
      factory: function() {
        if ( ! this.sortChoices ) return '';
        return this.X.PopupChoiceView.create({
          iconUrl: 'images/ic_sort_24dp.png',
          data$: this.sortOrder$,
          choices: this.sortChoices
        });
      }
    },
    {
      name: 'filterChoices'
    },
    {
      name: 'filteredDAO',
      model_: 'DAOProperty',
      help: 'Top-level filtered DAO. Further filtered by each canned query.'
    },
    {
      name: 'queryParser',
      factory: function() { return QueryParserFactory(this.model); }
    },
    {
      model_: 'BooleanProperty',
      name: 'editableCitationViews',
      defaultValue: false,
      help: 'True if you want to allow the citation views to be editable.'
    },
    {
      name: 'filteredDAOView',
      factory: function() {
        var DAOListView = this.X.ScrollView.xbind({
          model: this.model,
          mode: this.editableCitationViews ? 'read-write' : 'read-only',
          rowView: this.citationView,
          runway: 500
        });

        if ( ! this.filterChoices ) return DAOListView.create({ dao: this.filteredDAO$Proxy });
        var self = this;
        var views = this.filterChoices.map(function(filter) {
            return self.X.ViewChoice.create({
              view: self.X.PredicatedView.create({
                predicate: ( typeof filter[0] === "string" ?
                             self.queryParser.parseString(filter[0]) :
                             filter[0] ) || TRUE,
                dao: self.filteredDAO$Proxy,
                view: DAOListView.create()
              }),

              label: filter[1]
            });
          });

        return this.X.SwipeAltView.create({ views: views });
      }
    },
    {
      model_: 'BooleanProperty',
      defaultValue: false,
      name: 'searchMode'
    },
    {
      name: 'q',
      displayWidth: 25,
      view: {model_: 'TextFieldView', type: 'search', onKeyMode: true, placeholder: 'Search'} // TODO: change placeholder?
    },
    {
      model_: 'FunctionProperty',
      name: 'menuFactory'
    },
    {
      name: 'createAction',
      type: 'Action'
    }
  ],
  actions: [
    {
      name: 'menu',
      iconUrl: 'images/ic_menu_24dp.png',
      label: '',
      action: function() {
        this.X.stack.slideView(this.menuFactory());
      }
    },
    {
      name: 'previousQuery',
    },
    {
      name: 'enterSearchMode',
      iconUrl: 'images/ic_search_24dp.png',
      label: '',
      action: function() {
        this.previousQuery = this.q;
        this.searchMode = true;
      }
    },
    {
      name: 'leaveSearchMode',
      iconUrl: 'images/ic_arrow_back_24dp.png',
      label: '',
      action: function() {
        this.q = this.previousQuery;
        this.searchMode = false;
      }
    }
  ],
  methods: {
    init: function() {
      this.SUPER();

//      this.X = this.X.sub();

      var Button = ActionButtonCView.xbind({
        alpha:      0.76,
        width:      48,
        height:     44,
        iconWidth:  24,
        iconHeight: 24
      });
      this.X.registerModel(Button, 'ActionButton');

      var self = this;
      Events.dynamic(
        function() { self.sortOrder; self.q; },
        function() {
          self.filteredDAO = self.dao.where(self.queryParser.parseString(self.q) || TRUE).orderBy(self.sortOrder);
        }
      );
    }
  },
  templates: [
    function toDetailHTML() {/*
    <div id="<%= this.setClass('searchMode', function() { return self.data.searchMode; }, this.id) %>"  class="mdui-app-controller">

           $$menu
           $$name{mode: 'read-only', className: 'name'} $$enterSearchMode %%data.sortOrderView

           $$leaveSearchMode{className: 'backButton'} $$q

       %%data.filteredDAOView
       <% if ( this.data.createAction ) out(this.createActionView(this.data.createAction, { data: this.data, className: 'createButton', color: 'white', font: '30px Roboto Arial', alpha: 1, width: 44, height: 44, radius: 22, background: '#c43828'})); %>

    <%
      this.addInitializer(function() {
        if ( self.filterChoices ) {
          var v = self.data.filteredDAOView;
          v.index$.addListener(function() {
            self.qView.$.placeholder = "Search " + v.views[v.index].label.toLowerCase();
          });
        }
        self.data.searchMode$.addListener(EventService.merged(function() {
          self.qView.$.focus();
        }, 100));

      });

      this.on('touchstart', function(){ console.log('blurring'); self.qView.$.blur(); }, this.data.filteredDAOView.id);
      this.on('click', function(){ console.log('focusing'); self.qView.$.focus(); }, this.qView.id);
    %>
  */},
    function CSS() {/*
      body { background: white; }
   */}
  ]
});

MODEL({
  name: 'PositionedAppControllerView',
  traits: ['PositionedDOMViewTrait'],

  methods: {
    init: function() {
      this.SUPER();
      var self = this;
      this.X.dynamic(function() { self.width; self.height; }, this.layout);
    },
    header$: function() {
      return this.$(this.id + '-header');
    }
  },

  listeners: [
    {
      name: 'layout',
      code: function() {
        if ( ! this.$ ) return;
        this.header$().style.webkitTransform = 'translate3d(0,0,0)';
        if ( this.data && this.data.filteredDAOView ) {
          this.data.filteredDAOView.y = 48;
          this.data.filteredDAOView.height = this.height - 48;
          this.data.filteredDAOView.width = this.width;
        }
      }
    }
  ],

  templates: [
    function toHTML() {/*
    <div id="<%= this.setClass('searchMode', function() { return self.data.searchMode; }, this.id) %>"  class="mdui-app-controller" <%= this.layoutStyle() %>>
       <div id="<%= this.id %>-header" class="header">

           $$menu
           $$name{mode: 'read-only', className: 'name'} $$enterSearchMode %%data.sortOrderView

           $$leaveSearchMode{className: 'backButton'} $$q

       %%data.filteredDAOView
       <% if ( this.data.createAction ) out(this.createActionView(this.data.createAction, { data: this.data, className: 'createButton', color: 'white', font: '30px Roboto Arial', alpha: 1, width: 44, height: 44, radius: 22, background: '#c43828'})); %>

    <%
      this.addInitializer(function() {
        if ( self.filterChoices ) {
          var v = self.data.filteredDAOView;
          v.index$.addListener(function() {
            self.qView.$.placeholder = "Search " + v.views[v.index].label.toLowerCase();
          });
        }
        self.data.searchMode$.addListener(EventService.merged(function() {
          self.qView.$.focus();
        }, 100));
      });
    %>
    */}
  ]
});
<commit_msg>Added partialEval to query in AppController.<commit_after>MODEL({
  name: 'AppController',

  properties: [
    {
      name: 'model'
    },
    {
      name: 'name',
      defaultValueFn: function() { return this.model.plural; },
    },
    {
      name: 'dao'
    },
    {
      name: 'sortChoices',
      help: 'Possible sorting options for the view.'
    },
    {
      name: 'citationView',
      defaultValueFn: function() { return this.model.name + 'CitationView'; }
    },
    {
      name: 'sortOrder',
      defaultValueFn: function() { return this.sortChoices ? this.sortChoices[0][0] : ''; }
    },
    {
      name: 'sortOrderView',
      factory: function() {
        if ( ! this.sortChoices ) return '';
        return this.X.PopupChoiceView.create({
          iconUrl: 'images/ic_sort_24dp.png',
          data$: this.sortOrder$,
          choices: this.sortChoices
        });
      }
    },
    {
      name: 'filterChoices'
    },
    {
      name: 'filteredDAO',
      model_: 'DAOProperty',
      help: 'Top-level filtered DAO. Further filtered by each canned query.'
    },
    {
      name: 'queryParser',
      factory: function() { return QueryParserFactory(this.model); }
    },
    {
      model_: 'BooleanProperty',
      name: 'editableCitationViews',
      defaultValue: false,
      help: 'True if you want to allow the citation views to be editable.'
    },
    {
      name: 'filteredDAOView',
      factory: function() {
        var DAOListView = this.X.ScrollView.xbind({
          model: this.model,
          mode: this.editableCitationViews ? 'read-write' : 'read-only',
          rowView: this.citationView,
          runway: 500
        });

        if ( ! this.filterChoices ) return DAOListView.create({ dao: this.filteredDAO$Proxy });
        var self = this;
        var views = this.filterChoices.map(function(filter) {
            return self.X.ViewChoice.create({
              view: self.X.PredicatedView.create({
                predicate: ( typeof filter[0] === "string" ?
                             self.queryParser.parseString(filter[0]) :
                             filter[0] ) || TRUE,
                dao: self.filteredDAO$Proxy,
                view: DAOListView.create()
              }),

              label: filter[1]
            });
          });

        return this.X.SwipeAltView.create({ views: views });
      }
    },
    {
      model_: 'BooleanProperty',
      defaultValue: false,
      name: 'searchMode'
    },
    {
      name: 'q',
      displayWidth: 25,
      view: {model_: 'TextFieldView', type: 'search', onKeyMode: true, placeholder: 'Search'} // TODO: change placeholder?
    },
    {
      model_: 'FunctionProperty',
      name: 'menuFactory'
    },
    {
      name: 'createAction',
      type: 'Action'
    }
  ],
  actions: [
    {
      name: 'menu',
      iconUrl: 'images/ic_menu_24dp.png',
      label: '',
      action: function() {
        this.X.stack.slideView(this.menuFactory());
      }
    },
    {
      name: 'previousQuery',
    },
    {
      name: 'enterSearchMode',
      iconUrl: 'images/ic_search_24dp.png',
      label: '',
      action: function() {
        this.previousQuery = this.q;
        this.searchMode = true;
      }
    },
    {
      name: 'leaveSearchMode',
      iconUrl: 'images/ic_arrow_back_24dp.png',
      label: '',
      action: function() {
        this.q = this.previousQuery;
        this.searchMode = false;
      }
    }
  ],
  methods: {
    init: function() {
      this.SUPER();

//      this.X = this.X.sub();

      var Button = ActionButtonCView.xbind({
        alpha:      0.76,
        width:      48,
        height:     44,
        iconWidth:  24,
        iconHeight: 24
      });
      this.X.registerModel(Button, 'ActionButton');

      var self = this;
      Events.dynamic(
        function() { self.sortOrder; self.q; },
        function() {
          var query = (self.queryParser.parseString(self.q) || TRUE).partialEval();
          self.filteredDAO = self.dao.where(query).orderBy(self.sortOrder);
        }
      );
    }
  },
  templates: [
    function toDetailHTML() {/*
    <div id="<%= this.setClass('searchMode', function() { return self.data.searchMode; }, this.id) %>"  class="mdui-app-controller">

           $$menu
           $$name{mode: 'read-only', className: 'name'} $$enterSearchMode %%data.sortOrderView

           $$leaveSearchMode{className: 'backButton'} $$q

       %%data.filteredDAOView
       <% if ( this.data.createAction ) out(this.createActionView(this.data.createAction, { data: this.data, className: 'createButton', color: 'white', font: '30px Roboto Arial', alpha: 1, width: 44, height: 44, radius: 22, background: '#c43828'})); %>

    <%
      this.addInitializer(function() {
        if ( self.filterChoices ) {
          var v = self.data.filteredDAOView;
          v.index$.addListener(function() {
            self.qView.$.placeholder = "Search " + v.views[v.index].label.toLowerCase();
          });
        }
        self.data.searchMode$.addListener(EventService.merged(function() {
          self.qView.$.focus();
        }, 100));

      });

      this.on('touchstart', function(){ console.log('blurring'); self.qView.$.blur(); }, this.data.filteredDAOView.id);
      this.on('click', function(){ console.log('focusing'); self.qView.$.focus(); }, this.qView.id);
    %>
  */},
    function CSS() {/*
      body { background: white; }
   */}
  ]
});

MODEL({
  name: 'PositionedAppControllerView',
  traits: ['PositionedDOMViewTrait'],

  methods: {
    init: function() {
      this.SUPER();
      var self = this;
      this.X.dynamic(function() { self.width; self.height; }, this.layout);
    },
    header$: function() {
      return this.$(this.id + '-header');
    }
  },

  listeners: [
    {
      name: 'layout',
      code: function() {
        if ( ! this.$ ) return;
        this.header$().style.webkitTransform = 'translate3d(0,0,0)';
        if ( this.data && this.data.filteredDAOView ) {
          this.data.filteredDAOView.y = 48;
          this.data.filteredDAOView.height = this.height - 48;
          this.data.filteredDAOView.width = this.width;
        }
      }
    }
  ],

  templates: [
    function toHTML() {/*
    <div id="<%= this.setClass('searchMode', function() { return self.data.searchMode; }, this.id) %>"  class="mdui-app-controller" <%= this.layoutStyle() %>>
       <div id="<%= this.id %>-header" class="header">

           $$menu
           $$name{mode: 'read-only', className: 'name'} $$enterSearchMode %%data.sortOrderView

           $$leaveSearchMode{className: 'backButton'} $$q

       %%data.filteredDAOView
       <% if ( this.data.createAction ) out(this.createActionView(this.data.createAction, { data: this.data, className: 'createButton', color: 'white', font: '30px Roboto Arial', alpha: 1, width: 44, height: 44, radius: 22, background: '#c43828'})); %>

    <%
      this.addInitializer(function() {
        if ( self.filterChoices ) {
          var v = self.data.filteredDAOView;
          v.index$.addListener(function() {
            self.qView.$.placeholder = "Search " + v.views[v.index].label.toLowerCase();
          });
        }
        self.data.searchMode$.addListener(EventService.merged(function() {
          self.qView.$.focus();
        }, 100));
      });
    %>
    */}
  ]
});
<|endoftext|>


<commit_before>//= require <effects/operators/base>

/**
 *  class S2.FX.Operators.Style < S2.FX.Operators.Base
 *
 *  Operator for interpolatung the CSS styles of an Element.
**/
S2.FX.Operators.Style = Class.create(S2.FX.Operators.Base, {
  initialize: function($super, effect, object, options) {
    $super(effect, object, options);
    this.element = $(this.object);

    this.style = Object.isString(this.options.style) ?
      S2.CSS.parseStyle(this.options.style) : this.options.style;

    this.tweens = [];
    for(var item in this.style){
      var property = item.underscore().dasherize(),
        from = this.element.getStyle(property), to = this.style[item];

      console.log(item);
      console.log(this.options.propertyTransitions);
      if(from!=to)
        this.tweens.push([
          property, S2.CSS.interpolate.curry(property, from, to),
          (this.options.propertyTransitions && this.options.propertyTransitions[item]) ?
            Object.propertize(this.options.propertyTransitions[item], S2.FX.Transitions) : Prototype.K
        ]);
    }
  },

  valueAt: function(position) {
    return this.tweens.map( function(tween){
      return tween[0]+':'+tween[1](tween[2](position));
    }).join(';')
  },

  applyValue: function(value) {
    if(this.currentStyle == value) return;
    this.element.setStyle(value);
    this.currentStyle = value;
  }
});<commit_msg>remove console.log calls<commit_after>//= require <effects/operators/base>

/**
 *  class S2.FX.Operators.Style < S2.FX.Operators.Base
 *
 *  Operator for interpolatung the CSS styles of an Element.
**/
S2.FX.Operators.Style = Class.create(S2.FX.Operators.Base, {
  initialize: function($super, effect, object, options) {
    $super(effect, object, options);
    this.element = $(this.object);

    this.style = Object.isString(this.options.style) ?
      S2.CSS.parseStyle(this.options.style) : this.options.style;

    this.tweens = [];
    for(var item in this.style){
      var property = item.underscore().dasherize(),
        from = this.element.getStyle(property), to = this.style[item];

      if(from!=to)
        this.tweens.push([
          property, S2.CSS.interpolate.curry(property, from, to),
          (this.options.propertyTransitions && this.options.propertyTransitions[item]) ?
            Object.propertize(this.options.propertyTransitions[item], S2.FX.Transitions) : Prototype.K
        ]);
    }
  },

  valueAt: function(position) {
    return this.tweens.map( function(tween){
      return tween[0]+':'+tween[1](tween[2](position));
    }).join(';')
  },

  applyValue: function(value) {
    if(this.currentStyle == value) return;
    this.element.setStyle(value);
    this.currentStyle = value;
  }
});<|endoftext|>