<commit_before>/**
 * Copyright Victor Berchet
 *
 * This file is part of VisuGps3
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

/**
 * @fileoverview VisuGps3 map.
 * @author Victor Berchet <victor@suumit.com>
 */

goog.provide('vgps3.Map');

goog.require('goog.Uri.QueryData');
goog.require('goog.array');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.object');
goog.require('goog.ui.Dialog');
goog.require('goog.ui.Dialog.ButtonSet');
goog.require('vgps3.templates');

/**
 * @param {!Element} container The container.
 * @param {function(): Object.<string>} userOptions Google Maps options.
 * @param {(Array.<vgps3.PluginBase>|vgps3.PluginBase)=} opt_plugins A list of plugins.
 * @param {Function=} opt_callback Called once the map has been initialized.
 *
 * @constructor
 * @extends {goog.events.EventTarget}
 */
vgps3.Map = function(container, userOptions, opt_plugins, opt_callback) {
  /**
  * @type {google.maps.Map}
  * @private
  */
  this.gMap_;

  /**
  * @type {goog.ui.Dialog}
  * @private
  */
  this.aboutDialog_;

  /**
   * @type {Array.<vgps3.PluginBase>}
   * @private
   */
  this.plugins_ = goog.isArray(opt_plugins) ? opt_plugins : [opt_plugins];

  /**
   * @type {goog.debug.Logger}
   * @private
   */
  this.logger_ = goog.debug.Logger.getLogger('vgps3.Map');

  goog.base(this);

  this.loadGoogleMapsApi_(container, userOptions, opt_callback);
};
goog.inherits(vgps3.Map, goog.events.EventTarget);

/**
 * @return {google.maps.Map} The google map object.
 */
vgps3.Map.prototype.getGoogleMap = function() {
  return this.gMap_;
};

/**
 * Displays the about dialog.
 *
 * @return {undefined}
 */
vgps3.Map.prototype.showAbout = function() {
  if (!this.aboutDialog_) {
    this.aboutDialog_ = new goog.ui.Dialog(undefined, true);
    this.aboutDialog_.setTitle('VisuGps v' + vgps3.VERSION);
    this.aboutDialog_.setContent(vgps3.templates.about());
    this.aboutDialog_.setButtonSet(goog.ui.Dialog.ButtonSet.createOk());
    this.aboutDialog_.setEscapeToCancel(true);
    this.aboutDialog_.getDialogElement();
  }
  this.aboutDialog_.setVisible(true);
};

/**
 * Loads the google maps API with required libs.
 *
 * @param {!Element} container The container.
 * @param {function(): Object.<string>} userOptions Google Maps options.
 * @param {Function=} opt_callback Called once the map has been initialized.
 *
 * @private
 */
vgps3.Map.prototype.loadGoogleMapsApi_ = function(container, userOptions, opt_callback) {
  var libs = ['geometry'],
      parameters = new goog.Uri.QueryData('sensor=false'),
      key = this.getDomainKey(vgps3.Map.GOOGLE_API_KEYS);

  goog.array.forEach(this.plugins_, function(plugin) {
    libs = libs.concat(plugin.requireGoogleMapLibs());
  });

  if (libs.length > 0) {
    goog.array.removeDuplicates(libs);
    parameters.add('libraries', libs.join(','));
  }

  if (null !== key) {
    parameters.add('key', key);
  }

  vgps3.loader.load(
      'maps',
      '3',
      goog.bind(this.init_, this, container, userOptions, opt_callback),
      {'other_params': parameters.toString()}
  );
};

/**
 * @override
 */
vgps3.Map.prototype.disposeInternal = function() {
  goog.base(this, 'disposeInternal');
  goog.events.removeAll();
  google.maps.clearInstanceListeners(this.gMap_);
  goog.dispose(this.aboutDialog_);
  this.aboutDialog_ = null;
  goog.array.forEach(this.plugins_, function(plugin) {
    goog.dispose(plugin);
  });
};

/**
 * Creates the map and initializes the plugins.
 *
 * @param {!Element} container The map container.
 * @param {function(): Object.<string>} userOptions A list of plugins.
 * @param {Function} callback called at the end of the init phase.
 * @private
 */
vgps3.Map.prototype.init_ = function(container, userOptions, callback) {
  var options = {
    'center': new google.maps.LatLng(46.73986, 2.17529),
    'zoom': 5,
    'minZoom': 6,
    'mapTypeId': google.maps.MapTypeId.TERRAIN,
    'streetViewControl': false,
    'scaleControl': true
  };

  goog.object.extend(options, userOptions() || {});

  this.gMap_ = new google.maps.Map(container, options);

  goog.events.listen(
      window,
      'resize',
      function() {google.maps.event.trigger(this.gMap_, 'resize')},
      undefined,
      this
  );

  goog.array.forEach(this.plugins_, function(plugin) {plugin.init(this);}, this);

  callback();
};

/**
 * Returns the key for the current domain
 *
 * @param {string} keys The keys, format='domain1="key1" domain2="key2" *="fallback key"'.
 *
 * @return {?string} The key, null when no matching domain has been found.
 */
vgps3.Map.prototype.getDomainKey = function(keys) {
  var re = /([\w-.*]+)="(.+?)"/g,
      matches;

  while (matches = re.exec(keys)) {
    if ('*' === matches[1] || -1 !== document.domain.indexOf(matches[1])) {
      return matches[2];
    }
  }

  return null;
};

/**
 * @define {string} The API keys format='domain1="key1" domain2="key2" *="fallback key"'.
 */
vgps3.Map.GOOGLE_API_KEYS = '';

/**
 * @define {string}
 */
vgps3.VERSION = '3.0.0-beta1';

goog.exportSymbol('vgps3.Map', vgps3.Map);
goog.exportSymbol('vgps3.Map.showAbout', vgps3.Map.prototype.showAbout);
goog.exportSymbol('vgps3.Map.getGoogleMap', vgps3.Map.prototype.getGoogleMap);
goog.exportSymbol('vgps3.Map.getDomainKey', vgps3.Map.prototype.getDomainKey);
<commit_msg>sensor parameter is no longer required in the Maps API URL since 3.17<commit_after>/**
 * Copyright Victor Berchet
 *
 * This file is part of VisuGps3
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 */

/**
 * @fileoverview VisuGps3 map.
 * @author Victor Berchet <victor@suumit.com>
 */

goog.provide('vgps3.Map');

goog.require('goog.Uri.QueryData');
goog.require('goog.array');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.object');
goog.require('goog.ui.Dialog');
goog.require('goog.ui.Dialog.ButtonSet');
goog.require('vgps3.templates');

/**
 * @param {!Element} container The container.
 * @param {function(): Object.<string>} userOptions Google Maps options.
 * @param {(Array.<vgps3.PluginBase>|vgps3.PluginBase)=} opt_plugins A list of plugins.
 * @param {Function=} opt_callback Called once the map has been initialized.
 *
 * @constructor
 * @extends {goog.events.EventTarget}
 */
vgps3.Map = function(container, userOptions, opt_plugins, opt_callback) {
  /**
  * @type {google.maps.Map}
  * @private
  */
  this.gMap_;

  /**
  * @type {goog.ui.Dialog}
  * @private
  */
  this.aboutDialog_;

  /**
   * @type {Array.<vgps3.PluginBase>}
   * @private
   */
  this.plugins_ = goog.isArray(opt_plugins) ? opt_plugins : [opt_plugins];

  /**
   * @type {goog.debug.Logger}
   * @private
   */
  this.logger_ = goog.debug.Logger.getLogger('vgps3.Map');

  goog.base(this);

  this.loadGoogleMapsApi_(container, userOptions, opt_callback);
};
goog.inherits(vgps3.Map, goog.events.EventTarget);

/**
 * @return {google.maps.Map} The google map object.
 */
vgps3.Map.prototype.getGoogleMap = function() {
  return this.gMap_;
};

/**
 * Displays the about dialog.
 *
 * @return {undefined}
 */
vgps3.Map.prototype.showAbout = function() {
  if (!this.aboutDialog_) {
    this.aboutDialog_ = new goog.ui.Dialog(undefined, true);
    this.aboutDialog_.setTitle('VisuGps v' + vgps3.VERSION);
    this.aboutDialog_.setContent(vgps3.templates.about());
    this.aboutDialog_.setButtonSet(goog.ui.Dialog.ButtonSet.createOk());
    this.aboutDialog_.setEscapeToCancel(true);
    this.aboutDialog_.getDialogElement();
  }
  this.aboutDialog_.setVisible(true);
};

/**
 * Loads the google maps API with required libs.
 *
 * @param {!Element} container The container.
 * @param {function(): Object.<string>} userOptions Google Maps options.
 * @param {Function=} opt_callback Called once the map has been initialized.
 *
 * @private
 */
vgps3.Map.prototype.loadGoogleMapsApi_ = function(container, userOptions, opt_callback) {
  var libs = ['geometry'],
      parameters = new goog.Uri.QueryData(),
      key = this.getDomainKey(vgps3.Map.GOOGLE_API_KEYS);

  goog.array.forEach(this.plugins_, function(plugin) {
    libs = libs.concat(plugin.requireGoogleMapLibs());
  });

  if (libs.length > 0) {
    goog.array.removeDuplicates(libs);
    parameters.add('libraries', libs.join(','));
  }

  if (null !== key) {
    parameters.add('key', key);
  }

  vgps3.loader.load(
      'maps',
      '3',
      goog.bind(this.init_, this, container, userOptions, opt_callback),
      {'other_params': parameters.toString()}
  );
};

/**
 * @override
 */
vgps3.Map.prototype.disposeInternal = function() {
  goog.base(this, 'disposeInternal');
  goog.events.removeAll();
  google.maps.clearInstanceListeners(this.gMap_);
  goog.dispose(this.aboutDialog_);
  this.aboutDialog_ = null;
  goog.array.forEach(this.plugins_, function(plugin) {
    goog.dispose(plugin);
  });
};

/**
 * Creates the map and initializes the plugins.
 *
 * @param {!Element} container The map container.
 * @param {function(): Object.<string>} userOptions A list of plugins.
 * @param {Function} callback called at the end of the init phase.
 * @private
 */
vgps3.Map.prototype.init_ = function(container, userOptions, callback) {
  var options = {
    'center': new google.maps.LatLng(46.73986, 2.17529),
    'zoom': 5,
    'minZoom': 6,
    'mapTypeId': google.maps.MapTypeId.TERRAIN,
    'streetViewControl': false,
    'scaleControl': true
  };

  goog.object.extend(options, userOptions() || {});

  this.gMap_ = new google.maps.Map(container, options);

  goog.events.listen(
      window,
      'resize',
      function() {google.maps.event.trigger(this.gMap_, 'resize')},
      undefined,
      this
  );

  goog.array.forEach(this.plugins_, function(plugin) {plugin.init(this);}, this);

  callback();
};

/**
 * Returns the key for the current domain
 *
 * @param {string} keys The keys, format='domain1="key1" domain2="key2" *="fallback key"'.
 *
 * @return {?string} The key, null when no matching domain has been found.
 */
vgps3.Map.prototype.getDomainKey = function(keys) {
  var re = /([\w-.*]+)="(.+?)"/g,
      matches;

  while (matches = re.exec(keys)) {
    if ('*' === matches[1] || -1 !== document.domain.indexOf(matches[1])) {
      return matches[2];
    }
  }

  return null;
};

