<commit_before>walk(document.body);

function walk(node)
{
	// I stole this function from here:
	// http://is.gd/mwZp7E

	var child, next;

	switch ( node.nodeType )
	{
		case 1:  // Element
		case 9:  // Document
		case 11: // Document fragment
			child = node.firstChild;
			while ( child )
			{
				next = child.nextSibling;
				walk(child);
				child = next;
			}
			break;

		case 3: // Text node
			handleText(node);
			break;
	}
}

function handleText(textNode)
{
	var v = textNode.nodeValue;

	// Millennial
	v = v.replace(/\bMillennial\b/g, "Snake Person");
	v = v.replace(/\bmillennial\b/g, "snake person");
	v = v.replace(/\bMillennials\b/g, "Snake People");
	v = v.replace(/\bmillennials\b/g, "snake people");
	v = v.replace(/\bMillennials'\b/g, "Snake People's");
	v = v.replace(/\bmillennials'\b/g, "snake people's");
	v = v.replace(/\bMillienials\b/g, "Snake People"); 		// Common misspelling
	v = v.replace(/\bmillienials\b/g, "snake people"); 	 	// Common misspelling

	// The Great Recession
	v = v.replace(/\bGreat Recession\b/g, "Time of Shedding and Cold Rocks");
	v = v.replace(/\bgreat recession\b/g, "time of shedding and cold rocks");

	// The Great Depression
	v = v.replace(/\bGreat Depression\b/g, "Clutch Plague");
	v = v.replace(/\bgreat depression\b/g, "clutch plague");

	// Occupy Wall Street
	v = v.replace(/\bOccupy Wall Street\b/g, "Great Ape-Snake War");
	v = v.replace(/\boccupy wall street\b/g, "great ape-snake war");
	v = v.replace(/\bOccupy Movement\b/g, "Great Ape-Snake War");
	v = v.replace(/\boccupy movement\b/g, "great ape-snake war");
	v = v.replace(/\bOWS Movement\b/g, "Great Ape-Snake War");
	v = v.replace(/\bOWS movement\b/g, "great ape-snake war");
	v = v.replace(/\bows movement\b/g, "great ape-snake war");
	v = v.replace(/\b ows \b/g, " ga-sw ");
	v = v.replace(/\b OWS \b/g, " GA-SW ");

	// Helicopter Parents
	v = v.replace(/\bHelicopter Parents\b/g, "Thulsa Doom");
	v = v.replace(/\bhelicopter parents\b/g, "Thoth-Amon");
	v = v.replace(/\bHelicopter Parents'\b/g, "Thulsa Doom's");
	v = v.replace(/\bhelicopter parents'\b/g, "Thoth-Amon's");

	// Trophy Kids
	v = v.replace(/\bTrophy Kids\b/g, "Quetzalcoatl's Chosen");
	v = v.replace(/\btrophy kids\b/g, "Quetzalcoatl's chosen");
	v = v.replace(/\bTrophy Kids'\b/g, "Quetzalcoatl's Chosen's");
	v = v.replace(/\btrophy kids'\b/g, "Quetzalcoatl's chosen's");

	// Digital Natives
	v = v.replace(/\bDigital Native\b/g, "Parseltongue");
	v = v.replace(/\bDigital Natives\b/g, "Parseltongues");
	v = v.replace(/\bdigital native\b/g, "parseltongue");
	v = v.replace(/\bdigital natives\b/g, "parseltongues");

	// Generation Y
	v = v.replace(/\bGeneration Y\b/g, "Serpent Society");
	v = v.replace(/\bgeneration y\b/g, "serpent society");
	v = v.replace(/\bGen Y\b/g, "Society of the Serpent");
	v = v.replace(/\bgen y\b/g, "serpent society");
	v = v.replace(/\bGenY\b/g, "Serpent Society");
	v = v.replace(/\bgeny\b/g, "serpent society");
	v = v.replace(/\bGeneration Why\b/g, "Serpent Society");
	v = v.replace(/\bgeneration why\b/g, "serpent society");

	// Millennial Generation
	v = v.replace(/\bMillennial Generation\b/g, "Plissken Faction");
	v = v.replace(/\bmillennial generation\b/g, "Plissken faction");
	v = v.replace(/\bGeneration Millennial\b/g, "Plissken Faction");
	v = v.replace(/\bgeneration millennial\b/g, "Plissken faction");

	// Generation We
	v = v.replace(/\bGeneration We\b/g, "Caduceus Cult");
	v = v.replace(/\bgeneration we\b/g, "caduceus cult");
	v = v.replace(/\bWe Generation\b/g, "Cult of the Caduceus");
	v = v.replace(/\bwe generation\b/g, "cult of the caduceus");

    // Generation Me
    v = v.replace(/\bGeneration Me\b/g, "The Cult of the Serpent");
    v = v.replace(/\bgeneration me\b/g, "the cult of the serpent");

	// Global Generation
	v = v.replace(/\bGlobal Generation\b/g, "Tannin's Horde");
	v = v.replace(/\bglobal generation\b/g, "Tannin's horde");
	v = v.replace(/\bGeneration Global\b/g, "Horde of Tannin");
	v = v.replace(/\bgeneration global\b/g, "horde of Tannin");

	// Generation Next
	v = v.replace(/\bGeneration Next\b/g, "Time of Nidhogg");
	v = v.replace(/\bgeneration next\b/g, "time of Nidhogg");

	// Net Generation
	v = v.replace(/\bNet Generation\b/g, "Damballa's Coils");
	v = v.replace(/\bnet generation\b/g, "Damballa's coils");
	v = v.replace(/\bGeneration Net\b/g, "Coils of Damballa");
	v = v.replace(/\bgeneration net\b/g, "Coils of Damballa");

	// Echo Boomers
	v = v.replace(/\bEcho Boomers\b/g, "Crotalids");
	v = v.replace(/\becho Boomers\b/g, "crotalids");

	// New Boomers
	v = v.replace(/\bNew Boomers\b/g, "Jörmungandr's Circle");
	v = v.replace(/\bnew Boomers\b/g, "Jörmungandr's circle");
	v = v.replace(/\bNew Boomers'\b/g, "Jörmungandr's Circle's");
	v = v.replace(/\bnew Boomers'\b/g, "Jörmungandr's circle's");

	// Generation Flux
	v = v.replace(/\bGeneration Flux\b/g, "Hiss Club");
	v = v.replace(/\bgeneration flux\b/g, "hiss club");
	v = v.replace(/\bFlux Generation\b/g, "Hiss Club");
	v = v.replace(/\bflux generation\b/g, "hiss club");

	// Generation Sell
	v = v.replace(/\bGeneration Sell\b/g, "Kaa Tribe");
	v = v.replace(/\bgeneration sell\b/g, "Kaa tribe");
	v = v.replace(/\bSell Generation\b/g, "Tribe of Kaa");
	v = v.replace(/\bsell generation\b/g, "tribe of Kaa");

	// Boomerang Generation
	v = v.replace(/\bBoomerang Generation\b/g, "Ouroboros Society");
	v = v.replace(/\bboomerang generation\b/g, "ouroboros society");
	v = v.replace(/\bGeneration Boomerang\b/g, "Ouroboros Society");
	v = v.replace(/\bgeneration boomerang\b/g, "ouroboros society");

	// Peter Pan Generation
	v = v.replace(/\bPeter Pan Generation\b/g, "Neheb-Kau Cult");
	v = v.replace(/\bPeter Pan generation\b/g, "Neheb-Kau cult");
	v = v.replace(/\bpeter pan generation\b/g, "Neheb-Kau cult");
	v = v.replace(/\bGeneration Peter Pan\b/g, "Cult of Neheb-Kau");
	v = v.replace(/\bgeneration Peter Pan\b/g, "cult of Neheb-Kau");
	v = v.replace(/\bgeneration peter pan\b/g, "cult of Neheb-Kau");

	// Generation 911
	v = v.replace(/\bGeneration 9\/11\b/g, "Kaa Tribe");
	v = v.replace(/\bGeneration 911\b/g, "Kaa Tribe");
	v = v.replace(/\bgeneration 9\/11\b/g, "Kaa tribe");
	v = v.replace(/\bgeneration 911\b/g, "Kaa tribe");
	v = v.replace(/\b9\/11 Generation\b/g, "Tribe of the Kaa");
	v = v.replace(/\b9\/11 generation\b/g, "tribe of the Kaa");
	v = v.replace(/\bGen 9\/11\b/g, "Kaa Tribe");
	v = v.replace(/\bgen 9\/11\b/g, "Kaa tribe");
	v = v.replace(/\bGen 911\b/g, "Kaa Tribe");
	v = v.replace(/\bgen 911\b/g, "Kaa tribe");

	// The Generation of €700
	v = v.replace(/\bThe Generation of €700\b/g, "Ophion");
	v = v.replace(/\bthe generation of €700\b/g, "ophion");
	v = v.replace(/\b€700 Generation\b/g, "Ophion");
	v = v.replace(/\b€700 generation\b/g, "ophion");

	// Mileurista
	v = v.replace(/\bMileurista\b/g, "Nagual");
	v = v.replace(/\bmileurista\b/g, "Nagual");
	v = v.replace(/\bMilleurista\b/g, "Nagual");
	v = v.replace(/\bmilleurista\b/g, "Nagual");

	// Precarious Generation
	v = v.replace(/\bPrecarious Generation\b/g, "Gargouille");
	v = v.replace(/\bprecarious generation\b/g, "gargouille");
	v = v.replace(/\bGeneration Precarious\b/g, "Gargouille");
	v = v.replace(/\bgeneration precarious\b/g, "gargouille");

	textNode.nodeValue = v;
}

<commit_msg>Combine singular and plural replacements<commit_after>walk(document.body);

function walk(node)
{
	// I stole this function from here:
	// http://is.gd/mwZp7E

	var child, next;

	switch ( node.nodeType )
	{
		case 1:  // Element
		case 9:  // Document
		case 11: // Document fragment
			child = node.firstChild;
			while ( child )
			{
				next = child.nextSibling;
				walk(child);
				child = next;
			}
			break;

		case 3: // Text node
			handleText(node);
			break;
	}
}

function handleText(textNode)
{
	var v = textNode.nodeValue;

	// Millennial
	v = v.replace(/\bMillennial\b/g, "Snake Person");
	v = v.replace(/\bmillennial\b/g, "snake person");
	v = v.replace(/\bMillennials\b/g, "Snake People");
	v = v.replace(/\bmillennials\b/g, "snake people");
	v = v.replace(/\bMillennials'\b/g, "Snake People's");
	v = v.replace(/\bmillennials'\b/g, "snake people's");
	v = v.replace(/\bMillienials\b/g, "Snake People"); 		// Common misspelling
	v = v.replace(/\bmillienials\b/g, "snake people"); 	 	// Common misspelling

	// The Great Recession
	v = v.replace(/\bGreat Recession\b/g, "Time of Shedding and Cold Rocks");
	v = v.replace(/\bgreat recession\b/g, "time of shedding and cold rocks");

	// The Great Depression
	v = v.replace(/\bGreat Depression\b/g, "Clutch Plague");
	v = v.replace(/\bgreat depression\b/g, "clutch plague");

	// Occupy Wall Street
	v = v.replace(/\bOccupy Wall Street\b/g, "Great Ape-Snake War");
	v = v.replace(/\boccupy wall street\b/g, "great ape-snake war");
	v = v.replace(/\bOccupy Movement\b/g, "Great Ape-Snake War");
	v = v.replace(/\boccupy movement\b/g, "great ape-snake war");
	v = v.replace(/\bOWS Movement\b/g, "Great Ape-Snake War");
	v = v.replace(/\bOWS movement\b/g, "great ape-snake war");
	v = v.replace(/\bows movement\b/g, "great ape-snake war");
	v = v.replace(/\b ows \b/g, " ga-sw ");
	v = v.replace(/\b OWS \b/g, " GA-SW ");

	// Helicopter Parents
	v = v.replace(/\bHelicopter Parents\b/g, "Thulsa Doom");
	v = v.replace(/\bhelicopter parents\b/g, "Thoth-Amon");
	v = v.replace(/\bHelicopter Parents'\b/g, "Thulsa Doom's");
	v = v.replace(/\bhelicopter parents'\b/g, "Thoth-Amon's");

	// Trophy Kids
	v = v.replace(/\bTrophy Kids\b/g, "Quetzalcoatl's Chosen");
	v = v.replace(/\btrophy kids\b/g, "Quetzalcoatl's chosen");
	v = v.replace(/\bTrophy Kids'\b/g, "Quetzalcoatl's Chosen's");
	v = v.replace(/\btrophy kids'\b/g, "Quetzalcoatl's chosen's");

	// Digital Natives
	v = v.replace(/\bDigital Native(s)?\b/g, "Parseltongue$1");
	v = v.replace(/\bdigital native(s)?\b/g, "parseltongue$1");

	// Generation Y
	v = v.replace(/\bGeneration Y\b/g, "Serpent Society");
	v = v.replace(/\bgeneration y\b/g, "serpent society");
	v = v.replace(/\bGen Y\b/g, "Society of the Serpent");
	v = v.replace(/\bgen y\b/g, "serpent society");
	v = v.replace(/\bGenY\b/g, "Serpent Society");
	v = v.replace(/\bgeny\b/g, "serpent society");
	v = v.replace(/\bGeneration Why\b/g, "Serpent Society");
	v = v.replace(/\bgeneration why\b/g, "serpent society");

	// Millennial Generation
	v = v.replace(/\bMillennial Generation\b/g, "Plissken Faction");
	v = v.replace(/\bmillennial generation\b/g, "Plissken faction");
	v = v.replace(/\bGeneration Millennial\b/g, "Plissken Faction");
	v = v.replace(/\bgeneration millennial\b/g, "Plissken faction");

	// Generation We
	v = v.replace(/\bGeneration We\b/g, "Caduceus Cult");
	v = v.replace(/\bgeneration we\b/g, "caduceus cult");
	v = v.replace(/\bWe Generation\b/g, "Cult of the Caduceus");
	v = v.replace(/\bwe generation\b/g, "cult of the caduceus");

    // Generation Me
    v = v.replace(/\bGeneration Me\b/g, "The Cult of the Serpent");
    v = v.replace(/\bgeneration me\b/g, "the cult of the serpent");

	// Global Generation
	v = v.replace(/\bGlobal Generation\b/g, "Tannin's Horde");
	v = v.replace(/\bglobal generation\b/g, "Tannin's horde");
	v = v.replace(/\bGeneration Global\b/g, "Horde of Tannin");
	v = v.replace(/\bgeneration global\b/g, "horde of Tannin");

	// Generation Next
	v = v.replace(/\bGeneration Next\b/g, "Time of Nidhogg");
	v = v.replace(/\bgeneration next\b/g, "time of Nidhogg");

	// Net Generation
	v = v.replace(/\bNet Generation\b/g, "Damballa's Coils");
	v = v.replace(/\bnet generation\b/g, "Damballa's coils");
	v = v.replace(/\bGeneration Net\b/g, "Coils of Damballa");
	v = v.replace(/\bgeneration net\b/g, "Coils of Damballa");

	// Echo Boomers
	v = v.replace(/\bEcho Boomers\b/g, "Crotalids");
	v = v.replace(/\becho Boomers\b/g, "crotalids");

	// New Boomers
	v = v.replace(/\bNew Boomers\b/g, "Jörmungandr's Circle");
	v = v.replace(/\bnew Boomers\b/g, "Jörmungandr's circle");
	v = v.replace(/\bNew Boomers'\b/g, "Jörmungandr's Circle's");
	v = v.replace(/\bnew Boomers'\b/g, "Jörmungandr's circle's");

	// Generation Flux
	v = v.replace(/\bGeneration Flux\b/g, "Hiss Club");
	v = v.replace(/\bgeneration flux\b/g, "hiss club");
	v = v.replace(/\bFlux Generation\b/g, "Hiss Club");
	v = v.replace(/\bflux generation\b/g, "hiss club");

	// Generation Sell
	v = v.replace(/\bGeneration Sell\b/g, "Kaa Tribe");
	v = v.replace(/\bgeneration sell\b/g, "Kaa tribe");
	v = v.replace(/\bSell Generation\b/g, "Tribe of Kaa");
	v = v.replace(/\bsell generation\b/g, "tribe of Kaa");

	// Boomerang Generation
	v = v.replace(/\bBoomerang Generation\b/g, "Ouroboros Society");
	v = v.replace(/\bboomerang generation\b/g, "ouroboros society");
	v = v.replace(/\bGeneration Boomerang\b/g, "Ouroboros Society");
	v = v.replace(/\bgeneration boomerang\b/g, "ouroboros society");

	// Peter Pan Generation
	v = v.replace(/\bPeter Pan Generation\b/g, "Neheb-Kau Cult");
	v = v.replace(/\bPeter Pan generation\b/g, "Neheb-Kau cult");
	v = v.replace(/\bpeter pan generation\b/g, "Neheb-Kau cult");
	v = v.replace(/\bGeneration Peter Pan\b/g, "Cult of Neheb-Kau");
	v = v.replace(/\bgeneration Peter Pan\b/g, "cult of Neheb-Kau");
	v = v.replace(/\bgeneration peter pan\b/g, "cult of Neheb-Kau");

	// Generation 911
	v = v.replace(/\bGeneration 9\/11\b/g, "Kaa Tribe");
	v = v.replace(/\bGeneration 911\b/g, "Kaa Tribe");
	v = v.replace(/\bgeneration 9\/11\b/g, "Kaa tribe");
	v = v.replace(/\bgeneration 911\b/g, "Kaa tribe");
	v = v.replace(/\b9\/11 Generation\b/g, "Tribe of the Kaa");
	v = v.replace(/\b9\/11 generation\b/g, "tribe of the Kaa");
	v = v.replace(/\bGen 9\/11\b/g, "Kaa Tribe");
	v = v.replace(/\bgen 9\/11\b/g, "Kaa tribe");
	v = v.replace(/\bGen 911\b/g, "Kaa Tribe");
	v = v.replace(/\bgen 911\b/g, "Kaa tribe");

	// The Generation of €700
	v = v.replace(/\bThe Generation of €700\b/g, "Ophion");
	v = v.replace(/\bthe generation of €700\b/g, "ophion");
	v = v.replace(/\b€700 Generation\b/g, "Ophion");
	v = v.replace(/\b€700 generation\b/g, "ophion");

	// Mileurista
	v = v.replace(/\bMileurista\b/g, "Nagual");
	v = v.replace(/\bmileurista\b/g, "Nagual");
	v = v.replace(/\bMilleurista\b/g, "Nagual");
	v = v.replace(/\bmilleurista\b/g, "Nagual");

	// Precarious Generation
	v = v.replace(/\bPrecarious Generation\b/g, "Gargouille");
	v = v.replace(/\bprecarious generation\b/g, "gargouille");
	v = v.replace(/\bGeneration Precarious\b/g, "Gargouille");
	v = v.replace(/\bgeneration precarious\b/g, "gargouille");

	textNode.nodeValue = v;
}

<|endoftext|>


<commit_before>/*
---

name: PictureSlider

description: Animated picture slider.

license: MIT-style

authors:
- Peter Kuma

requires:
- core/1.4.3: [Class, Element.Style, Fx.Tween]

provides: PictureSlider

...
*/

var PictureSlider = new Class({
	Implements: [Options,Events],

	options: {
		arrows: 'medium',
		duration: 'short',
		center: true,
		controls: {
			opacity: 0.8,
			duration: 'short',
		},
		caption: {
			opacity: 0.8,
			duration: 'short',
		},
		text: {
			duration: 200,
		}
	},

	initialize: function(obj, images, options) {
		this.setOptions(options);
		var this_ = this;

		this.images = [];
		this.current = null;

		this.obj = obj;
		obj.addClass('picture-slider');

		/* Determine width and height. */
		this.width = obj.getStyle('width').toInt();
		this.height = obj.getStyle('height').toInt();

		/* Sheet. */
		this.sheet = document.createElement('div');
		this.sheet.addClass('ps-sheet');
		this.sheet.setStyle('width', this.width);
		this.sheet.setStyle('height', this.height);
		obj.appendChild(this.sheet);

		/* Place images on the sheet. */
		images.each(function(image) { this_.appendImage(image); });

		/* Bottom description panel. */
		this.caption = document.createElement('div');
		this.caption.addClass('ps-caption');
		this.caption.setStyle('height', 0);
		this.caption.setStyle('opacity', this.options.caption.opacity);
		this.caption.p = document.createElement('p');
		this.caption.p.set('tween', {duration: this.options.caption.duration});
		this.caption.appendChild(this.caption.p);
		this.obj.appendChild(this.caption);

		/* Controls. */
		this.controls = document.createElement('div');
		this.controls.addClass('ps-controls');
		this.controls.setStyle('width', this.width);
		this.controls.setStyle('height', this.height);
		this.controls.setStyle('opacity', 0);
		this.controls.set('tween',  {duration: this.options.controls.duration});
		this.obj.appendChild(this.controls);

		this.leftArrow = document.createElement('div');
		this.leftArrow.addClass('ps-left');
		if (this.options.arrows)
			this.leftArrow.addClass('ps-left-'+this.options.arrows);
		//this.leftArrow.setStyle('width', this.width*0.3);
		this.leftArrow.setStyle('height', this.height);
		this.leftArrow.setStyle('opacity', 0);
		this.leftArrow.addEvent('click', function() { this_.left(); });
		this.controls.appendChild(this.leftArrow);

		this.rightArrow = document.createElement('div');
		this.rightArrow.addClass('ps-right');
		if (this.options.arrows)
			this.rightArrow.addClass('ps-right-'+this.options.arrows);
		//this.rightArrow.setStyle('width', this.width*0.3);
		this.rightArrow.setStyle('height', this.height);
		this.rightArrow.setStyle('opacity', 0);
		this.rightArrow.addEvent('click', function() { this_.right(); });
		this.controls.appendChild(this.rightArrow);

		this.obj.addEvent('mouseover', function() { this_.activateControls(); });
		this.obj.addEvent('mouseout', function() { this_.deactivateControls(); });

		/* Keyboard control. */
		this.kb = null;
		if (typeof Keyboard != 'undefined') {
			this.kb = new Keyboard({
				defaultEventType: 'keydown',
				events: {
					'left': function() { this_.left(); },
					'right': function() { this_.right(); },
				},
			});
			this.kb.activate();
		}

		/* Switch to the first image. */
		this.switchTo(0);
	},

	activateControls: function() {
		this.controls.fade(this.options.controls.opacity);
		/* The last to get focus gets the keyboard. */
		if (this.kb) this.kb.activate();
	},

	deactivateControls: function() {
		this.controls.fade(0);
	},

	/*
	 * Switches to the image number n.
	 */
	switchTo: function(n) {
		if (!(n >= 0 && n < this.images.length))
			return this.current;

		this.current = this.images[n];

		var fx = new Fx.Tween(this.sheet, {
			duration: this.options.duration,
			property: 'left'
		});
		fx.start(-n*this.width);

		/* If at the beginning, hide left arrow. */
		if (n == 0)
			this.leftArrow.fade(0);
		else
			this.leftArrow.fade(1);

		/* If at the end, hide right arrow. */
		if (n == this.images.length - 1)
			this.rightArrow.fade(0);
		else
			this.rightArrow.fade(1);

		this.setCaption(this.current.caption);
		this.n = n;

		this.fireEvent('change', this.current);

		return this.current;
	},

	/*
	 * Switches to the previous image.
	 */
	left: function() {
		return this.switchTo(this.n - 1);
	},

	/*
	 * Switches to the next image.
	 */
	right: function() {
		return this.switchTo(this.n + 1);
	},

	/*
	 * Appends image to the end.
	 */
	appendImage: function(image) {
		var frame;
		if (image.link) {
			frame = document.createElement('a');
			frame.href = image.link;
		} else {
			frame = document.createElement('div');
		}
		frame.addClass('ps-frame');
		frame.setStyle('left', this.width*this.images.length);
		frame.setStyle('width', this.width);
		frame.setStyle('height', this.height);
		this.sheet.appendChild(frame);

		var center = this.options.center;
		if (typeof image.center != 'undefined')
			center = image.center;

		if (image.src) {
			var img = document.createElement('img');
			img.addClass('ps-frame-image');
			img.src = image.src;
			frame.appendChild(img);
			var this_ = this;
			img.addEvent('load', function() {
				if (img.width/img.height > this_.width/this_.height) {
					img.width = this_.width;
				} else {
					img.height = this_.height;
				}
				if (center)
					img.setStyle('top', (this_.height-img.height)/2);
			});
		}

		if (image.content) {
			var content = document.createElement('div');
			content.addClass('ps-frame-content');
			frame.appendChild(content);
			if (typeof image.content == 'string') {
				content.innerHTML = image.content;
			}
			var w = content.getStyle('width').toInt();
			var pad = content.getStyle('padding-left').toInt() +
		    		  content.getStyle('padding-right').toInt();
		 	var mar = content.getStyle('margin-left').toInt() +
		   			  content.getStyle('margin-right').toInt();
			content.setStyle('left', (this.width-w-pad-mar)/2);
			if (center) {
				var h = content.getStyle('height').toInt();
				var pad = content.getStyle('padding-top').toInt() +
		    			  content.getStyle('padding-bottom').toInt();
		 		var mar = content.getStyle('margin-top').toInt() +
		   				  content.getStyle('margin-bottom').toInt();
		   		var top = (this.height-h-pad-mar)/2;
		   		if (top > 0)
					content.setStyle('top', (this.height-h-pad-mar)/2);
			}
		}

		this.images.push(image);
	},

	/*
	 * Set caption to text.
	 */
	setCaption: function(text) {
		var fx = new Fx.Tween(this.caption, {
			duration: this.options.text.duration,
			property: 'height',
			link: 'chain',
		});

		if (text) {
			var this_ = this;
			fx.addEvent('complete', function() {
				this_.caption.p.innerHTML = text;
				this_.caption.p.fade(1);
			});
			this.caption.p.fade(0);
			var tmpcaption = document.createElement('div');
			tmpcaption.addClass('ps-caption');
			tmpcaption.setStyle('visibility', 'hidden');
			tmpcaption.p = document.createElement('p');
			tmpcaption.p.innerHTML = text;
			tmpcaption.appendChild(tmpcaption.p);
			this.obj.appendChild(tmpcaption);
			h = tmpcaption.getStyle('height');
			this.obj.removeChild(tmpcaption);
			fx.start(h);
		} else {
			this.caption.p.innerHTML = '';
			this.caption.p.fade(0);
			fx.start(0);
		}
	},
});

<commit_msg>Remove trailing commas as they upset IE7.<commit_after>/*
---

name: PictureSlider

description: Animated picture slider.

license: MIT-style

authors:
- Peter Kuma

requires:
- core/1.4.3: [Class, Element.Style, Fx.Tween]

provides: PictureSlider

...
*/

var PictureSlider = new Class({
	Implements: [Options,Events],

	options: {
		arrows: 'medium',
		duration: 'short',
		center: true,
		controls: {
			opacity: 0.8,
			duration: 'short'
		},
		caption: {
			opacity: 0.8,
			duration: 'short'
		},
		text: {
			duration: 200
		}
	},

	initialize: function(obj, images, options) {
		this.setOptions(options);
		var this_ = this;

		this.images = [];
		this.current = null;

		this.obj = obj;
		obj.addClass('picture-slider');

		/* Determine width and height. */
		this.width = obj.getStyle('width').toInt();
		this.height = obj.getStyle('height').toInt();

		/* Sheet. */
		this.sheet = document.createElement('div');
		this.sheet.addClass('ps-sheet');
		this.sheet.setStyle('width', this.width);
		this.sheet.setStyle('height', this.height);
		obj.appendChild(this.sheet);

		/* Place images on the sheet. */
		images.each(function(image) { this_.appendImage(image); });

		/* Bottom description panel. */
		this.caption = document.createElement('div');
		this.caption.addClass('ps-caption');
		this.caption.setStyle('height', 0);
		this.caption.setStyle('opacity', this.options.caption.opacity);
		this.caption.p = document.createElement('p');
		this.caption.p.set('tween', {duration: this.options.caption.duration});
		this.caption.appendChild(this.caption.p);
		this.obj.appendChild(this.caption);

		/* Controls. */
		this.controls = document.createElement('div');
		this.controls.addClass('ps-controls');
		this.controls.setStyle('width', this.width);
		this.controls.setStyle('height', this.height);
		this.controls.setStyle('opacity', 0);
		this.controls.set('tween',  {duration: this.options.controls.duration});
		this.obj.appendChild(this.controls);

		this.leftArrow = document.createElement('div');
		this.leftArrow.addClass('ps-left');
		if (this.options.arrows)
			this.leftArrow.addClass('ps-left-'+this.options.arrows);
		//this.leftArrow.setStyle('width', this.width*0.3);
		this.leftArrow.setStyle('height', this.height);
		this.leftArrow.setStyle('opacity', 0);
		this.leftArrow.addEvent('click', function() { this_.left(); });
		this.controls.appendChild(this.leftArrow);

		this.rightArrow = document.createElement('div');
		this.rightArrow.addClass('ps-right');
		if (this.options.arrows)
			this.rightArrow.addClass('ps-right-'+this.options.arrows);
		//this.rightArrow.setStyle('width', this.width*0.3);
		this.rightArrow.setStyle('height', this.height);
		this.rightArrow.setStyle('opacity', 0);
		this.rightArrow.addEvent('click', function() { this_.right(); });
		this.controls.appendChild(this.rightArrow);

		this.obj.addEvent('mouseover', function() { this_.activateControls(); });
		this.obj.addEvent('mouseout', function() { this_.deactivateControls(); });

		/* Keyboard control. */
		this.kb = null;
		if (typeof Keyboard != 'undefined') {
			this.kb = new Keyboard({
				defaultEventType: 'keydown',
				events: {
					'left': function() { this_.left(); },
					'right': function() { this_.right(); }
				}
			});
			this.kb.activate();
		}

		/* Switch to the first image. */
		this.switchTo(0);
	},

	activateControls: function() {
		this.controls.fade(this.options.controls.opacity);
		/* The last to get focus gets the keyboard. */
		if (this.kb) this.kb.activate();
	},

	deactivateControls: function() {
		this.controls.fade(0);
	},

	/*
	 * Switches to the image number n.
	 */
	switchTo: function(n) {
		if (!(n >= 0 && n < this.images.length))
			return this.current;

		this.current = this.images[n];

		var fx = new Fx.Tween(this.sheet, {
			duration: this.options.duration,
			property: 'left'
		});
		fx.start(-n*this.width);

		/* If at the beginning, hide left arrow. */
		if (n == 0)
			this.leftArrow.fade(0);
		else
			this.leftArrow.fade(1);

		/* If at the end, hide right arrow. */
		if (n == this.images.length - 1)
			this.rightArrow.fade(0);
		else
			this.rightArrow.fade(1);

		this.setCaption(this.current.caption);
		this.n = n;

		this.fireEvent('change', this.current);

		return this.current;
	},

	/*
	 * Switches to the previous image.
	 */
	left: function() {
		return this.switchTo(this.n - 1);
	},

	/*
	 * Switches to the next image.
	 */
	right: function() {
		return this.switchTo(this.n + 1);
	},

	/*
	 * Appends image to the end.
	 */
	appendImage: function(image) {
		var frame;
		if (image.link) {
			frame = document.createElement('a');
			frame.href = image.link;
		} else {
			frame = document.createElement('div');
		}
		frame.addClass('ps-frame');
		frame.setStyle('left', this.width*this.images.length);
		frame.setStyle('width', this.width);
		frame.setStyle('height', this.height);
		this.sheet.appendChild(frame);

		var center = this.options.center;
		if (typeof image.center != 'undefined')
			center = image.center;

		if (image.src) {
			var img = document.createElement('img');
			img.addClass('ps-frame-image');
			img.src = image.src;
			frame.appendChild(img);
			var this_ = this;
			img.addEvent('load', function() {
				if (img.width/img.height > this_.width/this_.height) {
					img.width = this_.width;
				} else {
					img.height = this_.height;
				}
				if (center)
					img.setStyle('top', (this_.height-img.height)/2);
			});
		}

		if (image.content) {
			var content = document.createElement('div');
			content.addClass('ps-frame-content');
			frame.appendChild(content);
			if (typeof image.content == 'string') {
				content.innerHTML = image.content;
			}
			var w = content.getStyle('width').toInt();
			var pad = content.getStyle('padding-left').toInt() +
		    		  content.getStyle('padding-right').toInt();
		 	var mar = content.getStyle('margin-left').toInt() +
		   			  content.getStyle('margin-right').toInt();
			content.setStyle('left', (this.width-w-pad-mar)/2);
			if (center) {
				var h = content.getStyle('height').toInt();
				var pad = content.getStyle('padding-top').toInt() +
		    			  content.getStyle('padding-bottom').toInt();
		 		var mar = content.getStyle('margin-top').toInt() +
		   				  content.getStyle('margin-bottom').toInt();
		   		var top = (this.height-h-pad-mar)/2;
		   		if (top > 0)
					content.setStyle('top', (this.height-h-pad-mar)/2);
			}
		}

		this.images.push(image);
	},

	/*
	 * Set caption to text.
	 */
	setCaption: function(text) {
		var fx = new Fx.Tween(this.caption, {
			duration: this.options.text.duration,
			property: 'height',
			link: 'chain'
		});

		if (text) {
			var this_ = this;
			fx.addEvent('complete', function() {
				this_.caption.p.innerHTML = text;
				this_.caption.p.fade(1);
			});
			this.caption.p.fade(0);
			var tmpcaption = document.createElement('div');
			tmpcaption.addClass('ps-caption');
			tmpcaption.setStyle('visibility', 'hidden');
			tmpcaption.p = document.createElement('p');
			tmpcaption.p.innerHTML = text;
			tmpcaption.appendChild(tmpcaption.p);
			this.obj.appendChild(tmpcaption);
			h = tmpcaption.getStyle('height');
			this.obj.removeChild(tmpcaption);
			fx.start(h);
		} else {
			this.caption.p.innerHTML = '';
			this.caption.p.fade(0);
			fx.start(0);
		}
	}
});

<|endoftext|>


<commit_before>export default {
  props: {
    service: {
      type: String,
      required: true
    },
    method: {
      type: String
    },
    query: {
      type: Object
    },
    queryWhen: {
      type: [ Boolean, Function ],
      default: true
    },
    // For get requests
    id: {
      type: [ Number, String ]
    },
    // If a separate query is desired to fetch data, use fetchQuery
    // The watchers will automatically be updated, so you don't have to write 'fetchQuery.propName'
    fetchQuery: {
      type: Object
    },
    watch: {
      type: Array,
      default () {
        return []
      }
    },
    immediate: {
      type: Boolean,
      default: true
    },
    local: {
      type: Boolean,
      default: false
    },
    editScope: {
      type: Function,
      default (scope) {
        return scope
      }
    }
  },
  data: () => ({
    isFindPending: false,
    isGetPending: false
  }),
  computed: {
    findItems () {
      return this.$store.getters[`${this.service}/find`]({ query: this.query }).data
    },
    getItem () {
      const getArgs = this.getArgs(this.query)

      return this.$store.getters[`${this.service}/get`](getArgs.length === 1 ? this.id : getArgs)
    },
    items () {
      if (this.method === 'find') {
        return this.findItems
      } else if (this.method === 'get') {
        return this.getItem
      } else if (this.id !== undefined && this.id !== null) {
        return this.getItem
      } else {
        return this.findItems
      }
    }
  },
  methods: {
    getArgs (queryToUse) {
      const query = queryToUse || this.fetchQuery || this.query
      const getArgs = [this.id]

      if (query) {
        getArgs.push({ query })
      }

      return getArgs
    },
    findData () {
      const query = this.fetchQuery || this.query

      if (typeof this.queryWhen === 'function' ? this.queryWhen(this.query) : this.queryWhen) {
        this.isFindPending = true

        return this.$store.dispatch(`${this.service}/find`, { query })
          .then(() => {
            this.isFindPending = false
          })
      }
    },
    getData () {
      const getArgs = this.getArgs()

      if (typeof this.queryWhen === 'function' ? this.queryWhen(...getArgs) : this.queryWhen) {
        this.isGetPending = true

        return this.$store.dispatch(`${this.service}/get`, getArgs.length === 1 ? this.id : getArgs)
          .then(() => {
            this.isGetPending = false
          })
      }
    },
    fetchData () {
      if (!this.local) {
        if (this.method === 'find') {
          return this.findData()
        } else if (this.method === 'get') {
          return this.getData()
        } else if (this.id !== undefined && this.id !== null) {
          return this.getData()
        } else {
          return this.findData()
        }
      }
    }
  },
  watch: {
    id: 'fetchData'
  },
  created () {
    if (!this.$FeathersVuex) {
      throw new Error(`You must first Vue.use the FeathersVuex plugin before using the 'feathers-vuex-data' component.`)
    }
    if (!this.$store.state[this.service]) {
      throw new Error(`The '${this.service}' plugin cannot be found. Did you register the service with feathers-vuex?`)
    }

    if (this.fetchQuery || this.query || (this.id !== null && this.id !== undefined)) {
      this.watch.forEach(prop => {
        if (typeof prop !== 'string') {
          throw new Error(`Values in the 'watch' array must be strings.`)
        }
        if (this.fetchQuery) {
          if (prop.startsWith('query')) {
            prop.replace('query', 'fetchQuery')
          }
        }
        this.$watch(prop, this.fetchData)
      })

      if (this.immediate) {
        this.fetchData()
      }
    }
  },
  render () {
    const { items, isFindPending, isGetPending } = this
    const defaultScope = { items, isFindPending, isGetPending }
    const scope = this.editScope(defaultScope)

    return this.$scopedSlots.default(scope || defaultScope)
  }
}
<commit_msg>Allow watch to just be a string<commit_after>export default {
  props: {
    service: {
      type: String,
      required: true
    },
    method: {
      type: String
    },
    query: {
      type: Object
    },
    queryWhen: {
      type: [ Boolean, Function ],
      default: true
    },
    // For get requests
    id: {
      type: [ Number, String ]
    },
    // If a separate query is desired to fetch data, use fetchQuery
    // The watchers will automatically be updated, so you don't have to write 'fetchQuery.propName'
    fetchQuery: {
      type: Object
    },
    watch: {
      type: [ String, Array ],
      default () {
        return []
      }
    },
    immediate: {
      type: Boolean,
      default: true
    },
    local: {
      type: Boolean,
      default: false
    },
    editScope: {
      type: Function,
      default (scope) {
        return scope
      }
    }
  },
  data: () => ({
    isFindPending: false,
    isGetPending: false
  }),
  computed: {
    findItems () {
      return this.$store.getters[`${this.service}/find`]({ query: this.query }).data
    },
    getItem () {
      const getArgs = this.getArgs(this.query)

      return this.$store.getters[`${this.service}/get`](getArgs.length === 1 ? this.id : getArgs)
    },
    items () {
      if (this.method === 'find') {
        return this.findItems
      } else if (this.method === 'get') {
        return this.getItem
      } else if (this.id !== undefined && this.id !== null) {
        return this.getItem
      } else {
        return this.findItems
      }
    }
  },
  methods: {
    getArgs (queryToUse) {
      const query = queryToUse || this.fetchQuery || this.query
      const getArgs = [this.id]

      if (query) {
        getArgs.push({ query })
      }

      return getArgs
    },
    findData () {
      const query = this.fetchQuery || this.query

      if (typeof this.queryWhen === 'function' ? this.queryWhen(this.query) : this.queryWhen) {
        this.isFindPending = true

        return this.$store.dispatch(`${this.service}/find`, { query })
          .then(() => {
            this.isFindPending = false
          })
      }
    },
    getData () {
      const getArgs = this.getArgs()

      if (typeof this.queryWhen === 'function' ? this.queryWhen(...getArgs) : this.queryWhen) {
        this.isGetPending = true

        return this.$store.dispatch(`${this.service}/get`, getArgs.length === 1 ? this.id : getArgs)
          .then(() => {
            this.isGetPending = false
          })
      }
    },
    fetchData () {
      if (!this.local) {
        if (this.method === 'find') {
          return this.findData()
        } else if (this.method === 'get') {
          return this.getData()
        } else if (this.id !== undefined && this.id !== null) {
          return this.getData()
        } else {
          return this.findData()
        }
      }
    }
  },
  watch: {
    id: 'fetchData'
  },
  created () {
    if (!this.$FeathersVuex) {
      throw new Error(`You must first Vue.use the FeathersVuex plugin before using the 'feathers-vuex-data' component.`)
    }
    if (!this.$store.state[this.service]) {
      throw new Error(`The '${this.service}' plugin cannot be found. Did you register the service with feathers-vuex?`)
    }

    const watch = Array.isArray(this.watch) ? this.watch : [ this.watch ]

    if (this.fetchQuery || this.query || (this.id !== null && this.id !== undefined)) {
      watch.forEach(prop => {
        if (typeof prop !== 'string') {
          throw new Error(`Values in the 'watch' array must be strings.`)
        }
        if (this.fetchQuery) {
          if (prop.startsWith('query')) {
            prop.replace('query', 'fetchQuery')
          }
        }
        this.$watch(prop, this.fetchData)
      })

      if (this.immediate) {
        this.fetchData()
      }
    }
  },
  render () {
    const { items, isFindPending, isGetPending } = this
    const defaultScope = { items, isFindPending, isGetPending }
    const scope = this.editScope(defaultScope)

    return this.$scopedSlots.default(scope || defaultScope)
  }
}
<|endoftext|>


<commit_before>import patchOps from '../client/patchOps';
import domAttrs from '../client/domAttrs';
import checkReuse from './utils/checkReuse';
import checkChildren from './utils/checkChildren';
import patchChildren from './utils/patchChildren';
import { addListener, removeListeners } from '../client/events/domEventManager';
import ATTRS_TO_EVENTS from '../client/events/attrsToEvents';
import escapeHtml from '../utils/escapeHtml';
import isInArray from '../utils/isInArray';
import console from '../utils/console';
import emptyObj from '../utils/emptyObj';
import merge from '../utils/merge';
import { isTrident, isEdge } from '../client/utils/ua';
import createElement from '../client/utils/createElement';
import createElementByHtml from '../client/utils/createElementByHtml';
import restrictObjProp from '../utils/restrictObjProp';
import { IS_DEBUG } from '../utils/debug';
import { NODE_TYPE_TAG } from './utils/nodeTypes';
import { setKey, setRef } from './utils/setters';

const SHORT_TAGS = {
        area : true,
        base : true,
        br : true,
        col : true,
        command : true,
        embed : true,
        hr : true,
        img : true,
        input : true,
        keygen : true,
        link : true,
        menuitem : true,
        meta : true,
        param : true,
        source : true,
        track : true,
        wbr : true
    },
    USE_DOM_STRINGS = isTrident || isEdge,
    ATTRS_SET = 4,
    CHILDREN_SET = 8,
    NS_SET = 16;

export default function TagNode(tag) {
    if(IS_DEBUG) {
        restrictObjProp(this, 'type');
        restrictObjProp(this, 'tag');
        restrictObjProp(this, 'key');
        restrictObjProp(this, 'attrs');
        restrictObjProp(this, 'children');

        this.__isFrozen = false;
    }

    this.type = NODE_TYPE_TAG;
    this.tag = tag;
    this.key = null;
    this.attrs = emptyObj;
    this.children = null;

    if(IS_DEBUG) {
        this.__isFrozen = true;
        this._sets = 0;
    }

    this._domNode = null;
    this._ns = null;
    this._escapeChildren = true;
    this._ctx = emptyObj;
    this._ref = null;
}

TagNode.prototype = {
    getDomNode() {
        return this._domNode;
    },

    setKey,

    setRef,

    setNs(ns) {
        if(IS_DEBUG) {
            if(this._sets & NS_SET) {
                console.warn('Namespace is already set and shouldn\'t be set again.');
            }
        }

        this._ns = ns;

        if(IS_DEBUG) {
            this._sets |= NS_SET;
        }

        return this;
    },

    setAttrs(attrs) {
        if(IS_DEBUG) {
            if(this._sets & ATTRS_SET) {
                console.warn('Attrs are already set and shouldn\'t be set again.');
            }

            checkAttrs(attrs);
            this.__isFrozen = false;
        }

        this.attrs = this.attrs === emptyObj? attrs : merge(this.attrs, attrs);

        if(IS_DEBUG) {
            Object.freeze(this.attrs);
            this._sets |= ATTRS_SET;
            this.__isFrozen = true;
        }

        return this;
    },

    setChildren(children) {
        if(IS_DEBUG) {
            if(this._sets & CHILDREN_SET) {
                console.warn('Children are already set and shouldn\'t be set again.');
            }

            this.__isFrozen = false;
        }

        this.children = processChildren(children);

        if(IS_DEBUG) {
            if(Array.isArray(this.children)) {
                Object.freeze(this.children);
            }

            this._sets |= CHILDREN_SET;
            this.__isFrozen = true;
        }

        return this;
    },

    setHtml(html) {
        if(IS_DEBUG) {
            if(this._sets & CHILDREN_SET) {
                console.warn('Children are already set and shouldn\'t be set again.');
            }

            this.__isFrozen = false;
        }

        this.children = html;

        if(IS_DEBUG) {
            this._sets |= CHILDREN_SET;
            this.__isFrozen = true;
        }

        this._escapeChildren = false;
        return this;
    },

    setCtx(ctx) {
        if(ctx !== emptyObj) {
            this._ctx = ctx;

            const { children } = this;

            if(children && typeof children !== 'string') {
                const len = children.length;
                let i = 0;

                while(i < len) {
                    children[i++].setCtx(ctx);
                }
            }
        }

        return this;
    },

    renderToDom(parentNs) {
        if(IS_DEBUG) {
            checkReuse(this, this.tag);
        }

        const { tag, children } = this,
            ns = this._ns || parentNs;

        if(USE_DOM_STRINGS && children && typeof children !== 'string') {
            const domNode = createElementByHtml(this.renderToString(), tag, ns);
            this.adoptDom([domNode], 0);
            return domNode;
        }

        const domNode = this._domNode = createElement(tag, ns),
            { attrs } = this;

        if(children) {
            if(typeof children === 'string') {
                this._escapeChildren?
                    domNode.textContent = children :
                    domNode.innerHTML = children;
            }
            else {
                let i = 0;
                const len = children.length;

                while(i < len) {
                    domNode.appendChild(children[i++].renderToDom(ns));
                }
            }
        }

        if(attrs !== emptyObj) {
            let name, value;
            for(name in attrs) {
                if((value = attrs[name]) != null) {
                    if(ATTRS_TO_EVENTS[name]) {
                        addListener(domNode, ATTRS_TO_EVENTS[name], value);
                    }
                    else {
                        domAttrs(name).set(domNode, name, value);
                    }
                }
            }
        }

        return domNode;
    },

    renderToString() {
        const { tag } = this;

        if(tag === '!') {
            return '<!---->';
        }

        const ns = this._ns,
            { attrs } = this;
        let { children } = this,
            res = '<' + tag;

        if(ns) {
            res += ' xmlns="' + ns + '"';
        }

        if(attrs !== emptyObj) {
            let name, value, attrHtml;
            for(name in attrs) {
                value = attrs[name];

                if(value != null) {
                    if(name === 'value') {
                        switch(tag) {
                            case 'textarea':
                                children = value;
                                continue;

                            case 'select':
                                this.setCtx({ value, multiple : attrs.multiple });
                                continue;

                            case 'option':
                                const ctx = this._ctx;

                                if(ctx.multiple? isInArray(ctx.value, value) : ctx.value === value) {
                                    res += ' ' + domAttrs('selected').toString('selected', true);
                                }
                        }
                    }

                    if(!ATTRS_TO_EVENTS[name] && (attrHtml = domAttrs(name).toString(name, value))) {
                        res += ' ' + attrHtml;
                    }
                }
            }
        }

        if(SHORT_TAGS[tag]) {
            res += '/>';
        }
        else {
            res += '>';

            if(children) {
                if(typeof children === 'string') {
                    res += this._escapeChildren?
                        escapeHtml(children) :
                        children;
                }
                else {
                    let i = 0;
                    const len = children.length;

                    while(i < len) {
                        res += children[i++].renderToString();
                    }
                }
            }

            res += '</' + tag + '>';
        }

        return res;
    },

    adoptDom(domNodes, domIdx) {
        if(IS_DEBUG) {
            checkReuse(this, this.tag);
        }

        const domNode = this._domNode = domNodes[domIdx],
            { attrs, children } = this;

        if(attrs !== emptyObj) {
            let name, value;
            for(name in attrs) {
                if((value = attrs[name]) != null && ATTRS_TO_EVENTS[name]) {
                    addListener(domNode, ATTRS_TO_EVENTS[name], value);
                }
            }
        }

        if(children && typeof children !== 'string') {
            let i = 0;
            const len = children.length;

            if(len) {
                const domChildren = domNode.childNodes;
                let domChildIdx = 0;

                while(i < len) {
                    domChildIdx = children[i++].adoptDom(domChildren, domChildIdx);
                }
            }
        }

        return domIdx + 1;
    },

    mount() {
        const { children } = this;

        if(children && typeof children !== 'string') {
            let i = 0;
            const len = children.length;

            while(i < len) {
                children[i++].mount();
            }
        }

        this._ref && this._ref(this._domNode);
    },

    unmount() {
        const { children } = this;

        if(children && typeof children !== 'string') {
            let i = 0;
            const len = children.length;

            while(i < len) {
                children[i++].unmount();
            }
        }

        removeListeners(this._domNode);

        this._domNode = null;

        this._ref && this._ref(null);
    },

    clone() {
        const res = new TagNode(this.tag);

        if(IS_DEBUG) {
            res.__isFrozen = false;
        }

        res.key = this.key;
        res.attrs = this.attrs;
        res.children = this.children;

        if(IS_DEBUG) {
            res.__isFrozen = true;
        }

        res._sets = NS_SET;
        res._ns = this._ns;
        res._escapeChildren = this._escapeChildren;
        res._ctx = this._ctx;
        res._ref = this._ref;

        return res;
    },

    patch(node) {
        if(this === node) {
            this._patchChildren(node);
        }
        else if(this.type === node.type && this.tag === node.tag && this._ns === node._ns) {
            node._domNode = this._domNode;
            this._patchChildren(node);
            this._patchAttrs(node);
            this._patchRef(node);
        }
        else {
            patchOps.replace(this, node);
        }
    },

    _patchChildren(node) {
        const childrenA = this.children,
            childrenB = node.children;

        if(!childrenA && !childrenB) {
            return;
        }

        const isChildrenAText = typeof childrenA === 'string',
            isChildrenBText = typeof childrenB === 'string';

        if(isChildrenBText) {
            if(isChildrenAText) {
                if(childrenA !== childrenB) {
                    patchOps.updateText(this, childrenB, node._escapeChildren);
                }
                return;
            }

            childrenA && childrenA.length && patchOps.removeChildren(this);
            childrenB && patchOps.updateText(this, childrenB, node._escapeChildren);

            return;
        }

        if(!childrenB || !childrenB.length) {
            if(childrenA) {
                isChildrenAText?
                    patchOps.removeText(this) :
                    childrenA.length && patchOps.removeChildren(this);
            }

            return;
        }

        if(isChildrenAText && childrenA) {
            patchOps.removeText(this);
        }

        if(isChildrenAText || !childrenA || !childrenA.length) {
            const childrenBLen = childrenB.length;
            let iB = 0;

            while(iB < childrenBLen) {
                patchOps.appendChild(node, childrenB[iB++]);
            }

            return;
        }

        patchChildren(this, node);
    },

    _patchAttrs(node) {
        const attrsA = this.attrs,
            attrsB = node.attrs;

        if(attrsA === attrsB) {
            return;
        }

        let attrName;

        if(attrsB !== emptyObj) {
            let attrAVal, attrBVal, isAttrAValArray, isAttrBValArray;

            for(attrName in attrsB) {
                attrBVal = attrsB[attrName];
                if(attrsA === emptyObj || (attrAVal = attrsA[attrName]) == null) {
                    if(attrBVal != null) {
                        patchOps.updateAttr(this, attrName, attrBVal);
                    }
                }
                else if(attrBVal == null) {
                    patchOps.removeAttr(this, attrName);
                }
                else if(typeof attrBVal === 'object' && typeof attrAVal === 'object') {
                    isAttrBValArray = Array.isArray(attrBVal);
                    isAttrAValArray = Array.isArray(attrAVal);
                    if(isAttrBValArray || isAttrAValArray) {
                        if(isAttrBValArray && isAttrAValArray) {
                            this._patchAttrArr(attrName, attrAVal, attrBVal);
                        }
                        else {
                            patchOps.updateAttr(this, attrName, attrBVal);
                        }
                    }
                    else {
                        this._patchAttrObj(attrName, attrAVal, attrBVal);
                    }
                }
                else if(attrAVal !== attrBVal) {
                    patchOps.updateAttr(this, attrName, attrBVal);
                }
            }
        }

        if(attrsA !== emptyObj) {
            for(attrName in attrsA) {
                if((attrsB === emptyObj || !(attrName in attrsB)) && attrsA[attrName] != null) {
                    patchOps.removeAttr(this, attrName);
                }
            }
        }
    },

    _patchAttrArr(attrName, arrA, arrB) {
        if(arrA === arrB) {
            return;
        }

        const lenA = arrA.length;
        let hasDiff = false;

        if(lenA === arrB.length) {
            let i = 0;
            while(!hasDiff && i < lenA) {
                if(arrA[i] != arrB[i]) {
                    hasDiff = true;
                }
                ++i;
            }
        }
        else {
            hasDiff = true;
        }

        hasDiff && patchOps.updateAttr(this, attrName, arrB);
    },

    _patchAttrObj(attrName, objA, objB) {
        if(objA === objB) {
            return;
        }

        const diffObj = {};
        let hasDiff = false;

        for(const i in objB) {
            if(objA[i] != objB[i]) {
                hasDiff = true;
                diffObj[i] = objB[i];
            }
        }

        for(const i in objA) {
            if(objA[i] != null && !(i in objB)) {
                hasDiff = true;
                diffObj[i] = null;
            }
        }

        hasDiff && patchOps.updateAttr(this, attrName, diffObj);
    },

    _patchRef(node) {
        if(this._ref) {
            if(this._ref !== node._ref) {
                this._ref(null);

                if(node._ref) {
                    node._ref(node._domNode);
                }
            }
        }
        else if(node._ref) {
            node._ref(node._domNode);
        }
    }
};

function processChildren(children) {
    if(children == null) {
        return null;
    }

    const typeOfChildren = typeof children;

    if(typeOfChildren === 'object') {
        const res = Array.isArray(children)? children : [children];

        if(IS_DEBUG) {
            checkChildren(res);
        }

        return res;
    }

    return typeOfChildren === 'string'?
        children :
        children.toString();
}

function checkAttrs(attrs) {
    for(const name in attrs) {
        if(name.substr(0, 2) === 'on' && !ATTRS_TO_EVENTS[name]) {
            throw Error(`vidom: Unsupported type of dom event listener "${name}".`);
        }
    }
}
<commit_msg>TagNode: patch attributes before children (closes #298) (#299)<commit_after>import patchOps from '../client/patchOps';
import domAttrs from '../client/domAttrs';
import checkReuse from './utils/checkReuse';
import checkChildren from './utils/checkChildren';
import patchChildren from './utils/patchChildren';
import { addListener, removeListeners } from '../client/events/domEventManager';
import ATTRS_TO_EVENTS from '../client/events/attrsToEvents';
import escapeHtml from '../utils/escapeHtml';
import isInArray from '../utils/isInArray';
import console from '../utils/console';
import emptyObj from '../utils/emptyObj';
import merge from '../utils/merge';
import { isTrident, isEdge } from '../client/utils/ua';
import createElement from '../client/utils/createElement';
import createElementByHtml from '../client/utils/createElementByHtml';
import restrictObjProp from '../utils/restrictObjProp';
import { IS_DEBUG } from '../utils/debug';
import { NODE_TYPE_TAG } from './utils/nodeTypes';
import { setKey, setRef } from './utils/setters';

const SHORT_TAGS = {
        area : true,
        base : true,
        br : true,
        col : true,
        command : true,
        embed : true,
        hr : true,
        img : true,
        input : true,
        keygen : true,
        link : true,
        menuitem : true,
        meta : true,
        param : true,
        source : true,
        track : true,
        wbr : true
    },
    USE_DOM_STRINGS = isTrident || isEdge,
    ATTRS_SET = 4,
    CHILDREN_SET = 8,
    NS_SET = 16;

export default function TagNode(tag) {
    if(IS_DEBUG) {
        restrictObjProp(this, 'type');
        restrictObjProp(this, 'tag');
        restrictObjProp(this, 'key');
        restrictObjProp(this, 'attrs');
        restrictObjProp(this, 'children');

        this.__isFrozen = false;
    }

    this.type = NODE_TYPE_TAG;
    this.tag = tag;
    this.key = null;
    this.attrs = emptyObj;
    this.children = null;

    if(IS_DEBUG) {
        this.__isFrozen = true;
        this._sets = 0;
    }

    this._domNode = null;
    this._ns = null;
    this._escapeChildren = true;
    this._ctx = emptyObj;
    this._ref = null;
}

TagNode.prototype = {
    getDomNode() {
        return this._domNode;
    },

    setKey,

    setRef,

    setNs(ns) {
        if(IS_DEBUG) {
            if(this._sets & NS_SET) {
                console.warn('Namespace is already set and shouldn\'t be set again.');
            }
        }

        this._ns = ns;

        if(IS_DEBUG) {
            this._sets |= NS_SET;
        }

        return this;
    },

    setAttrs(attrs) {
        if(IS_DEBUG) {
            if(this._sets & ATTRS_SET) {
                console.warn('Attrs are already set and shouldn\'t be set again.');
            }

            checkAttrs(attrs);
            this.__isFrozen = false;
        }

        this.attrs = this.attrs === emptyObj? attrs : merge(this.attrs, attrs);

        if(IS_DEBUG) {
            Object.freeze(this.attrs);
            this._sets |= ATTRS_SET;
            this.__isFrozen = true;
        }

        return this;
    },

    setChildren(children) {
        if(IS_DEBUG) {
            if(this._sets & CHILDREN_SET) {
                console.warn('Children are already set and shouldn\'t be set again.');
            }

            this.__isFrozen = false;
        }

        this.children = processChildren(children);

        if(IS_DEBUG) {
            if(Array.isArray(this.children)) {
                Object.freeze(this.children);
            }

            this._sets |= CHILDREN_SET;
            this.__isFrozen = true;
        }

        return this;
    },

    setHtml(html) {
        if(IS_DEBUG) {
            if(this._sets & CHILDREN_SET) {
                console.warn('Children are already set and shouldn\'t be set again.');
            }

            this.__isFrozen = false;
        }

        this.children = html;

        if(IS_DEBUG) {
            this._sets |= CHILDREN_SET;
            this.__isFrozen = true;
        }

        this._escapeChildren = false;
        return this;
    },

    setCtx(ctx) {
        if(ctx !== emptyObj) {
            this._ctx = ctx;

            const { children } = this;

            if(children && typeof children !== 'string') {
                const len = children.length;
                let i = 0;

                while(i < len) {
                    children[i++].setCtx(ctx);
                }
            }
        }

        return this;
    },

    renderToDom(parentNs) {
        if(IS_DEBUG) {
            checkReuse(this, this.tag);
        }

        const { tag, children } = this,
            ns = this._ns || parentNs;

        if(USE_DOM_STRINGS && children && typeof children !== 'string') {
            const domNode = createElementByHtml(this.renderToString(), tag, ns);
            this.adoptDom([domNode], 0);
            return domNode;
        }

        const domNode = this._domNode = createElement(tag, ns),
            { attrs } = this;

        if(children) {
            if(typeof children === 'string') {
                this._escapeChildren?
                    domNode.textContent = children :
                    domNode.innerHTML = children;
            }
            else {
                let i = 0;
                const len = children.length;

                while(i < len) {
                    domNode.appendChild(children[i++].renderToDom(ns));
                }
            }
        }

        if(attrs !== emptyObj) {
            let name, value;
            for(name in attrs) {
                if((value = attrs[name]) != null) {
                    if(ATTRS_TO_EVENTS[name]) {
                        addListener(domNode, ATTRS_TO_EVENTS[name], value);
                    }
                    else {
                        domAttrs(name).set(domNode, name, value);
                    }
                }
            }
        }

        return domNode;
    },

    renderToString() {
        const { tag } = this;

        if(tag === '!') {
            return '<!---->';
        }

        const ns = this._ns,
            { attrs } = this;
        let { children } = this,
            res = '<' + tag;

        if(ns) {
            res += ' xmlns="' + ns + '"';
        }

        if(attrs !== emptyObj) {
            let name, value, attrHtml;
            for(name in attrs) {
                value = attrs[name];

                if(value != null) {
                    if(name === 'value') {
                        switch(tag) {
                            case 'textarea':
                                children = value;
                                continue;

                            case 'select':
                                this.setCtx({ value, multiple : attrs.multiple });
                                continue;

                            case 'option':
                                const ctx = this._ctx;

                                if(ctx.multiple? isInArray(ctx.value, value) : ctx.value === value) {
                                    res += ' ' + domAttrs('selected').toString('selected', true);
                                }
                        }
                    }

                    if(!ATTRS_TO_EVENTS[name] && (attrHtml = domAttrs(name).toString(name, value))) {
                        res += ' ' + attrHtml;
                    }
                }
            }
        }

        if(SHORT_TAGS[tag]) {
            res += '/>';
        }
        else {
            res += '>';

            if(children) {
                if(typeof children === 'string') {
                    res += this._escapeChildren?
                        escapeHtml(children) :
                        children;
                }
                else {
                    let i = 0;
                    const len = children.length;

                    while(i < len) {
                        res += children[i++].renderToString();
                    }
                }
            }

            res += '</' + tag + '>';
        }

        return res;
    },

    adoptDom(domNodes, domIdx) {
        if(IS_DEBUG) {
            checkReuse(this, this.tag);
        }

        const domNode = this._domNode = domNodes[domIdx],
            { attrs, children } = this;

        if(attrs !== emptyObj) {
            let name, value;
            for(name in attrs) {
                if((value = attrs[name]) != null && ATTRS_TO_EVENTS[name]) {
                    addListener(domNode, ATTRS_TO_EVENTS[name], value);
                }
            }
        }

        if(children && typeof children !== 'string') {
            let i = 0;
            const len = children.length;

            if(len) {
                const domChildren = domNode.childNodes;
                let domChildIdx = 0;

                while(i < len) {
                    domChildIdx = children[i++].adoptDom(domChildren, domChildIdx);
                }
            }
        }

        return domIdx + 1;
    },

    mount() {
        const { children } = this;

        if(children && typeof children !== 'string') {
            let i = 0;
            const len = children.length;

            while(i < len) {
                children[i++].mount();
            }
        }

        this._ref && this._ref(this._domNode);
    },

    unmount() {
        const { children } = this;

        if(children && typeof children !== 'string') {
            let i = 0;
            const len = children.length;

            while(i < len) {
                children[i++].unmount();
            }
        }

        removeListeners(this._domNode);

        this._domNode = null;

        this._ref && this._ref(null);
    },

    clone() {
        const res = new TagNode(this.tag);

        if(IS_DEBUG) {
            res.__isFrozen = false;
        }

        res.key = this.key;
        res.attrs = this.attrs;
        res.children = this.children;

        if(IS_DEBUG) {
            res.__isFrozen = true;
        }

        res._sets = NS_SET;
        res._ns = this._ns;
        res._escapeChildren = this._escapeChildren;
        res._ctx = this._ctx;
        res._ref = this._ref;

        return res;
    },

    patch(node) {
        if(this === node) {
            this._patchChildren(node);
        }
        else if(this.type === node.type && this.tag === node.tag && this._ns === node._ns) {
            node._domNode = this._domNode;
            this._patchAttrs(node);
            this._patchChildren(node);
            this._patchRef(node);
        }
        else {
            patchOps.replace(this, node);
        }
    },

    _patchChildren(node) {
        const childrenA = this.children,
            childrenB = node.children;

        if(!childrenA && !childrenB) {
            return;
        }

        const isChildrenAText = typeof childrenA === 'string',
            isChildrenBText = typeof childrenB === 'string';

        if(isChildrenBText) {
            if(isChildrenAText) {
                if(childrenA !== childrenB) {
                    patchOps.updateText(this, childrenB, node._escapeChildren);
                }
                return;
            }

            childrenA && childrenA.length && patchOps.removeChildren(this);
            childrenB && patchOps.updateText(this, childrenB, node._escapeChildren);

            return;
        }

        if(!childrenB || !childrenB.length) {
            if(childrenA) {
                isChildrenAText?
                    patchOps.removeText(this) :
                    childrenA.length && patchOps.removeChildren(this);
            }

            return;
        }

        if(isChildrenAText && childrenA) {
            patchOps.removeText(this);
        }

        if(isChildrenAText || !childrenA || !childrenA.length) {
            const childrenBLen = childrenB.length;
            let iB = 0;

            while(iB < childrenBLen) {
                patchOps.appendChild(node, childrenB[iB++]);
            }

            return;
        }

        patchChildren(this, node);
    },

    _patchAttrs(node) {
        const attrsA = this.attrs,
            attrsB = node.attrs;

        if(attrsA === attrsB) {
            return;
        }

        let attrName;

        if(attrsB !== emptyObj) {
            let attrAVal, attrBVal, isAttrAValArray, isAttrBValArray;

            for(attrName in attrsB) {
                attrBVal = attrsB[attrName];
                if(attrsA === emptyObj || (attrAVal = attrsA[attrName]) == null) {
                    if(attrBVal != null) {
                        patchOps.updateAttr(this, attrName, attrBVal);
                    }
                }
                else if(attrBVal == null) {
                    patchOps.removeAttr(this, attrName);
                }
                else if(typeof attrBVal === 'object' && typeof attrAVal === 'object') {
                    isAttrBValArray = Array.isArray(attrBVal);
                    isAttrAValArray = Array.isArray(attrAVal);
                    if(isAttrBValArray || isAttrAValArray) {
                        if(isAttrBValArray && isAttrAValArray) {
                            this._patchAttrArr(attrName, attrAVal, attrBVal);
                        }
                        else {
                            patchOps.updateAttr(this, attrName, attrBVal);
                        }
                    }
                    else {
                        this._patchAttrObj(attrName, attrAVal, attrBVal);
                    }
                }
                else if(attrAVal !== attrBVal) {
                    patchOps.updateAttr(this, attrName, attrBVal);
                }
            }
        }

        if(attrsA !== emptyObj) {
            for(attrName in attrsA) {
                if((attrsB === emptyObj || !(attrName in attrsB)) && attrsA[attrName] != null) {
                    patchOps.removeAttr(this, attrName);
                }
            }
        }
    },

    _patchAttrArr(attrName, arrA, arrB) {
        if(arrA === arrB) {
            return;
        }

        const lenA = arrA.length;
        let hasDiff = false;

        if(lenA === arrB.length) {
            let i = 0;
            while(!hasDiff && i < lenA) {
                if(arrA[i] != arrB[i]) {
                    hasDiff = true;
                }
                ++i;
            }
        }
        else {
            hasDiff = true;
        }

        hasDiff && patchOps.updateAttr(this, attrName, arrB);
    },

    _patchAttrObj(attrName, objA, objB) {
        if(objA === objB) {
            return;
        }

        const diffObj = {};
        let hasDiff = false;

        for(const i in objB) {
            if(objA[i] != objB[i]) {
                hasDiff = true;
                diffObj[i] = objB[i];
            }
        }

        for(const i in objA) {
            if(objA[i] != null && !(i in objB)) {
                hasDiff = true;
                diffObj[i] = null;
            }
        }

        hasDiff && patchOps.updateAttr(this, attrName, diffObj);
    },

    _patchRef(node) {
        if(this._ref) {
            if(this._ref !== node._ref) {
                this._ref(null);

                if(node._ref) {
                    node._ref(node._domNode);
                }
            }
        }
        else if(node._ref) {
            node._ref(node._domNode);
        }
    }
};

function processChildren(children) {
    if(children == null) {
        return null;
    }

    const typeOfChildren = typeof children;

    if(typeOfChildren === 'object') {
        const res = Array.isArray(children)? children : [children];

        if(IS_DEBUG) {
            checkChildren(res);
        }

        return res;
    }

    return typeOfChildren === 'string'?
        children :
        children.toString();
}

function checkAttrs(attrs) {
    for(const name in attrs) {
        if(name.substr(0, 2) === 'on' && !ATTRS_TO_EVENTS[name]) {
            throw Error(`vidom: Unsupported type of dom event listener "${name}".`);
        }
    }
}
<|endoftext|>


<commit_before>'use strict';
var child_process = require('child_process');
var child = child_process.fork(__dirname + '/child.js');

module.exports = {

  saveBin: function(bin, user) {

  }

};
<commit_msg>Rename child_process to cp<commit_after>'use strict';
var cp = require('child_process');
var child = cp.fork(__dirname + '/child.js');

module.exports = {

  saveBin: function(bin, user) {

  }

};
<|endoftext|>


<commit_before>    var require = require('./define.js');
    var NodeWebSocket = require('./core/nodewebsocket');

    global.WebSocket = NodeWebSocket;
    // Create a colorization function (ANSI output) use ~rb~ to set color in string
    // and ~~ to end colorization.
    console.color = (function colorize() {
        var colors = {
            bl: "30", // black
            bo: "1", // bold current color
            r: "0;31", // red
            g: "0;32", // green
            y: "0;33", // yellow
            b: "0;34", // blue
            m: "0;35", // magenta
            c: "0;36", // cyan
            w: "0;37", // white
            br: "1;31", // bold red
            bg: "1;32", // bold green
            by: "1;33", // bold yellow
            bb: "1;34", // bold blue
            bm: "1;35", // bold magenta
            bc: "1;36", // bold cyan
            bw: "1;37" // bold white
        };
        return function() {
            for (var v = Array.prototype.slice.call(arguments), i = 0; i < v.length; i++) {
                v[i] = String(v[i]).replace(/~(\w*)~/g, function(m, a) {
                    return "\033[" + (colors[a] || 0) + "m";
                }) + "\033[0m";
                process.stdout.write(v[i] + "\n");
            }
        }
    })();
    var argv = process.argv,
        args = {};
    for (var lastkey = '', arg, i = 0; i < argv.length; i++) {
        arg = argv[i];
        if (arg.charAt(0) == '-') {
            lastkey = arg;
            args[lastkey] = true;
        } else {
            args[lastkey] = arg;
        }
    }
    var server = "http://localhost:8080";
    var composition = "example_spirallayout";
    var screen = "default";
    var reload = false;
    if (args["-server"]) server = args["-server"];

    if (args["-composition"]) {
        composition = args["-composition"];
    } else {
        console.log("not starting without composition! use \"-composition composition\" to load composition.dre from the server!");
        process.exit();
    }

    if (args["-screen"]) screen = args["-screen"];
    if (args["-reload"]) reload = process.argv.join(' ');

    if (args["-dali"]) {
        define.SPRITE = "$ROOT/lib/dr/sprite_daliruntime";
        console.color("*** ~bw~D~bb~r~bg~e~by~e~br~m ~bw~Dali Runtime~~ ***");
    } else {
        define.SPRITE = "$ROOT/lib/dr/sprite_headless";
        console.color("*** ~bw~D~bb~r~bg~e~by~e~br~m ~bw~Headless Runtime~~ ***");
    }

    console.color("** using server: ~by~" + server + "~~");
    console.color("** using composition: ~by~" + composition + "~~");
    console.color("** using screen: ~by~" + screen + "~~");
    define.env = "v8";
    var http = require('http');
    var url = require('url');
    var fs = require('fs');
    if (fs.existsSync("./dalicache") == false) {
        fs.mkdir("./dalicache");
    }
    if (fs.existsSync("./dalicache/classes") == false) {
        fs.mkdir("./dalicache/classes");
    }
    if (fs.existsSync("./dalicache/compositions") == false) {
        fs.mkdir("./dalicache/compositions");
    }
    define.MAIN = '';
    var loadedscripts = [];
    // the main dependency download queue counter
    var downloads = 0;
    var script_tags = {};
    var loaded = false;

    function startMain() {
        Unload();

        //the next line is a hack... but we need it for now..
        var JP = require("json-path");
        global.JsonPath = JP;

        define.ROOTSERVER = server;
        define.COMPOSITIONROOT = "./compositions/" +define.filePath( composition )+ "/";
        define.ROOTURL = "compositions/"+ composition + ".dre";
        define.ROOT = define.filePath(module.filename.replace(/\\/g, '/'));
        define.BUILD = "$ROOT/dalicache";
        define.MAIN = "$BUILD/compositions/" + composition + ".dre.screens." + screen + ".js";
        var F = require(define.MAIN)();
        define.startMain();
        loaded = true;
    }

    function Unload() {
        if (loaded == false) return;
        console.color("~~** ~rb~Unloading!~~");
    }

    function Reload() {
        // Reload the application (by replacing the running program with another
	// instance of ourself) if reload is set.
	if (reload) {
            console.log('Reloading application: ' + reload);
            var kexec = require('kexec');
	    kexec(reload);
	}
    }

    // Retrieve the main application file from the server to detect if the file
    // is in edit mode. A reload is invoked ONLY if the file is not in edit
    // mode. No changes to the server are required because this is only needed
    // in the short term.
    function selectiveReload() {
        script_url = server + "/build/compositions/" + composition + ".dre.screens." + screen + ".js";

        var script = {}
        var scripturl = url.parse(script_url);
        var base_path = define.filePath(script_url);
        script.src = script_url;
        script_tags[script_url] = script;

        http.get({
            host: scripturl.hostname,
            port: scripturl.port,
            path: scripturl.path
        }, function(res) {
            res.src = script_url;
            res.data = "";
            res.on('data', function(buf) {
                this.data += buf;
            });
            res.on('end', function() {
                var editable = this.data.indexOf('editable');
                //console.log('*****onend. File loaded', editable);
	        if (editable == -1) {
		    // Reload because the application is not in edit mode
		    Reload();
		}
            });
        }.bind(this));
    }

    function CreateNeededFoldersForFilePath(path) {
        //console.log(path);
        var S = path.split('/');
        var pathsofar = '';
        if (path[0] == '/') pathsofar = '/';
        for (i = 1; i < S.length - 1; i++) {
            pathsofar += S[i] + '/';
            //console.log(pathsofar);
            if (fs.existsSync(pathsofar) == false) {
                fs.mkdir(pathsofar);
            }
        }
    }

    function localExpand(path) {
        var originalroot = define.ROOT;
        var originalbuild = define.BUILD;
        define.BUILD = "$ROOT/dalicache";
        define.ROOT = define.filePath(module.filename.replace(/\\/g, '/'));
        var ret = define.expandVariables(path)
        define.ROOT = originalroot;
        define.BUILD = originalbuild;
        return ret;
    }

    function remoteExpand(path) {
        var originalroot = define.ROOT;
        var originalbuild = define.BUILD;
        define.BUILD = "$ROOT/build";
        define.ROOT = server; // + "/" + composition + "/default";
        var ret = define.expandVariables(path)
        define.ROOT = originalroot;
        define.BUILD = originalbuild;
        return ret;
    }

    function requireWalker(script_url, from_file, save_path) {
        var script = {}
        var scripturl = url.parse(script_url);
        var base_path = define.filePath(script_url);
        script.src = script_url;
        script_tags[script_url] = script;
        downloads++;
        http.get({
            host: scripturl.hostname,
            port: scripturl.port,
            path: scripturl.path
        }, function(res) {
            res.src = script_url;
            res.data = "";
            res.on('data', function(buf) {
                this.data += buf;
            });
            res.on('end', function() {
                if (save_path.indexOf("/dalicache") > -1) {
                    CreateNeededFoldersForFilePath(save_path);
                    fs.writeFileSync(save_path, this.data);
                }
                define.findRequires(this.data).forEach(function(path) {
                    // Make path absolute and process variables
                    var dep_path = define.joinPath(base_path, remoteExpand(path));
                    var local_dep_path = define.joinPath(base_path, localExpand(path));
                    // automatic .js appending if not given
                    if (dep_path.indexOf(".js") != dep_path.length - 3) dep_path += '.js';
                    // load it
                    if (!script_tags[dep_path]) requireWalker(dep_path, script_url, local_dep_path);
                });
                if (!--downloads) {
                    console.color('~~** ~bg~download complete~~.');
                    startMain(); // no more deps
                }
            });
        }.bind(this));
        loadedscripts.push(script);
    }
    var main_file = "./dalicache/compositions/" + composition + ".dre.screens." + screen + ".js";

    function LoadAll() {
        var originalroot = define.ROOT;
        define.ROOT = server + "/" + composition + "/default";
        define.MAIN = server + "/build/compositions/" + composition + ".dre.screens." + screen + ".js";
        requireWalker(define.MAIN, define.ROOT, main_file);
    }
    var sock;
    var sockethost = server + "/compositions/" + composition + ".dre"
    var reconnect = function() {
        // put up websocket.
        console.color("~~** reconnect started");
        if (sock) sock.close();
        sock = new NodeWebSocket(sockethost);
        sock.onError = function(msg) {
            console.log("error in socket!");
            setTimeout(function() {
                reconnect();
            }.bind(this), 500);
        }.bind(this);
        sock.onMessage = function(msg) {
            try {
                msg = JSON.parse(msg);
            } catch (e) {}
            if (msg.type == "sessionCheck") {
                console.color('~~** ~by~Files updated on server: downloading~~.');
		if (loaded) {
		    // selectiveReload only loads the file when not in edit mode
		    selectiveReload();
		    //Reload();
		} else {
		    LoadAll();
		}
            }
        }.bind(this);
        sock.onConnect = function() {
            console.color('~~** ~bg~Connected to server~~.');
        }
        sock.onClose = function() {
            setTimeout(function() {
                reconnect();
            }.bind(this), 500);
        }.bind(this);
    };
    // dali setup code
    var dalicontainer;
    var dalihost;
    var RootActor;
    if (args["-dali"]) {
        var window = {
            x: 0,
            y: 0,
            width: 1920,
            height: 1080,
            transparent: false,
            name: 'Dreem Dali Runtime: ' + composition
        };

        var viewMode = {
            'stereoscopic-mode': 'mono', // stereo-horizontal, stereo-vertical, stereo-interlaced,
            'stereo-base': 65 // Distance in millimeters between left/right cameras typically between (50-70mm)
        };

        var options = {
            'window': window,
            'view-mode': viewMode,
        }

        console.log("** loading Dali")
        global.dali = require('./dalinode/dali')(options);

//        global.dali.stage.add(new global.dali.ImageActor(new global.dali.ResourceImage({url:"./img/shoarma.jpg"})));

        console.color("~~** Dali loaded");
        global.dalihost = require('./lib/dr/sprite_daliruntime/dalihost.js');
        global.dalihost.init();
    }
    // attempt to connect to the notifier service, download initial version and download again if changes have been made.
    reconnect();
    //LoadAll();
<commit_msg>Create the behavior directory if it does not exist. This can happen if there is no /dalicache directory, or it has been removed<commit_after>    var require = require('./define.js');
    var NodeWebSocket = require('./core/nodewebsocket');

    global.WebSocket = NodeWebSocket;
    // Create a colorization function (ANSI output) use ~rb~ to set color in string
    // and ~~ to end colorization.
    console.color = (function colorize() {
        var colors = {
            bl: "30", // black
            bo: "1", // bold current color
            r: "0;31", // red
            g: "0;32", // green
            y: "0;33", // yellow
            b: "0;34", // blue
            m: "0;35", // magenta
            c: "0;36", // cyan
            w: "0;37", // white
            br: "1;31", // bold red
            bg: "1;32", // bold green
            by: "1;33", // bold yellow
            bb: "1;34", // bold blue
            bm: "1;35", // bold magenta
            bc: "1;36", // bold cyan
            bw: "1;37" // bold white
        };
        return function() {
            for (var v = Array.prototype.slice.call(arguments), i = 0; i < v.length; i++) {
                v[i] = String(v[i]).replace(/~(\w*)~/g, function(m, a) {
                    return "\033[" + (colors[a] || 0) + "m";
                }) + "\033[0m";
                process.stdout.write(v[i] + "\n");
            }
        }
    })();
    var argv = process.argv,
        args = {};
    for (var lastkey = '', arg, i = 0; i < argv.length; i++) {
        arg = argv[i];
        if (arg.charAt(0) == '-') {
            lastkey = arg;
            args[lastkey] = true;
        } else {
            args[lastkey] = arg;
        }
    }
    var server = "http://localhost:8080";
    var composition = "example_spirallayout";
    var screen = "default";
    var reload = false;
    if (args["-server"]) server = args["-server"];

    if (args["-composition"]) {
        composition = args["-composition"];
    } else {
        console.log("not starting without composition! use \"-composition composition\" to load composition.dre from the server!");
        process.exit();
    }

    if (args["-screen"]) screen = args["-screen"];
    if (args["-reload"]) reload = process.argv.join(' ');

    if (args["-dali"]) {
        define.SPRITE = "$ROOT/lib/dr/sprite_daliruntime";
        console.color("*** ~bw~D~bb~r~bg~e~by~e~br~m ~bw~Dali Runtime~~ ***");
    } else {
        define.SPRITE = "$ROOT/lib/dr/sprite_headless";
        console.color("*** ~bw~D~bb~r~bg~e~by~e~br~m ~bw~Headless Runtime~~ ***");
    }

    console.color("** using server: ~by~" + server + "~~");
    console.color("** using composition: ~by~" + composition + "~~");
    console.color("** using screen: ~by~" + screen + "~~");
    define.env = "v8";
    var http = require('http');
    var url = require('url');
    var fs = require('fs');

    // Some directories must be manually created
    // (ex: /dalicache is removed)
    var dirs = ["./dalicache", "./dalicache/classes", "./dalicache/classes/behavior", "./dalicache/compositions"];
    for (var i in dirs) {
        var dir = dirs[i];
	console.log('dir', dir, fs.existsSync(dir));
	if (fs.existsSync(dir) == false) {
            fs.mkdir(dir);
	}
    }

    define.MAIN = '';
    var loadedscripts = [];
    // the main dependency download queue counter
    var downloads = 0;
    var script_tags = {};
    var loaded = false;

    function startMain() {
        Unload();

        //the next line is a hack... but we need it for now..
        var JP = require("json-path");
        global.JsonPath = JP;

        define.ROOTSERVER = server;
        define.COMPOSITIONROOT = "./compositions/" +define.filePath( composition )+ "/";
        define.ROOTURL = "compositions/"+ composition + ".dre";
        define.ROOT = define.filePath(module.filename.replace(/\\/g, '/'));
        define.BUILD = "$ROOT/dalicache";
        define.MAIN = "$BUILD/compositions/" + composition + ".dre.screens." + screen + ".js";
        var F = require(define.MAIN)();
        define.startMain();
        loaded = true;
    }

    function Unload() {
        if (loaded == false) return;
        console.color("~~** ~rb~Unloading!~~");
    }

    function Reload() {
        // Reload the application (by replacing the running program with another
	// instance of ourself) if reload is set.
	if (reload) {
            console.log('Reloading application: ' + reload);
            var kexec = require('kexec');
	    kexec(reload);
	}
    }

    // Retrieve the main application file from the server to detect if the file
    // is in edit mode. A reload is invoked ONLY if the file is not in edit
    // mode. No changes to the server are required because this is only needed
    // in the short term.
    function selectiveReload() {
        script_url = server + "/build/compositions/" + composition + ".dre.screens." + screen + ".js";

        var script = {}
        var scripturl = url.parse(script_url);
        var base_path = define.filePath(script_url);
        script.src = script_url;
        script_tags[script_url] = script;

        http.get({
            host: scripturl.hostname,
            port: scripturl.port,
            path: scripturl.path
        }, function(res) {
            res.src = script_url;
            res.data = "";
            res.on('data', function(buf) {
                this.data += buf;
            });
            res.on('end', function() {
                var editable = this.data.indexOf('editable');
                //console.log('*****onend. File loaded', editable);
	        if (editable == -1) {
		    // Reload because the application is not in edit mode
		    Reload();
		}
            });
        }.bind(this));
    }

    function CreateNeededFoldersForFilePath(path) {
        //console.log(path);
        var S = path.split('/');
        var pathsofar = '';
        if (path[0] == '/') pathsofar = '/';
        for (i = 1; i < S.length - 1; i++) {
            pathsofar += S[i] + '/';
            //console.log(pathsofar);
            if (fs.existsSync(pathsofar) == false) {
                fs.mkdir(pathsofar);
            }
        }
    }

    function localExpand(path) {
        var originalroot = define.ROOT;
        var originalbuild = define.BUILD;
        define.BUILD = "$ROOT/dalicache";
        define.ROOT = define.filePath(module.filename.replace(/\\/g, '/'));
        var ret = define.expandVariables(path)
        define.ROOT = originalroot;
        define.BUILD = originalbuild;
        return ret;
    }

    function remoteExpand(path) {
        var originalroot = define.ROOT;
        var originalbuild = define.BUILD;
        define.BUILD = "$ROOT/build";
        define.ROOT = server; // + "/" + composition + "/default";
        var ret = define.expandVariables(path)
        define.ROOT = originalroot;
        define.BUILD = originalbuild;
        return ret;
    }

    function requireWalker(script_url, from_file, save_path) {
        var script = {}
        var scripturl = url.parse(script_url);
        var base_path = define.filePath(script_url);
        script.src = script_url;
        script_tags[script_url] = script;
        downloads++;
        http.get({
            host: scripturl.hostname,
            port: scripturl.port,
            path: scripturl.path
        }, function(res) {
            res.src = script_url;
            res.data = "";
            res.on('data', function(buf) {
                this.data += buf;
            });
            res.on('end', function() {
                if (save_path.indexOf("/dalicache") > -1) {
                    CreateNeededFoldersForFilePath(save_path);
                    fs.writeFileSync(save_path, this.data);
                }
                define.findRequires(this.data).forEach(function(path) {
                    // Make path absolute and process variables
                    var dep_path = define.joinPath(base_path, remoteExpand(path));
                    var local_dep_path = define.joinPath(base_path, localExpand(path));
                    // automatic .js appending if not given
                    if (dep_path.indexOf(".js") != dep_path.length - 3) dep_path += '.js';
                    // load it
                    if (!script_tags[dep_path]) requireWalker(dep_path, script_url, local_dep_path);
                });
                if (!--downloads) {
                    console.color('~~** ~bg~download complete~~.');
                    startMain(); // no more deps
                }
            });
        }.bind(this));
        loadedscripts.push(script);
    }
    var main_file = "./dalicache/compositions/" + composition + ".dre.screens." + screen + ".js";

    function LoadAll() {
        var originalroot = define.ROOT;
        define.ROOT = server + "/" + composition + "/default";
        define.MAIN = server + "/build/compositions/" + composition + ".dre.screens." + screen + ".js";
        requireWalker(define.MAIN, define.ROOT, main_file);
    }
    var sock;
    var sockethost = server + "/compositions/" + composition + ".dre"
    var reconnect = function() {
        // put up websocket.
        console.color("~~** reconnect started");
        if (sock) sock.close();
        sock = new NodeWebSocket(sockethost);
        sock.onError = function(msg) {
            console.log("error in socket!");
            setTimeout(function() {
                reconnect();
            }.bind(this), 500);
        }.bind(this);
        sock.onMessage = function(msg) {
            try {
                msg = JSON.parse(msg);
            } catch (e) {}
            if (msg.type == "sessionCheck") {
                console.color('~~** ~by~Files updated on server: downloading~~.');
		if (loaded) {
		    // selectiveReload only loads the file when not in edit mode
		    selectiveReload();
		    //Reload();
		} else {
		    LoadAll();
		}
            }
        }.bind(this);
        sock.onConnect = function() {
            console.color('~~** ~bg~Connected to server~~.');
        }
        sock.onClose = function() {
            setTimeout(function() {
                reconnect();
            }.bind(this), 500);
        }.bind(this);
    };
    // dali setup code
    var dalicontainer;
    var dalihost;
    var RootActor;
    if (args["-dali"]) {
        var window = {
            x: 0,
            y: 0,
            width: 1920,
            height: 1080,
            transparent: false,
            name: 'Dreem Dali Runtime: ' + composition
        };

        var viewMode = {
            'stereoscopic-mode': 'mono', // stereo-horizontal, stereo-vertical, stereo-interlaced,
            'stereo-base': 65 // Distance in millimeters between left/right cameras typically between (50-70mm)
        };

        var options = {
            'window': window,
            'view-mode': viewMode,
        }

        console.log("** loading Dali")
        global.dali = require('./dalinode/dali')(options);

//        global.dali.stage.add(new global.dali.ImageActor(new global.dali.ResourceImage({url:"./img/shoarma.jpg"})));

        console.color("~~** Dali loaded");
        global.dalihost = require('./lib/dr/sprite_daliruntime/dalihost.js');
        global.dalihost.init();
    }
    // attempt to connect to the notifier service, download initial version and download again if changes have been made.
    reconnect();
    //LoadAll();
<|endoftext|>


<commit_before>export class NumberFormatValueConverter {
  toView(value) {
    return value.toLocaleString('value', {minimumFractionDigits: 0});
  }
}
<commit_msg>feat(sizing): indicate that a value is bigger zero when shown as zero<commit_after>export class NumberFormatValueConverter {
  toView(value) {
    let valueString = value.toLocaleString('value', {minimumFractionDigits: 0});

    if (value > 0 && valueString === '0') {
      return '> 0';
    }

    return valueString;
  }
}
<|endoftext|>