/**
 * @define {string} The API keys format='domain1="key1" domain2="key2" *="fallback key"'.
 */
vgps3.Map.GOOGLE_API_KEYS = '';

/**
 * @define {string}
 */
vgps3.VERSION = '3.0.0-beta1';

goog.exportSymbol('vgps3.Map', vgps3.Map);
goog.exportSymbol('vgps3.Map.showAbout', vgps3.Map.prototype.showAbout);
goog.exportSymbol('vgps3.Map.getGoogleMap', vgps3.Map.prototype.getGoogleMap);
goog.exportSymbol('vgps3.Map.getDomainKey', vgps3.Map.prototype.getDomainKey);
<|endoftext|>


<commit_before>
export function timeSince(to) {
    var seconds = Math.floor((new Date() - to) / 1000);
    var interval = Math.floor(seconds / 31536000);
    if (interval > 1) {
        return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
}

export function strFromDuration(duration) {
    var seconds = Math.floor(duration / 1000);
    var interval = Math.floor(seconds / 31536000);
    var ret = "";
    if (interval > 1) {
        ret += interval + " years ";
        seconds -= interval * 31536000;
    }
    interval = Math.floor(seconds / 2592000);
    if (interval > 1) {
        ret += interval + " months ";
        seconds -= interval * 2592000;
    }
    interval = Math.floor(seconds / 86400);
    if (interval > 1) {
        ret += interval + " days ";
        seconds -= interval * 86400;
    }
    interval = Math.floor(seconds / 3600);
    if (interval > 1) {
        ret += interval + " hr ";
        seconds -= interval * 3600;
    }
    interval = Math.floor(seconds / 60);
    if (interval > 1) {
        ret += interval + " min ";
        seconds -= interval * 60;
    }
    ret += Math.floor(seconds) + " s ";
    return ret;
}

export function dateToString(date) {
    return date.toLocaleDateString() + " " + date.toLocaleTimeString('en-US');
}<commit_msg>bug fix duration and time ago<commit_after>
export function timeSince(to) {
    var seconds = Math.floor((new Date() - to) / 1000);
    var interval = Math.floor(seconds / 31536000);
    if (interval >= 1) {
        return interval + " years";
    }
    interval = Math.floor(seconds / 2592000);
    if (interval >= 1) {
        return interval + " months";
    }
    interval = Math.floor(seconds / 86400);
    if (interval >= 1) {
        return interval + " days";
    }
    interval = Math.floor(seconds / 3600);
    if (interval >= 1) {
        return interval + " hours";
    }
    interval = Math.floor(seconds / 60);
    if (interval >= 1) {
        return interval + " minutes";
    }
    return Math.floor(seconds) + " seconds";
}

export function strFromDuration(duration) {
    var seconds = Math.floor(duration / 1000);
    var interval = Math.floor(seconds / 31536000);
    var ret = "";
    if (interval >= 1) {
        ret += interval + " years ";
        seconds -= interval * 31536000;
    }
    interval = Math.floor(seconds / 2592000);
    if (interval >= 1) {
        ret += interval + " months ";
        seconds -= interval * 2592000;
    }
    interval = Math.floor(seconds / 86400);
    if (interval >= 1) {
        ret += interval + " days ";
        seconds -= interval * 86400;
    }
    interval = Math.floor(seconds / 3600);
    if (interval >= 1) {
        ret += interval + " hr ";
        seconds -= interval * 3600;
    }
    interval = Math.floor(seconds / 60);
    if (interval >= 1) {
        ret += interval + " min ";
        seconds -= interval * 60;
    }
    ret += Math.floor(seconds) + " s ";
    return ret;
}

export function dateToString(date) {
    return date.toLocaleDateString() + " " + date.toLocaleTimeString('en-US');
}<|endoftext|>


<commit_before>import Obj from 'snew/obj/class';

export default Obj({
	////-----------------------------------------------------------------------------------------
	// In which package does requirejs use the templates
	templatePrefix: 'templates/',
	////-----------------------------------------------------------------------------------------
	// Jquery selector where the this.startPath controller and view are added
	entrance: '#app',
	////-----------------------------------------------------------------------------------------
	// Controller which is added at startup
	startPath: 'main/app',
	////-----------------------------------------------------------------------------------------
	// domnode-attribute for start uid node
	uidDomNode: 'SCRIPT',
	////-----------------------------------------------------------------------------------------
	// domnode-attribute for start uid node
	uidAttrStart: 'data-begin',
	////-----------------------------------------------------------------------------------------
	// domnode-attribute for end uid node
	uidAttrEnd: 'data-end',
	////-----------------------------------------------------------------------------------------
	// Existing classes collection
	list: {},
	////-----------------------------------------------------------------------------------------
	// saves which views changed
	dirties: [],
	////-----------------------------------------------------------------------------------------
	// Decides which instances are asked for handling events
	eventSpaces: [ 'controllerHelper', 'helperHelper' ],
	////-----------------------------------------------------------------------------------------
	// JQuery events which the framework is listening for
	eventListeners: ['keyup'],
	////-----------------------------------------------------------------------------------------
	// maps e.g. keypresses to trigger shortevents for enter and escape-keys
	eventMap: {
		keyup: {
			keyCode: {
				13: 'view.enterkey',
				27: 'view.escapekey'
			}

		}
	},
	_meta: {
		contentSpace: false
	},
	////-----------------------------------------------------------------------------------------
	// adds dirtychecking to runloop and inserts first view this.startPath and starts document event listener
	init() {
		tempartCompiler.partial = this.partialHandling; // Thats how you configure tempart...
		if( this.dirtyHandling !== false ){
			this.addJob({callback: this.dirtyChecking});
		}
		this.checkValidity();
		this.insertApp();
		this.addEvents();
	},
	////-----------------------------------------------------------------------------------------
	// adds dirtychecking to runloop and inserts first view this.startPath and starts document event listener
	partialHandling(block, context, currentValues, dirties, path) {
		// @TODO add uid to currentValues
		currentValues[ block.id ] = {path, uid: 1 + snew.controllerHelper.id};
		return snew.controllerHelper.create( path, context ).html;
	},
	////-----------------------------------------------------------------------------------------
	// creates instance of view
	create(path, opt) {
		return this.getEntity(path);
	},
	////-----------------------------------------------------------------------------------------
	// inserts first view to this.entrance
	insertApp() {
		const dom = document.querySelector( this.entrance );
		if( dom ) {
			const result = snew.controllerHelper.create( this.startPath, null, {} );
			dom.outerHTML = result.html;
		} else {
			console.error('snew.viewHelper.entrance was not represented in dom properly', dom);
		}
	},
	////-----------------------------------------------------------------------------------------
	// gets class and returns instance
	getEntity(path) {
		if( !this.list[ path ]){
			console.log(`View ${path} does not exist`);
			snew.View(path, {_meta: {pseudo: true}});
		}
		return snew.utilHelper.clone( this.list[ path ] );
	},
	////-----------------------------------------------------------------------------------------
	// start uid
	// @TODO move this to the templating engine
	scriptStart(id, path) {
		return `<${this.uidDomNode} ${this.uidAttrStart}="${id}" data-template="${path}"></${this.uidDomNode}>`;
	},
	////-----------------------------------------------------------------------------------------
	// end uid
	scriptEnd(id) {
		return `<${this.uidDomNode} ${this.uidAttrEnd}="${id}"></${this.uidDomNode}>`;
	},
	////-----------------------------------------------------------------------------------------
	// some basic checking if values are correct
	checkValidity() {
		if( !this.entrance ){
			throw "App entrance is not defined";
		}
	},
	////-----------------------------------------------------------------------------------------
	// checks which views are dirty, to asynchronoesly render them
	dirtyChecking() {
		if(snew.viewHelper.dirties) {

			for( let i = 0; i < snew.viewHelper.dirties.length; i++ ){
				const uid = snew.viewHelper.dirties[i];
				const controllers = snew.controllerHelper.search(uid);
				for( let controllerIndex = 0; controllerIndex < controllers.length; controllerIndex++ ){
					const controller = controllers[ controllerIndex ];
					controller.view._handleDirties();
				}
			}
			snew.viewHelper.dirties = [];
		}
	},
	////-----------------------------------------------------------------------------------------
	// iterates through all dom-nodes to the top and returns an array of controllers
	getUids(obj) {
		const result    = [];
		const excludes  = [];
		do {
			const endUid = this.isUidEndObj( obj );
			const uid = this.isUidObj( obj );

			if( endUid ){
				excludes.push(endUid); // Needed to handle siblings, which do not surround the target
			} else if( uid && excludes.indexOf( uid ) === -1 ){
				result.push(uid);
			}
			if(obj.previousSibling) {
				obj = obj.previousSibling;
			} else {
				obj = obj.parentNode;
			}
		} while(obj)

		return result;
	},
	////-----------------------------------------------------------------------------------------
	// checks if dom-node is an uid-obj
	isUidObj(obj) {
		return this._getAttributeValue(obj, this.uidDomNode, this.uidAttrStart);
	},
	////-----------------------------------------------------------------------------------------
	// checks if dom-node is an uid-end-obj
	isUidEndObj(obj) {
		return this._getAttributeValue(obj, this.uidDomNode, this.uidAttrEnd);
	},
	////-----------------------------------------------------------------------------------------
	// expects node type and an attribute key, returns this when exists
	_getAttributeValue(obj, nodeName, attributeName) {
		if(obj.nodeName === nodeName) { // @FIXME
			for( let i = 0; i < obj.attributes.length; i++ ) {
				if( obj.attributes[ i ].nodeName === attributeName ){
					return obj.attributes[ i ].nodeValue;
				}
			}
		}
	},
	////-----------------------------------------------------------------------------------------
	// adds all dom events which the framework ist listening for
	addEvents() {
		for(let i = 0; i < this.eventListeners.length; i++) {
			document.body.addEventListener(this.eventListeners[ i ], evt => {
				return snew.viewHelper.handleEvent( evt );
			});
		}
		window.addEventListener('hashchange', () => {
			trhis.trigger('hashchange', location.hash);
		});
	},
	////-----------------------------------------------------------------------------------------
	// wrapper for triggering events, selects corresponding parent-controllers
	handleEvent(evt) {
		const uids = this.getUids( evt.target );
		this.triggerExtra(evt);
		this.updateData(evt);
	},
	////-----------------------------------------------------------------------------------------
	// way binding from dom
	updateData(evt) {
		if( evt.type == 'keyup' || evt.type == 'keydown' ){
			const identifier = evt.target.getAttribute('tempartstart');
			if( identifier && evt.keyCode !== 13 ){ // Enter button don't bring changes into the values
				const pos = identifier.indexOf( '-' );
				const uid = identifier.slice( 0, pos );
				const blockId = identifier.slice( pos + 1, identifier.length );
				const controllers = snew.search( uid );
				if( controllers.length === 1 ){
					const controller = controllers[ 0 ];
					controller.view._updateCurrent(blockId, 'value', evt.target.value);
				} else {
					throw 'Getting the correct controller failed somehow';
				}
			}
		}
	},
	////-----------------------------------------------------------------------------------------
	// triggers eventmaps like keypresses to shortevents like "enterkey" and escapekey
	triggerExtra(evt) {
		if( this.eventMap[ evt.type ] ){
			for( const index in this.eventMap[ evt.type ] ) {
				const eventValue = evt[ index ];
				if( eventValue ) {
					const mapValue = this.eventMap[ evt.type ][ index ][ eventValue ];
					if( mapValue ){
						this.trigger(mapValue, evt); // @TODO does this evt needs a clone?
					}
				}
			}
		}
	},
	////-----------------------------------------------------------------------------------------
	// recusively goes upside in the dom, to collect dataattributes
	getAttributes(target, result) {
		if(!result) result = {};

		if(target) {
			const attributes = target.attributes;

			if(result.id === undefined && target.attr('id') && attributes['data-id'] === undefined) {
				result.id = target.attr('id');
			}

			const excludes = ['ember-extension'];

			for (const index in attributes) {
				if (attributes.hasOwnProperty(index)) {
					const name  = attributes[index].name, value = attributes[index].value;
					if(name && name.search('data-') === 0) {
						let key = name.replace(/data-/, '');
						if(result[key] === undefined && excludes.indexOf(key) == -1) { // SHould only overwrite when not set
							result[key] = value || null;
						}
					}
				}
			}
			if(target.parentNode) {
				result = this.getAttributes(target.parentNode, result);
			}
		}
		return result;
	}
});<commit_msg>[typo] removed typo<commit_after>import Obj from 'snew/obj/class';

export default Obj({
	////-----------------------------------------------------------------------------------------
	// In which package does requirejs use the templates
	templatePrefix: 'templates/',
	////-----------------------------------------------------------------------------------------
	// Jquery selector where the this.startPath controller and view are added
	entrance: '#app',
	////-----------------------------------------------------------------------------------------
	// Controller which is added at startup
	startPath: 'main/app',
	////-----------------------------------------------------------------------------------------
	// domnode-attribute for start uid node
	uidDomNode: 'SCRIPT',
	////-----------------------------------------------------------------------------------------
	// domnode-attribute for start uid node
	uidAttrStart: 'data-begin',
	////-----------------------------------------------------------------------------------------
	// domnode-attribute for end uid node
	uidAttrEnd: 'data-end',
	////-----------------------------------------------------------------------------------------
	// Existing classes collection
	list: {},
	////-----------------------------------------------------------------------------------------
	// saves which views changed
	dirties: [],
	////-----------------------------------------------------------------------------------------
	// Decides which instances are asked for handling events
	eventSpaces: [ 'controllerHelper', 'helperHelper' ],
	////-----------------------------------------------------------------------------------------
	// JQuery events which the framework is listening for
	eventListeners: ['keyup'],
	////-----------------------------------------------------------------------------------------
	// maps e.g. keypresses to trigger shortevents for enter and escape-keys
	eventMap: {
		keyup: {
			keyCode: {
				13: 'view.enterkey',
				27: 'view.escapekey'
			}

		}
	},
	_meta: {
		contentSpace: false
	},
	////-----------------------------------------------------------------------------------------
	// adds dirtychecking to runloop and inserts first view this.startPath and starts document event listener
	init() {
		tempartCompiler.partial = this.partialHandling; // Thats how you configure tempart...
		if( this.dirtyHandling !== false ){
			this.addJob({callback: this.dirtyChecking});
		}
		this.checkValidity();
		this.insertApp();
		this.addEvents();
	},
	////-----------------------------------------------------------------------------------------
	// adds dirtychecking to runloop and inserts first view this.startPath and starts document event listener
	partialHandling(block, context, currentValues, dirties, path) {
		// @TODO add uid to currentValues
		currentValues[ block.id ] = {path, uid: 1 + snew.controllerHelper.id};
		return snew.controllerHelper.create( path, context ).html;
	},
	////-----------------------------------------------------------------------------------------
	// creates instance of view
	create(path, opt) {
		return this.getEntity(path);
	},
	////-----------------------------------------------------------------------------------------
	// inserts first view to this.entrance
	insertApp() {
		const dom = document.querySelector( this.entrance );
		if( dom ) {
			const result = snew.controllerHelper.create( this.startPath, null, {} );
			dom.outerHTML = result.html;
		} else {
			console.error('snew.viewHelper.entrance was not represented in dom properly', dom);
		}
	},
	////-----------------------------------------------------------------------------------------
	// gets class and returns instance
	getEntity(path) {
		if( !this.list[ path ]){
			console.log(`View ${path} does not exist`);
			snew.View(path, {_meta: {pseudo: true}});
		}
		return snew.utilHelper.clone( this.list[ path ] );
	},
	////-----------------------------------------------------------------------------------------
	// start uid
	// @TODO move this to the templating engine
	scriptStart(id, path) {
		return `<${this.uidDomNode} ${this.uidAttrStart}="${id}" data-template="${path}"></${this.uidDomNode}>`;
	},
	////-----------------------------------------------------------------------------------------
	// end uid
	scriptEnd(id) {
		return `<${this.uidDomNode} ${this.uidAttrEnd}="${id}"></${this.uidDomNode}>`;
	},
	////-----------------------------------------------------------------------------------------
	// some basic checking if values are correct
	checkValidity() {
		if( !this.entrance ){
			throw "App entrance is not defined";
		}
	},
	////-----------------------------------------------------------------------------------------
	// checks which views are dirty, to asynchronoesly render them
	dirtyChecking() {
		if(snew.viewHelper.dirties) {

			for( let i = 0; i < snew.viewHelper.dirties.length; i++ ){
				const uid = snew.viewHelper.dirties[i];
				const controllers = snew.controllerHelper.search(uid);
				for( let controllerIndex = 0; controllerIndex < controllers.length; controllerIndex++ ){
					const controller = controllers[ controllerIndex ];
					controller.view._handleDirties();
				}
			}
			snew.viewHelper.dirties = [];
		}
	},
	////-----------------------------------------------------------------------------------------
	// iterates through all dom-nodes to the top and returns an array of controllers
	getUids(obj) {
		const result    = [];
		const excludes  = [];
		do {
			const endUid = this.isUidEndObj( obj );
			const uid = this.isUidObj( obj );

			if( endUid ){
				excludes.push(endUid); // Needed to handle siblings, which do not surround the target
			} else if( uid && excludes.indexOf( uid ) === -1 ){
				result.push(uid);
			}
			if(obj.previousSibling) {
				obj = obj.previousSibling;
			} else {
				obj = obj.parentNode;
			}
		} while(obj)

		return result;
	},
	////-----------------------------------------------------------------------------------------
	// checks if dom-node is an uid-obj
	isUidObj(obj) {
		return this._getAttributeValue(obj, this.uidDomNode, this.uidAttrStart);
	},
	////-----------------------------------------------------------------------------------------
	// checks if dom-node is an uid-end-obj
	isUidEndObj(obj) {
		return this._getAttributeValue(obj, this.uidDomNode, this.uidAttrEnd);
	},
	////-----------------------------------------------------------------------------------------
	// expects node type and an attribute key, returns this when exists
	_getAttributeValue(obj, nodeName, attributeName) {
		if(obj.nodeName === nodeName) { // @FIXME
			for( let i = 0; i < obj.attributes.length; i++ ) {
				if( obj.attributes[ i ].nodeName === attributeName ){
					return obj.attributes[ i ].nodeValue;
				}
			}
		}
	},
	////-----------------------------------------------------------------------------------------
	// adds all dom events which the framework ist listening for
	addEvents() {
		for(let i = 0; i < this.eventListeners.length; i++) {
			document.body.addEventListener(this.eventListeners[ i ], evt => {
				return snew.viewHelper.handleEvent( evt );
			});
		}
		window.addEventListener('hashchange', () => {
			this.trigger('hashchange', location.hash);
		});
	},
	////-----------------------------------------------------------------------------------------
	// wrapper for triggering events, selects corresponding parent-controllers
	handleEvent(evt) {
		const uids = this.getUids( evt.target );
		this.triggerExtra(evt);
		this.updateData(evt);
	},
	////-----------------------------------------------------------------------------------------
	// way binding from dom
	updateData(evt) {
		if( evt.type == 'keyup' || evt.type == 'keydown' ){
			const identifier = evt.target.getAttribute('tempartstart');
			if( identifier && evt.keyCode !== 13 ){ // Enter button don't bring changes into the values
				const pos = identifier.indexOf( '-' );
				const uid = identifier.slice( 0, pos );
				const blockId = identifier.slice( pos + 1, identifier.length );
				const controllers = snew.search( uid );
				if( controllers.length === 1 ){
					const controller = controllers[ 0 ];
					controller.view._updateCurrent(blockId, 'value', evt.target.value);
				} else {
					throw 'Getting the correct controller failed somehow';
				}
			}
		}
	},
	////-----------------------------------------------------------------------------------------
	// triggers eventmaps like keypresses to shortevents like "enterkey" and escapekey
	triggerExtra(evt) {
		if( this.eventMap[ evt.type ] ){
			for( const index in this.eventMap[ evt.type ] ) {
				const eventValue = evt[ index ];
				if( eventValue ) {
					const mapValue = this.eventMap[ evt.type ][ index ][ eventValue ];
					if( mapValue ){
						this.trigger(mapValue, evt); // @TODO does this evt needs a clone?
					}
				}
			}
		}
	},
	////-----------------------------------------------------------------------------------------
	// recusively goes upside in the dom, to collect dataattributes
	getAttributes(target, result) {
		if(!result) result = {};

		if(target) {
			const attributes = target.attributes;

			if(result.id === undefined && target.attr('id') && attributes['data-id'] === undefined) {
				result.id = target.attr('id');
			}

			const excludes = ['ember-extension'];

			for (const index in attributes) {
				if (attributes.hasOwnProperty(index)) {
					const name  = attributes[index].name, value = attributes[index].value;
					if(name && name.search('data-') === 0) {
						let key = name.replace(/data-/, '');
						if(result[key] === undefined && excludes.indexOf(key) == -1) { // SHould only overwrite when not set
							result[key] = value || null;
						}
					}
				}
			}
			if(target.parentNode) {
				result = this.getAttributes(target.parentNode, result);
			}
		}
		return result;
	}
});<|endoftext|>


<commit_before>/**
 * Proyecto
 *
 * # author      Damián <@damian>
 * # copyright   Copyright (c) 2016, Proyecto
 *
 */

/**
 * ----------------------------
 *		Variables
 * ----------------------------
 *
 * - Modal
 *
 */

// Modal - Agregar
var modal = document.getElementById('modal-agregar-post');
var modalOpen = document.getElementById("modal-agregar-post-open");
// var modalClose = document.getElementById("modal-agregar-post-close");

// Modal - Mensaje
var modalMensaje = document.getElementById('modal-mensaje');
var modalOpenMensaje = document.getElementById("modal-mensaje-open");
var modalCloseMensaje = document.getElementsByClassName("modal-mensaje-close");

// Body Alto
var bodysHeight = 0;

/**
 * ----------------------------
 *		Document Ready
 * ----------------------------
 *
 * - Animsition
 * - Ladda
 * - Modal
 *
 */
$(document).ready(function(){

	/**
	 * Animsition
	 */
	$('.animsition').animsition();

	$('.ver-capitulos').addClass("ver-js-capitulos");

	/**
	 * Ladda
	 */

	$('.home-article-button').click(function(e){
		var l = Ladda.create(this);
		l.start();
	});

	/**
	 * Modal
	 */
	// Open Modal
	$(modalOpen).on("click", function(){
		modal.style.display = "flex";
		modal.style.display = "-ms-flexbox";
	});

	/**
	 * Animate - Login elementos
	 */
	$(".login-cont .animated").animate({ "opacity": "0" }, 0, function() {
		$(".login-cont").show();
		$(".login-cont .animated").each(function(index) {$( this ).addClass("delay-"+(index)+" fadeInUp");});
	});

	/**
	 * Cambio de color - White
	 */
	$('.ver-capitulo-leer').on("click", function(){
		$('body').toggleClass("body-white");
		$('.ver-capitulo').toggleClass("ver-capitulo-white");
		$('footer').toggleClass("footer-white");
	});

	/**
	 * Click view Full
	 */
	$('.ver-capitulo-full-screen').on("click", function(){

		// $(".ver-capitulo").removeClass("ver-capitulo-white");

		// var heightScreen = $( window ).height();
		// alert(heightScreen);

		// $('.ver-capitulo-full-screen').fadeOut();
		// $('.ver-capitulo-full-screen').fadeOut();
		$('.ver-capitulo-full-screen').hide();
		$('.ver-capitulo-close-screen').css("display", "flex");
		$('.ver-capitulo-close-screen').css("display", "-ms-flexbox");
		$('.ver-capitulo').fullscreen();
		$(".ver-capitulo").addClass("ver-capitulo-full");

		// $(".asScrollable-container").css("height", heightScreen + "px");

		$(".asScrollable-container").toggleClass("asScrollable-container-full");
		$(".asScrollable-bar-vertical").delay(400).css("height", "calc(100vh - 10px)");

		$('.ver-capitulos').removeClass("ver-js-capitulos");
		$(".ver-capitulos").addClass("ver-js-capitulos-full");
		// $(".nav-capitulos-cont").delay(400).css("height", "100vh");

		// $(".ver-capitulo-leer").fadeOut();
		// $(".ver-capitulo-leer-full").fadeIn();

		// $('body').toggleClass("body-white");
		// $('footer').toggleClass("footer-white");

	});

	/**
	 * Click close Full
	 */
	$('.ver-capitulo-close-screen').on("click", function(){

		// $('.ver-capitulo-full-screen').fadeIn();
		// $('.ver-capitulo-close-screen').fadeOut();
		$('.ver-capitulo-full-screen').css("display", "flex");
		$('.ver-capitulo-full-screen').css("display", "-ms-flexbox");
		$('.ver-capitulo-close-screen').hide();
		$(".ver-capitulo").removeClass("ver-capitulo-full");

		$(".asScrollable-container").toggleClass("asScrollable-container-full");
		$(".asScrollable-bar-vertical").delay(400).css("height", "calc(100vh - 10px)");

		$('.ver-capitulos').addClass("ver-js-capitulos");
		$(".ver-capitulos").removeClass("ver-js-capitulos-full");

		// $(".asScrollable-bar-vertical").delay(400).css("height", "100vh");
		// $(".nav-capitulos-cont").delay(400).css("height", "100%");

		$.fullscreen.exit();

	});

	/**
	 * Click close Full (ESC)
	 */
	$(document).keyup(function (e) {
		if (e.keyCode == 27) {

			// $('.ver-capitulo-full-screen').fadeIn();
			// $('.ver-capitulo-close-screen').fadeOut();
			$('.ver-capitulo-full-screen').css("display", "flex");
			$('.ver-capitulo-full-screen').css("display", "-ms-flexbox");
			$('.ver-capitulo-close-screen').hide();
			$(".ver-capitulo").removeClass("ver-capitulo-full");

			$(".asScrollable-container").toggleClass("asScrollable-container-full");
			$(".asScrollable-bar-vertical").delay(400).css("height", "calc(100vh - 10px)");

			$('.ver-capitulos').addClass("ver-js-capitulos");
			$(".ver-capitulos").removeClass("ver-js-capitulos-full");

			// $(".asScrollable-bar-vertical").delay(400).css("height", "100vh");
			// $(".nav-capitulos-cont").delay(400).css("height", "100%");

			$.fullscreen.exit();

		}
	});

	/**
	 * Cambio de color - White
	 */
	$('.ver-capitulo-leer-full').on("click", function(){
		$('.ver-capitulo').toggleClass("ver-capitulo-white-full");
	});

	/**
	 * Modal - Mensaje
	 */
	// Open Modal
	$(modalOpenMensaje).on("click", function(){

		modalMensaje.style.display = "flex";
		modalMensaje.style.display = "-ms-flexbox";
	});
	// Close Modal
	$(modalCloseMensaje).on("click", function(){

		modalMensaje.style.display = "none";
	});

	/**
	 * Click - Open Ver Capitulos
	 */
	$("body").on("click", '.ver-js-capitulos', function(){
		$(".nav-capitulos").toggleClass('nav-capitulos-toggle');
		$("body").css("overflow", "hidden");
	});

	/**
	 * Click - Open Ver Capitulos
	 */
	$("body").on("click", '.ver-js-capitulos-full', function(){
		$(".nav-capitulos").toggleClass('nav-capitulos-toggle');
	});

	/**
	 * Click - Close Ver Capitulos
	 */
	$('.close-nav-capitulos').click(function(){
		// $(this).toggleClass('open');
		$(".nav-capitulos").toggleClass('nav-capitulos-toggle');
		$("body").css("overflow", "auto");
	});

	/**
	 * asScrollbar (init - direction)
	 */
	Holder.run();
	$('.nav-scroll').asScrollable();
	$('.nav-scroll').on('asScrollable::scrolltop', function(e, api, direction) {
	console.info('top:' + direction);
	});
	$('.nav-scroll').on('asScrollable::scrollend', function(e, api, direction) {
	console.info('end:' + direction);
	});

	/**
	 * Click - Variables - Funcion para agrandar div y ver input[RANGE]
	 */
	var slider = document.querySelector(".ver-capitulo-options-texto-resize-slider"),
		estado = true;
	$(".ver-capitulo-options-texto-resize-icon").on("click", function(){

		if (estado) {
			slider.classList.add("ver-capitulo-options-texto-resize-slider-anim");
			$("#icon-resize").removeClass("ion-arrow-resize").addClass("ion-close-round");
			estado = false;
		} else {
			slider.classList.remove("ver-capitulo-options-texto-resize-slider-anim");
			$("#icon-resize").removeClass("ion-close-round").addClass("ion-arrow-resize");
			estado = true;
		}

	});

	/**
	 * Change - Input[RANGE] optener size y agrandar texto
	 */
	$(window).resize(function(){
		if ($(window).width() <= 767){
			$('.ver-capitulo-post-desc').css('font-size', "18px");
		} else {
			$('.ver-capitulo-post-desc').css('font-size', "28px");
		}
	});
	$( "#my-texto" ).change(function() {
		var x = document.getElementById("my-texto").value;
		$('.ver-capitulo-post-desc').css('font-size', x + "px");

		$('.ver-capitulo-post-desc').animate({fontSize: x + "px"}, 300);
	});

	/**
	 * Click - Modo de Lectura (FOCUS)
	 */
	$('.ver-capitulo-options-focus').click(function(){
		$("body").toggleClass('body-focus');
		$(".ver-capitulo").toggleClass('ver-capitulo-focus');
		$("footer").toggleClass('footer-focus');
	});

	/**
	 * Obtener alto de body
	 */
	bodysHeight = $("body").height();
	// alert(bodysHeight);

	/**
	 * Inicializar Popup Gallery
	 */
	$('.popup-gallery').magnificPopup({
		delegate: 'a',
		type: 'image',
		tLoading: 'Loading image #%curr%...',
		mainClass: 'mfp-img-mobile',
		gallery: {
			enabled: true,
			navigateByImgClick: true,
			preload: [0,1] // Will preload 0 - before current, and 1 after the current image
		},
		image: {
			tError: 'The image #%curr% could not be loaded.',
			titleSrc: function(item) {
				return item.el.attr('title');
			}
		}
	});

}); // end - READY

/**
 * ----------------------------
 *		Document Scroll
 * ----------------------------
 *
 * - Scroll
 *
 */
$(document).on("scroll", function(){
	/**
	 * Scroll - Listado, ocultar o mostar imagen
	 */
	var desplazamientoActual = $(document).scrollTop();
	if(desplazamientoActual > 100 ){
		$(".ver-capitulo-header").fadeTo( 18, 0.15 );
		$(".ver-capitulo-options").addClass("ver-capitulo-options-scroll");
		$(".cerrar-sesion").addClass("cerrar-sesion-scroll");
		$(".ver-capitulo-back").addClass("ver-capitulo-back-scroll");
		$(".ver-capitulos").addClass("ver-capitulos-scroll");
	}
	else{
		$(".ver-capitulo-header").fadeTo( 10, 1 );
		$(".ver-capitulo-options").removeClass("ver-capitulo-options-scroll");
		$(".cerrar-sesion").removeClass("cerrar-sesion-scroll");
		$(".ver-capitulo-back").removeClass("ver-capitulo-back-scroll");
		$(".ver-capitulos").removeClass("ver-capitulos-scroll");
	}

	// if(desplazamientoActual >100){
	// 	bodysHeight
	// }
});

/**
 * ----------------------------
 *		Click Window
 * ----------------------------
 *
 * - Modal
 *
 */
window.onclick = function(event) {
	// Modal Agregar - Close
	if (event.target == modal) {
		modal.style.display = "none";
	}
	// Modal Mensaje - Close
	if (event.target == modalMensaje) {
		modalMensaje.style.display = "none";
	}
}
<commit_msg>agregado<commit_after>/**
 * Proyecto
 *
 * # author      Damián <@damian>
 * # copyright   Copyright (c) 2016, Proyecto
 *
 */

/**
 * ----------------------------
 *		Variables
 * ----------------------------
 *
 * - Modal
 *
 */

// Modal - Agregar
var modal = document.getElementById('modal-agregar-post');
var modalOpen = document.getElementById("modal-agregar-post-open");
// var modalClose = document.getElementById("modal-agregar-post-close");

// Modal - Mensaje
var modalMensaje = document.getElementById('modal-mensaje');
var modalOpenMensaje = document.getElementById("modal-mensaje-open");
var modalCloseMensaje = document.getElementsByClassName("modal-mensaje-close");

// Body Alto
var bodysHeight = 0;

/**
 * ----------------------------
 *		Document Ready
 * ----------------------------
 *
 * - Animsition
 * - Ladda
 * - Modal
 *
 */
$(document).ready(function(){

	/**
	 * Animsition
	 */
	$('.animsition').animsition();

	$('.ver-capitulos').addClass("ver-js-capitulos");

	/**
	 * Ladda
	 */

	$('.home-article-button').click(function(e){
		var l = Ladda.create(this);
		l.start();
	});

	/**
	 * Modal
	 */
	// Open Modal
	$(modalOpen).on("click", function(){
		modal.style.display = "flex";
		modal.style.display = "-ms-flexbox";
	});

	/**
	 * Animate - Login elementos
	 */
	$(".login-cont .animated").animate({ "opacity": "0" }, 0, function() {
		$(".login-cont").show();
		$(".login-cont .animated").each(function(index) {$( this ).addClass("delay-"+(index)+" fadeInUp");});
	});

	/**
	 * Cambio de color - White
	 */
	$('.ver-capitulo-leer').on("click", function(){
		$('body').toggleClass("body-white");
		$('.ver-capitulo').toggleClass("ver-capitulo-white");
		$('footer').toggleClass("footer-white");
	});

	/**
	 * Click view Full
	 */
	$('.ver-capitulo-full-screen').on("click", function(){

		// $(".ver-capitulo").removeClass("ver-capitulo-white");

		// var heightScreen = $( window ).height();
		// alert(heightScreen);

		// $('.ver-capitulo-full-screen').fadeOut();
		// $('.ver-capitulo-full-screen').fadeOut();
		$('.ver-capitulo-full-screen').hide();
		$('.ver-capitulo-close-screen').css("display", "flex");
		$('.ver-capitulo-close-screen').css("display", "-ms-flexbox");
		$('.ver-capitulo').fullscreen();
		$(".ver-capitulo").addClass("ver-capitulo-full");

		// $(".asScrollable-container").css("height", heightScreen + "px");

		$(".asScrollable-container").toggleClass("asScrollable-container-full");
		$(".asScrollable-bar-vertical").delay(400).css("height", "calc(100vh - 10px)");

		$('.ver-capitulos').removeClass("ver-js-capitulos");
		$(".ver-capitulos").addClass("ver-js-capitulos-full");
		// $(".nav-capitulos-cont").delay(400).css("height", "100vh");

		// $(".ver-capitulo-leer").fadeOut();
		// $(".ver-capitulo-leer-full").fadeIn();

		// $('body').toggleClass("body-white");
		// $('footer').toggleClass("footer-white");

	});

	/**
	 * Click close Full
	 */
	$('.ver-capitulo-close-screen').on("click", function(){

		// $('.ver-capitulo-full-screen').fadeIn();
		// $('.ver-capitulo-close-screen').fadeOut();
		$('.ver-capitulo-full-screen').css("display", "flex");
		$('.ver-capitulo-full-screen').css("display", "-ms-flexbox");
		$('.ver-capitulo-close-screen').hide();
		$(".ver-capitulo").removeClass("ver-capitulo-full");

		$(".asScrollable-container").toggleClass("asScrollable-container-full");
		$(".asScrollable-bar-vertical").delay(400).css("height", "calc(100vh - 10px)");

		$('.ver-capitulos').addClass("ver-js-capitulos");
		$(".ver-capitulos").removeClass("ver-js-capitulos-full");

		// $(".asScrollable-bar-vertical").delay(400).css("height", "100vh");
		// $(".nav-capitulos-cont").delay(400).css("height", "100%");

		$.fullscreen.exit();

	});

	/**
	 * Click close Full (ESC)
	 */
	$(document).keyup(function (e) {
		if (e.keyCode == 27) {

			// $('.ver-capitulo-full-screen').fadeIn();
			// $('.ver-capitulo-close-screen').fadeOut();
			$('.ver-capitulo-full-screen').css("display", "flex");
			$('.ver-capitulo-full-screen').css("display", "-ms-flexbox");
			$('.ver-capitulo-close-screen').hide();
			$(".ver-capitulo").removeClass("ver-capitulo-full");

			$(".asScrollable-container").toggleClass("asScrollable-container-full");
			$(".asScrollable-bar-vertical").delay(400).css("height", "calc(100vh - 10px)");

			$('.ver-capitulos').addClass("ver-js-capitulos");
			$(".ver-capitulos").removeClass("ver-js-capitulos-full");

			// $(".asScrollable-bar-vertical").delay(400).css("height", "100vh");
			// $(".nav-capitulos-cont").delay(400).css("height", "100%");

			$.fullscreen.exit();

		}
	});

	/**
	 * Cambio de color - White
	 */
	$('.ver-capitulo-leer-full').on("click", function(){
		$('.ver-capitulo').toggleClass("ver-capitulo-white-full");
	});

	/**
	 * Modal - Mensaje
	 */
	// Open Modal
	$(modalOpenMensaje).on("click", function(){

		modalMensaje.style.display = "flex";
		modalMensaje.style.display = "-ms-flexbox";
	});
	// Close Modal
	$(modalCloseMensaje).on("click", function(){

		modalMensaje.style.display = "none";
	});

	/**
	 * Click - Open Ver Capitulos
	 */
	$("body").on("click", '.ver-js-capitulos', function(){
		$(".nav-capitulos").toggleClass('nav-capitulos-toggle');
		$("body").css("overflow", "hidden");
	});

	/**
	 * Click - Open Ver Capitulos
	 */
	$("body").on("click", '.ver-js-capitulos-full', function(){
		$(".nav-capitulos").toggleClass('nav-capitulos-toggle');
	});

	/**
	 * Click - Close Ver Capitulos
	 */
	$('.close-nav-capitulos').click(function(){
		// $(this).toggleClass('open');
		$(".nav-capitulos").toggleClass('nav-capitulos-toggle');
		$("body").css("overflow", "auto");
	});

	/**
	 * asScrollbar (init - direction)
	 */
	Holder.run();
	$('.nav-scroll').asScrollable();
	$('.nav-scroll').on('asScrollable::scrolltop', function(e, api, direction) {
	console.info('top:' + direction);
	});
	$('.nav-scroll').on('asScrollable::scrollend', function(e, api, direction) {
	console.info('end:' + direction);
	});

	/**
	 * Click - Variables - Funcion para agrandar div y ver input[RANGE]
	 */
	var slider = document.querySelector(".ver-capitulo-options-texto-resize-slider"),
		estado = true;
	$(".ver-capitulo-options-texto-resize-icon").on("click", function(){

		if (estado) {
			slider.classList.add("ver-capitulo-options-texto-resize-slider-anim");
			$("#icon-resize").removeClass("ion-arrow-resize").addClass("ion-close-round");
			estado = false;
		} else {
			slider.classList.remove("ver-capitulo-options-texto-resize-slider-anim");
			$("#icon-resize").removeClass("ion-close-round").addClass("ion-arrow-resize");
			estado = true;
		}

	});

	$('.ver-capitulo-post-desc').css('font-size', "28px");
	/**
	 * Change - Input[RANGE] optener size y agrandar texto
	 */
	$(window).resize(function(){
		if ($(window).width() <= 767){
			$('.ver-capitulo-post-desc').css('font-size', "18px");
		} else {
			$('.ver-capitulo-post-desc').css('font-size', "28px");
		}
	});
	$( "#my-texto" ).change(function() {
		var x = document.getElementById("my-texto").value;
		$('.ver-capitulo-post-desc').css('font-size', x + "px");

		$('.ver-capitulo-post-desc').animate({fontSize: x + "px"}, 300);
	});

	/**
	 * Click - Modo de Lectura (FOCUS)
	 */
	$('.ver-capitulo-options-focus').click(function(){
		$("body").toggleClass('body-focus');
		$(".ver-capitulo").toggleClass('ver-capitulo-focus');
		$("footer").toggleClass('footer-focus');
	});

	/**
	 * Obtener alto de body
	 */
	bodysHeight = $("body").height();
	// alert(bodysHeight);

	/**
	 * Inicializar Popup Gallery
	 */
	$('.popup-gallery').magnificPopup({
		delegate: 'a',
		type: 'image',
		tLoading: 'Loading image #%curr%...',
		mainClass: 'mfp-img-mobile',
		gallery: {
			enabled: true,
			navigateByImgClick: true,
			preload: [0,1] // Will preload 0 - before current, and 1 after the current image
		},
		image: {
			tError: 'The image #%curr% could not be loaded.',
			titleSrc: function(item) {
				return item.el.attr('title');
			}
		}
	});

}); // end - READY

/**
 * ----------------------------
 *		Document Scroll
 * ----------------------------
 *
 * - Scroll
 *
 */
$(document).on("scroll", function(){
	/**
	 * Scroll - Listado, ocultar o mostar imagen
	 */
	var desplazamientoActual = $(document).scrollTop();
	if(desplazamientoActual > 100 ){
		$(".ver-capitulo-header").fadeTo( 18, 0.15 );
		$(".ver-capitulo-options").addClass("ver-capitulo-options-scroll");
		$(".cerrar-sesion").addClass("cerrar-sesion-scroll");
		$(".ver-capitulo-back").addClass("ver-capitulo-back-scroll");
		$(".ver-capitulos").addClass("ver-capitulos-scroll");
	}
	else{
		$(".ver-capitulo-header").fadeTo( 10, 1 );
		$(".ver-capitulo-options").removeClass("ver-capitulo-options-scroll");
		$(".cerrar-sesion").removeClass("cerrar-sesion-scroll");
		$(".ver-capitulo-back").removeClass("ver-capitulo-back-scroll");
		$(".ver-capitulos").removeClass("ver-capitulos-scroll");
	}

	// if(desplazamientoActual >100){
	// 	bodysHeight
	// }
});

/**
 * ----------------------------
 *		Click Window
 * ----------------------------
 *
 * - Modal
 *
 */
window.onclick = function(event) {
	// Modal Agregar - Close
	if (event.target == modal) {
		modal.style.display = "none";
	}
	// Modal Mensaje - Close
	if (event.target == modalMensaje) {
		modalMensaje.style.display = "none";
	}
}
<|endoftext|>


<commit_before><commit_msg>fix(waves): revert amd workaround, call Waves.attact again<commit_after><|endoftext|>


<commit_before>odoo.define("web_gantt8.gantt", function(require) {
    "use strict";
    /* global GanttProjectInfo,GanttTaskInfo,GanttTaskInfo,GanttChart*/
    var core = require("web.core");
    var View = require("web.View");
    var Model = require("web.DataModel");
    var formats = require("web.formats");
    var time = require("web.time");
    var parse_value = require("web.web_client");
    var form_common = require("web.form_common");

    var _lt = core._lt;
    var QWeb = core.qweb;

    var GanttView = View.extend({
        display_name: _lt("Gantt"),
        template: "GanttView",
        view_type: "gantt8",
        icon: "fa-tasks",
        init: function() {
            this._super.apply(this, arguments);
            this.has_been_loaded = $.Deferred();
            this.chart_id = _.uniqueId();
        },
        willStart: function() {
            var self = this;
            this.$el.addClass(this.fields_view.arch.attrs.class);
            return self
                .alive(new Model(this.dataset.model).call("fields_get"))
                .then(function(fields) {
                    self.fields = fields;
                    self.has_been_loaded.resolve();
                });
        },
        do_search: function(domains, contexts, group_bys) {
            var self = this;
            self.last_domains = domains;
            self.last_contexts = contexts;
            self.last_group_bys = group_bys;
            // Select the group by
            var n_group_bys = [];
            if (this.fields_view.arch.attrs.default_group_by) {
                n_group_bys = this.fields_view.arch.attrs.default_group_by.split(",");
            }
            if (group_bys.length) {
                n_group_bys = group_bys;
            }
            // Gather the fields to get
            var fields = _.compact(
                _.map(["date_start", "date_delay", "date_stop", "progress"], function(
                    key
                ) {
                    return self.fields_view.arch.attrs[key] || "";
                })
            );
            fields = _.uniq(fields.concat(n_group_bys));

            return $.when(this.has_been_loaded).then(function() {
                return self.dataset
                    .read_slice(fields, {
                        domain: domains,
                        context: contexts,
                    })
                    .then(function(data) {
                        return self.on_data_loaded(data, n_group_bys);
                    });
            });
        },
        reload: function() {
            if (typeof this.last_domains !== "undefined") {
                return this.do_search(
                    this.last_domains,
                    this.last_contexts,
                    this.last_group_bys
                );
            }
        },
        on_data_loaded: function(tasks, group_bys) {
            var self = this;
            var ids = _.pluck(tasks, "id");
            return this.dataset.name_get(ids).then(function(names) {
                var ntasks = _.map(tasks, function(task) {
                    return _.extend(
                        {
                            __name: _.detect(names, function(name) {
                                return name[0] === task.id;
                            })[1],
                        },
                        task
                    );
                });
                return self.on_data_loaded_2(ntasks, group_bys);
            });
        },
        on_data_loaded_2: function(tasks, group_bys_arg) {
            var group_bys = group_bys_arg;
            var self = this;
            $(".oe_gantt", this.$el).html("");

            // Prevent more that 1 group by
            if (group_bys.length > 0) {
                group_bys = [group_bys[0]];
            }
            // If there is no group by, simulate it
            if (group_bys.length === 0) {
                group_bys = ["_pseudo_group_by"];
                _.each(tasks, function(el) {
                    el._pseudo_group_by = "Gantt View";
                });
                this.fields._pseudo_group_by = {type: "string"};
            }

            // Get the groups
            var split_groups = function(tasks_, group_bys_) {
                if (group_bys_.length === 0) {
                    return tasks_;
                }
                var groups = [];
                _.each(tasks_, function(task) {
                    var group_name = task[_.first(group_bys_)];
                    var group = _.find(groups, function(group_) {
                        return _.isEqual(group_.name, group_name);
                    });
                    if (typeof group === "undefined") {
                        group = {name: group_name, tasks_: [], __is_group: true};
                        groups.push(group);
                    }
                    group.tasks.push(task);
                });
                _.each(groups, function(group) {
                    group.tasks = split_groups(group.tasks, _.rest(group_bys_));
                });
                return groups;
            };
            var groups = split_groups(tasks, group_bys);

            // Track ids of task items for context menu
            var task_ids = {};
            // Creation of the chart
            var generate_task_info = function(task, plevel) {
                var percent = 100;
                if (_.isNumber(task[self.fields_view.arch.attrs.progress])) {
                    percent = task[self.fields_view.arch.attrs.progress] || 0;
                }
                var level = plevel || 0;
                if (task.__is_group) {
                    var task_infos = _.compact(
                        _.map(task.tasks, function(sub_task) {
                            return generate_task_info(sub_task, level + 1);
                        })
                    );
                    if (task_infos.length === 0) {
                        return;
                    }
                    var task_start = _.reduce(_.pluck(task_infos, "task_start"), function(
                        date,
                        memo
                    ) {
                        return typeof memo === "undefined" || date < memo ? date : memo;
                    });
                    var task_stop = _.reduce(_.pluck(task_infos, "task_stop"), function(
                        date,
                        memo
                    ) {
                        return typeof memo === "undefined" || date > memo ? date : memo;
                    });
                    var duration =
                        (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                    var group_name = task.name
                        ? formats.format_value(task.name, self.fields[group_bys[level]])
                        : "-";
                    var group = null;
                    if (level === 0) {
                        group = new GanttProjectInfo(
                            _.uniqueId("gantt_project_"),
                            group_name,
                            task_start
                        );
                        _.each(task_infos, function(el) {
                            group.addTask(el.task_info);
                        });
                        return group;
                    }
                    group = new GanttTaskInfo(
                        _.uniqueId("gantt_project_task_"),
                        group_name,
                        task_start,
                        duration || 1,
                        percent
                    );
                    _.each(task_infos, function(el) {
                        group.addChildTask(el.task_info);
                    });
                    return {
                        task_info: group,
                        task_start: task_start,
                        task_stop: task_stop,
                    };
                }
                var task_name = task.__name;
                var duration_in_business_hours = false;
                task_start = time.auto_str_to_date(
                    task[self.fields_view.arch.attrs.date_start]
                );
                if (!task_start) {
                    return;
                }
                if (self.fields_view.arch.attrs.date_stop) {
                    task_stop = time.auto_str_to_date(
                        task[self.fields_view.arch.attrs.date_stop]
                    );
                    if (!task_stop) {
                        task_stop = task_start;
                    }
                } else {
                    // We assume date_duration is defined
                    var tmp = formats.format_value(
                        task[self.fields_view.arch.attrs.date_delay],
                        self.fields[self.fields_view.arch.attrs.date_delay]
                    );
                    if (!tmp) {
                        return;
                    }
                    task_stop = new Date(task_start);
                    task_stop.setMilliseconds(
                        parse_value(tmp, {type: "float"}) * 60 * 60 * 1000
                    );
                    duration_in_business_hours = true;
                }
                duration =
                    (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var id = _.uniqueId("gantt_task_");
                if (!duration_in_business_hours) {
                    duration = (duration / 24) * 8;
                }
                var task_info = new GanttTaskInfo(
                    id,
                    task_name,
                    task_start,
                    duration || 1,
                    percent
                );
                task_info.internal_task = task;
                task_ids[id] = task_info;
                return {
                    task_info: task_info,
                    task_start: task_start,
                    task_stop: task_stop,
                };
            };
            var $div = $("

");
            $div.css("min-height", 500);
            $div.prependTo(document.body);
            var gantt = new GanttChart();
            gantt.maxWidthPanelNames = 250;
            _.each(
                _.compact(
                    _.map(groups, function(e) {
                        return generate_task_info(e, 0);
                    })
                ),
                function(project) {
                    gantt.addProject(project);
                }
            );
            gantt.setEditable(true);
            gantt.setImagePath("/web_gantt8/static/lib/dhtmlxGantt/codebase/imgs/");
            gantt.attachEvent("onTaskEndDrag", function(task) {
                self.on_task_changed(task);
            });
            gantt.attachEvent("onTaskEndResize", function(task) {
                self.on_task_changed(task);
            });
            gantt.create(this.chart_id);
            this.$el.children().append($div.contents());
            $div.remove();

            // Bind event to display task when we click the item in the tree
            $(".taskNameItem", self.$el).click(function(event) {
                var task_info = task_ids[event.target.id];
                if (task_info) {
                    self.on_task_display(task_info.internal_task);
                }
            });
            if (this.is_action_enabled("create")) {
                // Insertion of create button
                var td = $($("table td", self.$el)[0]);
                var rendered = QWeb.render("GanttView-create-button");
                $(rendered).prependTo(td);
                $(".oe_gantt_button_create", this.$el).click(this.on_task_create);
            }
            // Fix for IE to display the content of gantt view.
            this.$el
                .find(".oe_gantt td:first > div, .oe_gantt td:eq(1) > div > div")
                .css("overflow", "");
        },
        on_task_changed: function(task_obj) {
            var self = this;
            var itask = task_obj.TaskInfo.internal_task;
            var start = task_obj.getEST();
            var duration = task_obj.getDuration();
            var duration_in_business_hours = Boolean(
                self.fields_view.arch.attrs.date_delay
            );
            if (!duration_in_business_hours) {
                duration = (duration / 8) * 24;
            }
            var end = new Date(start);
            end.setMilliseconds(duration * 60 * 60 * 1000);
            var data = {};
            data[self.fields_view.arch.attrs.date_start] = time.auto_date_to_str(
                start,
                self.fields[self.fields_view.arch.attrs.date_start].type
            );
            if (self.fields_view.arch.attrs.date_stop) {
                data[self.fields_view.arch.attrs.date_stop] = time.auto_date_to_str(
                    end,
                    self.fields[self.fields_view.arch.attrs.date_stop].type
                );
            } else {
                // We assume date_duration is defined
                data[self.fields_view.arch.attrs.date_delay] = duration;
            }
            this.dataset.write(itask.id, data);
        },
        on_task_display: function(task) {
            var self = this;
            var pop = new form_common.FormViewDialog(self, {
                res_model: self.dataset.model,
                res_id: task.id,
            }).open();
            pop.on("write_completed", self, function() {
                self.reload();
            });
        },
        on_task_create: function() {
            var self = this;
            new form_common.SelectCreateDialog(this, {
                res_model: self.dataset.model,
                initial_view: "form",
                on_selected: function() {
                    self.reload();
                },
            }).open();
        },
    });
    core.view_registry.add("gantt8", GanttView);
});
<commit_msg>:green_heart: pre-commit: auto cleanups<commit_after>odoo.define("web_gantt8.gantt", function(require) {
    "use strict";
    /* global GanttProjectInfo,GanttTaskInfo,GanttTaskInfo,GanttChart*/
    var core = require("web.core");
    var View = require("web.View");
    var Model = require("web.DataModel");
    var formats = require("web.formats");
    var time = require("web.time");
    var parse_value = require("web.web_client");
    var form_common = require("web.form_common");

    var _lt = core._lt;
    var QWeb = core.qweb;

    var GanttView = View.extend({
        display_name: _lt("Gantt"),
        template: "GanttView",
        view_type: "gantt8",
        icon: "fa-tasks",
        init: function() {
            this._super.apply(this, arguments);
            this.has_been_loaded = $.Deferred();
            this.chart_id = _.uniqueId();
        },
        willStart: function() {
            var self = this;
            this.$el.addClass(this.fields_view.arch.attrs.class);
            return self
                .alive(new Model(this.dataset.model).call("fields_get"))
                .then(function(fields) {
                    self.fields = fields;
                    self.has_been_loaded.resolve();
                });
        },
        do_search: function(domains, contexts, group_bys) {
            var self = this;
            self.last_domains = domains;
            self.last_contexts = contexts;
            self.last_group_bys = group_bys;
            // Select the group by
            var n_group_bys = [];
            if (this.fields_view.arch.attrs.default_group_by) {
                n_group_bys = this.fields_view.arch.attrs.default_group_by.split(",");
            }
            if (group_bys.length) {
                n_group_bys = group_bys;
            }
            // Gather the fields to get
            var fields = _.compact(
                _.map(["date_start", "date_delay", "date_stop", "progress"], function(
                    key
                ) {
                    return self.fields_view.arch.attrs[key] || "";
                })
            );
            fields = _.uniq(fields.concat(n_group_bys));

            return $.when(this.has_been_loaded).then(function() {
                return self.dataset
                    .read_slice(fields, {
                        domain: domains,
                        context: contexts,
                    })
                    .then(function(data) {
                        return self.on_data_loaded(data, n_group_bys);
                    });
            });
        },
        reload: function() {
            if (typeof this.last_domains !== "undefined") {
                return this.do_search(
                    this.last_domains,
                    this.last_contexts,
                    this.last_group_bys
                );
            }
        },
        on_data_loaded: function(tasks, group_bys) {
            var self = this;
            var ids = _.pluck(tasks, "id");
            return this.dataset.name_get(ids).then(function(names) {
                var ntasks = _.map(tasks, function(task) {
                    return _.extend(
                        {
                            __name: _.detect(names, function(name) {
                                return name[0] === task.id;
                            })[1],
                        },
                        task
                    );
                });
                return self.on_data_loaded_2(ntasks, group_bys);
            });
        },
        on_data_loaded_2: function(tasks, group_bys_arg) {
            var group_bys = group_bys_arg;
            var self = this;
            $(".oe_gantt", this.$el).html("");

            // Prevent more that 1 group by
            if (group_bys.length > 0) {
                group_bys = [group_bys[0]];
            }
            // If there is no group by, simulate it
            if (group_bys.length === 0) {
                group_bys = ["_pseudo_group_by"];
                _.each(tasks, function(el) {
                    el._pseudo_group_by = "Gantt View";
                });
                this.fields._pseudo_group_by = {type: "string"};
            }

            // Get the groups
            var split_groups = function(tasks_, group_bys_) {
                if (group_bys_.length === 0) {
                    return tasks_;
                }
                var groups = [];
                _.each(tasks_, function(task) {
                    var group_name = task[_.first(group_bys_)];
                    var group = _.find(groups, function(group_) {
                        return _.isEqual(group_.name, group_name);
                    });
                    if (typeof group === "undefined") {
                        group = {name: group_name, tasks_: [], __is_group: true};
                        groups.push(group);
                    }
                    group.tasks.push(task);
                });
                _.each(groups, function(group) {
                    group.tasks = split_groups(group.tasks, _.rest(group_bys_));
                });
                return groups;
            };
            var groups = split_groups(tasks, group_bys);

            // Track ids of task items for context menu
            var task_ids = {};
            // Creation of the chart
            var generate_task_info = function(task, plevel) {
                var percent = 100;
                if (_.isNumber(task[self.fields_view.arch.attrs.progress])) {
                    percent = task[self.fields_view.arch.attrs.progress] || 0;
                }
                var level = plevel || 0;
                if (task.__is_group) {
                    var task_infos = _.compact(
                        _.map(task.tasks, function(sub_task) {
                            return generate_task_info(sub_task, level + 1);
                        })
                    );
                    if (task_infos.length === 0) {
                        return;
                    }
                    var task_start = _.reduce(
                        _.pluck(task_infos, "task_start"),
                        function(date, memo) {
                            return typeof memo === "undefined" || date < memo
                                ? date
                                : memo;
                        }
                    );
                    var task_stop = _.reduce(_.pluck(task_infos, "task_stop"), function(
                        date,
                        memo
                    ) {
                        return typeof memo === "undefined" || date > memo ? date : memo;
                    });
                    var duration =
                        (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                    var group_name = task.name
                        ? formats.format_value(task.name, self.fields[group_bys[level]])
                        : "-";
                    var group = null;
                    if (level === 0) {
                        group = new GanttProjectInfo(
                            _.uniqueId("gantt_project_"),
                            group_name,
                            task_start
                        );
                        _.each(task_infos, function(el) {
                            group.addTask(el.task_info);
                        });
                        return group;
                    }
                    group = new GanttTaskInfo(
                        _.uniqueId("gantt_project_task_"),
                        group_name,
                        task_start,
                        duration || 1,
                        percent
                    );
                    _.each(task_infos, function(el) {
                        group.addChildTask(el.task_info);
                    });
                    return {
                        task_info: group,
                        task_start: task_start,
                        task_stop: task_stop,
                    };
                }
                var task_name = task.__name;
                var duration_in_business_hours = false;
                task_start = time.auto_str_to_date(
                    task[self.fields_view.arch.attrs.date_start]
                );
                if (!task_start) {
                    return;
                }
                if (self.fields_view.arch.attrs.date_stop) {
                    task_stop = time.auto_str_to_date(
                        task[self.fields_view.arch.attrs.date_stop]
                    );
                    if (!task_stop) {
                        task_stop = task_start;
                    }
                } else {
                    // We assume date_duration is defined
                    var tmp = formats.format_value(
                        task[self.fields_view.arch.attrs.date_delay],
                        self.fields[self.fields_view.arch.attrs.date_delay]
                    );
                    if (!tmp) {
                        return;
                    }
                    task_stop = new Date(task_start);
                    task_stop.setMilliseconds(
                        parse_value(tmp, {type: "float"}) * 60 * 60 * 1000
                    );
                    duration_in_business_hours = true;
                }
                duration =
                    (task_stop.getTime() - task_start.getTime()) / (1000 * 60 * 60);
                var id = _.uniqueId("gantt_task_");
                if (!duration_in_business_hours) {
                    duration = (duration / 24) * 8;
                }
                var task_info = new GanttTaskInfo(
                    id,
                    task_name,
                    task_start,
                    duration || 1,
                    percent
                );
                task_info.internal_task = task;
                task_ids[id] = task_info;
                return {
                    task_info: task_info,
                    task_start: task_start,
                    task_stop: task_stop,
                };
            };
            var $div = $("

");
            $div.css("min-height", 500);
            $div.prependTo(document.body);
            var gantt = new GanttChart();
            gantt.maxWidthPanelNames = 250;
            _.each(
                _.compact(
                    _.map(groups, function(e) {
                        return generate_task_info(e, 0);
                    })
                ),
                function(project) {
                    gantt.addProject(project);
                }
            );
            gantt.setEditable(true);
            gantt.setImagePath("/web_gantt8/static/lib/dhtmlxGantt/codebase/imgs/");
            gantt.attachEvent("onTaskEndDrag", function(task) {
                self.on_task_changed(task);
            });
            gantt.attachEvent("onTaskEndResize", function(task) {
                self.on_task_changed(task);
            });
            gantt.create(this.chart_id);
            this.$el.children().append($div.contents());
            $div.remove();

            // Bind event to display task when we click the item in the tree
            $(".taskNameItem", self.$el).click(function(event) {
                var task_info = task_ids[event.target.id];
                if (task_info) {
                    self.on_task_display(task_info.internal_task);
                }
            });
            if (this.is_action_enabled("create")) {
                // Insertion of create button
                var td = $($("table td", self.$el)[0]);
                var rendered = QWeb.render("GanttView-create-button");
                $(rendered).prependTo(td);
                $(".oe_gantt_button_create", this.$el).click(this.on_task_create);
            }
            // Fix for IE to display the content of gantt view.
            this.$el
                .find(".oe_gantt td:first > div, .oe_gantt td:eq(1) > div > div")
                .css("overflow", "");
        },
        on_task_changed: function(task_obj) {
            var self = this;
            var itask = task_obj.TaskInfo.internal_task;
            var start = task_obj.getEST();
            var duration = task_obj.getDuration();
            var duration_in_business_hours = Boolean(
                self.fields_view.arch.attrs.date_delay
            );
            if (!duration_in_business_hours) {
                duration = (duration / 8) * 24;
            }
            var end = new Date(start);
            end.setMilliseconds(duration * 60 * 60 * 1000);
            var data = {};
            data[self.fields_view.arch.attrs.date_start] = time.auto_date_to_str(
                start,
                self.fields[self.fields_view.arch.attrs.date_start].type
            );
            if (self.fields_view.arch.attrs.date_stop) {
                data[self.fields_view.arch.attrs.date_stop] = time.auto_date_to_str(
                    end,
                    self.fields[self.fields_view.arch.attrs.date_stop].type
                );
            } else {
                // We assume date_duration is defined
                data[self.fields_view.arch.attrs.date_delay] = duration;
            }
            this.dataset.write(itask.id, data);
        },
        on_task_display: function(task) {
            var self = this;
            var pop = new form_common.FormViewDialog(self, {
                res_model: self.dataset.model,
                res_id: task.id,
            }).open();
            pop.on("write_completed", self, function() {
                self.reload();
            });
        },
        on_task_create: function() {
            var self = this;
            new form_common.SelectCreateDialog(this, {
                res_model: self.dataset.model,
                initial_view: "form",
                on_selected: function() {
                    self.reload();
                },
            }).open();
        },
    });
    core.view_registry.add("gantt8", GanttView);
});
<|endoftext|>


<commit_before>import m from 'mithril';
import I18n from 'i18n-js';
import {
    catarse
} from '../api';
import _ from 'underscore';
import models from '../models';
import h from '../h';

const I18nScope = _.partial(h.i18nScope, 'projects.posts');

const projectPosts = {
    controller(args) {
        const listVM = catarse.paginationVM(models.projectPostDetail),
            filterVM = catarse.filtersVM({
                project_id: 'eq',
                id: 'eq'
            });
        const scrollTo = (el, isInit) => {
            if (!isInit) {
                h.animateScrollTo(el);
            }
        };

        filterVM.project_id(args.project().project_id);

        if (_.isNumber(args.post_id)) {
            filterVM.id(args.post_id);
        }

        if (!listVM.collection().length) {
            listVM.firstPage(filterVM.parameters());
        }

        return {
            listVM,
            filterVM,
            scrollTo
        };
    },
    view(ctrl, args) {
        const list = ctrl.listVM,
            project = args.project() || {};

        return m('#posts.project-posts.w-section', {
            config: ctrl.scrollTo
        }, [
            m('.w-container.u-margintop-20', [
                (project.is_owner_or_admin ? [
                    (!list.isLoading()) ?
                    (_.isEmpty(list.collection()) ? m('.w-hidden-small.w-hidden-tiny', [
                        m('.fontsize-base.u-marginbottom-30.u-margintop-20', 'Toda novidade publicada no Catarse é enviada diretamente para o email de quem já apoiou seu projeto e também fica disponível para visualização no site. Você pode optar por deixá-la pública, ou visível somente para seus apoiadores aqui nesta aba.')
                    ]) : '') : '',
                    m('.w-row.u-marginbottom-20', [
                        m('.w-col.w-col-4.w-col-push-4', [
                            m(`a.btn.btn-edit.btn-small[href='/pt/projects/${project.project_id}/posts']`, 'Escrever novidade')
                        ])
                    ])
                ] : ''), (_.map(list.collection(), post => m('.w-row', [
                    _.isEmpty(post.comment_html) ?
                    m('.card.card-message.u-radius.card-big.u-text-center.u-marginbottom-10', [
                        m('.fa.fa-lock.fa-3x.fontcolor-secondary',
                            ''
                        ),
                        project.mode === 'sub' ? [
                            m('.fontsize-base.fontweight-semibold.u-marginbottom-20',
                                `Post exclusivo para assinantes${post.reward_id ? ` da recompensa de R$${post.minimum_value}` : ''}`
                            ),
                            m(`a.btn.btn-medium.btn-inline.w-button[href="/projects/${post.project_id}/subscriptions/start${post.reward_id ? `?reward_id=${post.reward_id}` : ''}"]`,
                                'Acessar esse post'
                            )
                        ] : [
                            m('.fontsize-base.fontweight-semibold.u-marginbottom-20',
                                `Post exclusivo para apoiadores${post.reward_id ? ` da recompensa de R$${post.minimum_value}` : ''}`
                            ),
                            m(`a.btn.btn-medium.btn-inline.w-button[href="/projects/${post.project_id}/contributions/new${post.reward_id ? `?reward_id=${post.reward_id}` : ''}"]`,
                              'Acessar esse post'
                            )
                        ]

                    ]) : [m('.w-col.w-col-1'),
                        m('.w-col.w-col-10', [
                            m('.post', [
                                m('.u-marginbottom-60 .w-clearfix', [
                                    m('.fontsize-small.fontcolor-secondary.u-text-center', h.momentify(post.created_at)),
                                    m('p.fontweight-semibold.fontsize-larger.u-text-center.u-marginbottom-30', [
                                        m(`a.link-hidden[href="/projects/${post.project_id}/posts/${post.id}#posts"]`, post.title)
                                    ]),
                                    (m('.fontsize-base', m.trust(post.comment_html)))
                                ]),
                                m('.divider.u-marginbottom-60')
                            ])
                        ]),
                        m('.w-col.w-col-1')
                    ]
                ]))),
                m('.w-row', [
                    (!_.isUndefined(args.post_id) ? '' :
                        (!list.isLoading() ?
                            (list.collection().length === 0 && args.projectContributions().length === 0) ?
                            !project.is_owner_or_admin ? m('.w-col.w-col-10.w-col-push-1',
                                m('p.fontsize-base',
                                    m.trust(
                                        I18n.t('empty',
                                            I18nScope({
                                                project_user_name: args.userDetails().name,
                                                project_id: project.project_id
                                            })
                                        )
                                    )
                                )
                            ) : '' :
                            m('.w-col.w-col-2.w-col-push-5',
                                (list.isLastPage() ?
                                    list.collection().length === 0 ? 'Nenhuma novidade.' : '' :
                                    m('button#load-more.btn.btn-medium.btn-terciary', {
                                        onclick: list.nextPage
                                    }, 'Carregar mais'))
                            ) :
                            m('.w-col.w-col-2.w-col-push-5', h.loader())
                        ))

                ])
            ]),
        ]);
    }
};

export default projectPosts;
<commit_msg>show post title to all[#155056856]<commit_after>import m from 'mithril';
import I18n from 'i18n-js';
import {
    catarse
} from '../api';
import _ from 'underscore';
import models from '../models';
import h from '../h';

const I18nScope = _.partial(h.i18nScope, 'projects.posts');

const projectPosts = {
    controller(args) {
        const listVM = catarse.paginationVM(models.projectPostDetail),
            filterVM = catarse.filtersVM({
                project_id: 'eq',
                id: 'eq'
            });
        const scrollTo = (el, isInit) => {
            if (!isInit) {
                h.animateScrollTo(el);
            }
        };

        filterVM.project_id(args.project().project_id);

        if (_.isNumber(args.post_id)) {
            filterVM.id(args.post_id);
        }

        if (!listVM.collection().length) {
            listVM.firstPage(filterVM.parameters());
        }

        return {
            listVM,
            filterVM,
            scrollTo
        };
    },
    view(ctrl, args) {
        const list = ctrl.listVM,
            project = args.project() || {};

        return m('#posts.project-posts.w-section', {
            config: ctrl.scrollTo
        }, [
            m('.w-container.u-margintop-20', [
                (project.is_owner_or_admin ? [
                    (!list.isLoading()) ?
                    (_.isEmpty(list.collection()) ? m('.w-hidden-small.w-hidden-tiny', [
                        m('.fontsize-base.u-marginbottom-30.u-margintop-20', 'Toda novidade publicada no Catarse é enviada diretamente para o email de quem já apoiou seu projeto e também fica disponível para visualização no site. Você pode optar por deixá-la pública, ou visível somente para seus apoiadores aqui nesta aba.')
                    ]) : '') : '',
                    m('.w-row.u-marginbottom-20', [
                        m('.w-col.w-col-4.w-col-push-4', [
                            m(`a.btn.btn-edit.btn-small[href='/pt/projects/${project.project_id}/posts']`, 'Escrever novidade')
                        ])
                    ])
                ] : ''), (_.map(list.collection(), post => m('.w-row', [
                    _.isEmpty(post.comment_html) ? [
                        m('.fontsize-small.fontcolor-secondary.u-text-center', h.momentify(post.created_at)),
                        m('p.fontweight-semibold.fontsize-larger.u-text-center.u-marginbottom-30', [
                            m(`a.link-hidden[href="/projects/${post.project_id}/posts/${post.id}#posts"]`, post.title)
                        ]),
                        m('.card.card-message.u-radius.card-big.u-text-center.u-marginbottom-60', [
                            m('.fa.fa-lock.fa-3x.fontcolor-secondary',
                                ''
                            ),
                            project.mode === 'sub' ? [
                                m('.fontsize-base.fontweight-semibold.u-marginbottom-20',
                                    `Post exclusivo para assinantes${post.reward_id ? ` da recompensa de R$${post.minimum_value}` : ''}`
                                ),
                                m(`a.btn.btn-medium.btn-inline.w-button[href="/projects/${post.project_id}/subscriptions/start${post.reward_id ? `?reward_id=${post.reward_id}` : ''}"]`,
                                    'Acessar esse post'
                                )
                            ] : [
                                m('.fontsize-base.fontweight-semibold.u-marginbottom-20',
                                    `Post exclusivo para apoiadores${post.reward_id ? ` da recompensa de R$${post.minimum_value}` : ''}`
                                ),
                                m(`a.btn.btn-medium.btn-inline.w-button[href="/projects/${post.project_id}/contributions/new${post.reward_id ? `?reward_id=${post.reward_id}` : ''}"]`,
                                    'Acessar esse post'
                                )
                            ]

                        ])
                    ] : [m('.w-col.w-col-1'),
                        m('.w-col.w-col-10', [
                            m('.post', [
                                m('.u-marginbottom-60 .w-clearfix', [
                                    m('.fontsize-small.fontcolor-secondary.u-text-center', h.momentify(post.created_at)),
                                    m('p.fontweight-semibold.fontsize-larger.u-text-center.u-marginbottom-30', [
                                        m(`a.link-hidden[href="/projects/${post.project_id}/posts/${post.id}#posts"]`, post.title)
                                    ]),
                                    (m('.fontsize-base', m.trust(post.comment_html)))
                                ]),
                                m('.divider.u-marginbottom-60')
                            ])
                        ]),
                        m('.w-col.w-col-1')
                    ]
                ]))),
                m('.w-row', [
                    (!_.isUndefined(args.post_id) ? '' :
                        (!list.isLoading() ?
                            (list.collection().length === 0 && args.projectContributions().length === 0) ?
                            !project.is_owner_or_admin ? m('.w-col.w-col-10.w-col-push-1',
                                m('p.fontsize-base',
                                    m.trust(
                                        I18n.t('empty',
                                            I18nScope({
                                                project_user_name: args.userDetails().name,
                                                project_id: project.project_id
                                            })
                                        )
                                    )
                                )
                            ) : '' :
                            m('.w-col.w-col-2.w-col-push-5',
                                (list.isLastPage() ?
                                    list.collection().length === 0 ? 'Nenhuma novidade.' : '' :
                                    m('button#load-more.btn.btn-medium.btn-terciary', {
                                        onclick: list.nextPage
                                    }, 'Carregar mais'))
                            ) :
                            m('.w-col.w-col-2.w-col-push-5', h.loader())
                        ))

                ])
            ]),
        ]);
    }
};

export default projectPosts;
<|endoftext|>


<commit_before>var d3, graphChartProcessor, markdownItGraph, nvd3, uuid

markdownItGraph = require('./md_graph')

d3 = require('d3')
nvd3 = require('nvd3')
uuid = require('node-uuid')

parseInput = function (input) {}

graphChartProcessor = function (tokens, graph_template, error_template) {
  parseInput = function (input) {
    var code, out,
      code = '\
    function _plot(input) {\
      if (typeof(input) == "function")\
        return input();\
      return input;\
    }\
    function plot() {\
      _plotData = [];\
      for(var _i = 0; _i < arguments.length; _i++) {\
        _plotData.push(_plot(arguments[_i]));\
      }\
      return _plotData;\
    }' + input

    out = []
    try {
      out = eval(code)
    } catch (error) {
      throw 'Failed to parse chart plot javascript
' + error
    }
    var data = []
    var part, line, xyArray, len, len1
    for (var j = 0, len = out.length; j < len; j++) {
      part = out[j]
      line = []
      xyArray = []
      for (var k = 0, len1 = part.length; k < len1; k++) {
        i = part[k]
        xyArray.push({ x: i[0], y: i[1]})
      }
      data.push({ values: xyArray, seriesIndex: j, key: '' + j })
    }
    return data
  }
  return {
    parse: parseInput,
    register: function (mdInstance, postProcessors) {
      markdownItGraph(tokens).register(mdInstance, function (inputStr) {
        try {
          var data = parseInput(inputStr)
          var id = 'charts-dg-' + uuid.v4()
          postProcessors.registerElemenbById(id, function (elem, done) {
            var fnc, svgElem, svgHeight
            fnc = function () {
              var chart
              chart = nvd3.models.lineChart()
              chart.useInteractiveGuideline(false) // buggy
              d3.select(elem.childNodes[0]).datum(data).call(chart)
              nvd3.utils.windowResize(chart.update)
              return chart
            }
            nvd3.addGraph(fnc)
            svgElem = elem.getElementsByClassName('output')[0]
            svgHeight = (svgElem != null ? svgElem.getBoundingClientRect().height : void 0) || 0
            console.log(svgElem, elem)
            elem.style.height = 350
            return done()
          })
          return graph_template({
            id: id
          })
        } catch (error1) {
          return error_template({
            error: error1
          })
        }
      })
      return null
    }
  }
}

module.exports = graphChartProcessor
<commit_msg>Remove debug console.log<commit_after>var d3, graphChartProcessor, markdownItGraph, nvd3, uuid

markdownItGraph = require('./md_graph')

d3 = require('d3')
nvd3 = require('nvd3')
uuid = require('node-uuid')

parseInput = function (input) {}

graphChartProcessor = function (tokens, graph_template, error_template) {
  parseInput = function (input) {
    var code, out,
      code = '\
    function _plot(input) {\
      if (typeof(input) == "function")\
        return input();\
      return input;\
    }\
    function plot() {\
      _plotData = [];\
      for(var _i = 0; _i < arguments.length; _i++) {\
        _plotData.push(_plot(arguments[_i]));\
      }\
      return _plotData;\
    }' + input

    out = []
    try {
      out = eval(code)
    } catch (error) {
      throw 'Failed to parse chart plot javascript
' + error
    }
    var data = []
    var part, line, xyArray, len, len1
    for (var j = 0, len = out.length; j < len; j++) {
      part = out[j]
      line = []
      xyArray = []
      for (var k = 0, len1 = part.length; k < len1; k++) {
        i = part[k]
        xyArray.push({ x: i[0], y: i[1]})
      }
      data.push({ values: xyArray, seriesIndex: j, key: '' + j })
    }
    return data
  }
  return {
    parse: parseInput,
    register: function (mdInstance, postProcessors) {
      markdownItGraph(tokens).register(mdInstance, function (inputStr) {
        try {
          var data = parseInput(inputStr)
          var id = 'charts-dg-' + uuid.v4()
          postProcessors.registerElemenbById(id, function (elem, done) {
            var fnc, svgElem, svgHeight
            fnc = function () {
              var chart
              chart = nvd3.models.lineChart()
              chart.useInteractiveGuideline(false) // buggy
              d3.select(elem.childNodes[0]).datum(data).call(chart)
              nvd3.utils.windowResize(chart.update)
              return chart
            }
            nvd3.addGraph(fnc)
            svgElem = elem.getElementsByClassName('output')[0]
            svgHeight = (svgElem != null ? svgElem.getBoundingClientRect().height : void 0) || 0
            elem.style.height = 350
            return done()
          })
          return graph_template({
            id: id
          })
        } catch (error1) {
          return error_template({
            error: error1
          })
        }
      })
      return null
    }
  }
}

module.exports = graphChartProcessor
<|endoftext|>