<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name Raster
 *
 * @class The Raster item represents an image in a Paper.js project.
 *
 * @extends PlacedItem
 */
var Raster = this.Raster = PlacedItem.extend(/** @lends Raster# */{
	// TODO: Implement url / type, width, height.
	// TODO: Have PlacedSymbol & Raster inherit from a shared class?
	// DOCS: Document Raster constructor.
	/**
	 * Creates a new raster item and places it in the active layer.
	 *
	 * @param {HTMLImageElement|Canvas|string} [object]
	 */
	initialize: function(object) {
		this.base();
		if (object.getContext) {
			this.setCanvas(object);
		} else {
/*#*/ if (options.browser) {
			// If it's a string, get the element with this id first.
			if (typeof object === 'string')
				object = document.getElementById(object);
/*#*/ } else if (options.server) {
			// If we're running on the server and it's a string,
			// load it from disk:
			if (typeof object === 'string') {
				// TODO: load images async
				var data = fs.readFileSync(object);
				object = new Image();
				object.src = data;
			}
/*#*/ } // options.server
			this.setImage(object);
		}
		this._matrix = new Matrix();
	},

	clone: function() {
		var image = this._image;
		if (!image) {
			// If the Raster contains a Canvas object, we need to create
			// a new one and draw this raster's canvas on it.
			image = CanvasProvider.getCanvas(this._size);
			image.getContext('2d').drawImage(this._canvas, 0, 0);
		}
		var copy = new Raster(image);
		copy._matrix = this._matrix.clone();
		return this._clone(copy);
	},

	/**
	 * The size of the raster in pixels.
	 *
	 * @type Size
	 * @bean
	 */
	getSize: function() {
		return this._size;
	},

	setSize: function() {
		var size = Size.read(arguments),
			// Get reference to image before changing canvas
			image = this.getImage();
		// Setting canvas internally sets _size
		this.setCanvas(CanvasProvider.getCanvas(size));
		// Draw image back onto new canvas
		this.getContext(true).drawImage(image, 0, 0, size.width, size.height);
	},

	/**
	 * The width of the raster in pixels.
	 *
	 * @type Number
	 * @bean
	 */
	getWidth: function() {
		return this._size.width;
	},

	/**
	 * The height of the raster in pixels.
	 *
	 * @type Number
	 * @bean
	 */
	getHeight: function() {
		return this._size.height;
	},

	/**
	 * Pixels per inch of the raster at its current size.
	 *
	 * @type Size
	 * @bean
	 */
	getPpi: function() {
		var matrix = this._matrix,
			orig = new Point(0, 0).transform(matrix),
			u = new Point(1, 0).transform(matrix).subtract(orig),
			v = new Point(0, 1).transform(matrix).subtract(orig);
		return new Size(
			72 / u.getLength(),
			72 / v.getLength()
		);
	},

	/**
	 * The Canvas 2d drawing context of the raster.
	 *
	 * @type Context
	 * @bean
	 */
	getContext: function() {
		if (!this._context)
			this._context = this.getCanvas().getContext('2d');
		// Support a hidden parameter that indicates if the context will be used
		// to modify the Raster object. We can notify such changes ahead since
		// they are only used afterwards for redrawing.
		if (arguments[0])
			this._changed(Change.PIXELS);
		return this._context;
	},

	setContext: function(context) {
		this._context = context;
	},

	getCanvas: function() {
		if (!this._canvas) {
			this._canvas = CanvasProvider.getCanvas(this._size);
			if (this._image)
				this.getContext(true).drawImage(this._image, 0, 0);
		}
		return this._canvas;
	},

	setCanvas: function(canvas) {
		if (this._canvas)
			CanvasProvider.returnCanvas(this._canvas);
		this._canvas = canvas;
		this._size = new Size(canvas.width, canvas.height);
		this._image = null;
		this._context = null;
		this._changed(Change.GEOMETRY);
	},

	/**
	 * The HTMLImageElement or Canvas of the raster.
	 *
	 * @type HTMLImageElement|Canvas
	 * @bean
	 */
	getImage: function() {
		return this._image || this.getCanvas();
	},

	// TODO: Support string id of image element.
	setImage: function(image) {
		if (this._canvas)
			CanvasProvider.returnCanvas(this._canvas);
		this._image = image;
/*#*/ if (options.browser) {
		this._size = new Size(image.naturalWidth, image.naturalHeight);
/*#*/ } else if (options.server) {
		this._size = new Size(image.width, image.height);
/*#*/ } // options.server
		this._canvas = null;
		this._context = null;
		this._changed(Change.GEOMETRY);
	},

	// DOCS: document Raster#getSubImage
	/**
	 * @param {Rectangle} rect the boundaries of the sub image in pixel
	 * coordinates
	 *
	 * @return {Canvas}
	 */
	getSubImage: function(rect) {
		rect = Rectangle.read(arguments);
		var canvas = CanvasProvider.getCanvas(rect.getSize());
		canvas.getContext('2d').drawImage(this.getCanvas(), rect.x, rect.y,
				canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
		return canvas;
	},

	/**
	 * Draws an image on the raster.
	 *
	 * @param {HTMLImageELement|Canvas} image
	 * @param {Point} point the offset of the image as a point in pixel
	 * coordinates
	 */
	drawImage: function(image, point) {
		point = Point.read(arguments, 1);
		this.getContext(true).drawImage(image, point.x, point.y);
	},

	/**
	 * Calculates the average color of the image within the given path,
	 * rectangle or point. This can be used for creating raster image
	 * effects.
	 *
	 * @param {Path|Rectangle|Point} object
	 * @return {RgbColor} the average color contained in the area covered by the
	 * specified path, rectangle or point.
	 */
	getAverageColor: function(object) {
		if (!object)
			object = this.getBounds();
		var bounds, path;
		if (object instanceof PathItem) {
			// TODO: What if the path is smaller than 1 px?
			// TODO: How about rounding of bounds.size?
			path = object;
			bounds = object.getBounds();
		} else if (object.width) {
			bounds = new Rectangle(object);
		} else if (object.x) {
			bounds = Rectangle.create(object.x - 0.5, object.y - 0.5, 1, 1);
		}
		// Use a sample size of max 32 x 32 pixels, into which the path is
		// scaled as a clipping path, and then the actual image is drawn in and
		// sampled.
		var sampleSize = 32,
			width = Math.min(bounds.width, sampleSize),
			height = Math.min(bounds.height, sampleSize);
		// Reuse the same sample context for speed. Memory consumption is low
		// since it's only 32 x 32 pixels.
		var ctx = Raster._sampleContext;
		if (!ctx) {
			ctx = Raster._sampleContext = CanvasProvider.getCanvas(
					new Size(sampleSize)).getContext('2d');
		} else {
			// Clear the sample canvas:
			ctx.clearRect(0, 0, sampleSize, sampleSize);
		}
		ctx.save();
		// Scale the context so that the bounds ends up at the given sample size
		ctx.scale(width / bounds.width, height / bounds.height);
		ctx.translate(-bounds.x, -bounds.y);
		// If a path was passed, draw it as a clipping mask:
		if (path)
			path.draw(ctx, { clip: true });
		// Now draw the image clipped into it.
		this._matrix.applyToContext(ctx);
		ctx.drawImage(this._canvas || this._image,
				-this._size.width / 2, -this._size.height / 2);
		ctx.restore();
		// Get pixel data from the context and calculate the average color value
		// from it, taking alpha into account.
		var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
				Math.ceil(height)).data,
			channels = [0, 0, 0],
			total = 0;
		for (var i = 0, l = pixels.length; i < l; i += 4) {
			var alpha = pixels[i + 3];
			total += alpha;
			alpha /= 255;
			channels[0] += pixels[i] * alpha;
			channels[1] += pixels[i + 1] * alpha;
			channels[2] += pixels[i + 2] * alpha;
		}
		for (var i = 0; i < 3; i++)
			channels[i] /= total;
		return total ? Color.read(channels) : null;
	},

	/**
	 * {@grouptitle Pixels}
	 * Gets the color of a pixel in the raster.
	 *
	 * @name Raster#getPixel
	 * @function
	 * @param x the x offset of the pixel in pixel coordinates
	 * @param y the y offset of the pixel in pixel coordinates
	 * @return {RgbColor} the color of the pixel
	 */
	/**
	 * Gets the color of a pixel in the raster.
	 *
	 * @name Raster#getPixel
	 * @function
	 * @param point the offset of the pixel as a point in pixel coordinates
	 * @return {RgbColor} the color of the pixel
	 */
	getPixel: function(point) {
		point = Point.read(arguments);
		var pixels = this.getContext().getImageData(point.x, point.y, 1, 1).data,
			channels = new Array(4);
		for (var i = 0; i < 4; i++)
			channels[i] = pixels[i] / 255;
		return RgbColor.read(channels);
	},

	/**
	 * Sets the color of the specified pixel to the specified color.
	 *
	 * @name Raster#setPixel
	 * @function
	 * @param x the x offset of the pixel in pixel coordinates
	 * @param y the y offset of the pixel in pixel coordinates
	 * @param color the color that the pixel will be set to
	 */
	/**
	 * Sets the color of the specified pixel to the specified color.
	 *
	 * @name Raster#setPixel
	 * @function
	 * @param point the offset of the pixel as a point in pixel coordinates
	 * @param color the color that the pixel will be set to
	 */
	setPixel: function(point, color) {
		var hasPoint = arguments.length == 2;
		point = Point.read(arguments, 0, hasPoint ? 1 : 2);
		color = Color.read(arguments, hasPoint ? 1 : 2);
		var ctx = this.getContext(true),
			imageData = ctx.createImageData(1, 1),
			alpha = color.getAlpha();
		imageData.data[0] = color.getRed() * 255;
		imageData.data[1] = color.getGreen() * 255;
		imageData.data[2] = color.getBlue() * 255;
		imageData.data[3] = alpha != null ? alpha * 255 : 255;
		ctx.putImageData(imageData, point.x, point.y);
	},

	// DOCS: document Raster#createData
	/**
	 * {@grouptitle Image Data}
	 * @param {Size} size
	 * @return {ImageData}
	 */
	createData: function(size) {
		size = Size.read(arguments);
		return this.getContext().createImageData(size.width, size.height);
	},

	// TODO: Rename to #get/setImageData, as it will conflict with Item#getData
	// DOCS: document Raster#getData
	/**
	 * @param {Rectangle} rect
	 * @return {ImageData}
	 */
	getData: function(rect) {
		rect = Rectangle.read(arguments);
		if (rect.isEmpty())
			rect = new Rectangle(this.getSize());
		return this.getContext().getImageData(rect.x, rect.y,
				rect.width, rect.height);
	},

	// DOCS: document Raster#setData
	/**
	 * @param {ImageData} data
	 * @param {Point} point
	 * @return {ImageData}
	 */
	setData: function(data, point) {
		point = Point.read(arguments, 1);
		this.getContext(true).putImageData(data, point.x, point.y);
	},

	_calculateBounds: function(getter, matrix) {
		// The getter is only used for PlacedSymbol, not Raster
		return matrix._transformBounds(
				new Rectangle(this._size).setCenter(0, 0));
	},

	// Since Raster doesn't make the distinction between the different bounds,
	// simply redirect to strokeBounds so the cached values can be reused.

	getHandleBounds: function(/* matrix */) {
		return this.getStrokeBounds(arguments[0]);
	},

	getRoughBounds: function(/* matrix */) {
		return this.getStrokeBounds(arguments[0]);
	},

	_hitTest: function(point, options) {
		point = this._matrix._inverseTransform(point);
		if (point.isInside(new Rectangle(this._size).setCenter(0, 0))) {
			var that = this;
			return new HitResult('pixel', that, {
				offset: point.add(that._size.divide(2)).round(),
				// Becomes HitResult#color
				getColor: function() {
					return that.getPixel(this.offset);
				}
			});
		}
	},

	draw: function(ctx, param) {
		if (param.selection) {
			var bounds = new Rectangle(this._size).setCenter(0, 0);
			Item.drawSelectedBounds(bounds, ctx, this._matrix);
		} else {
			ctx.save();
			this._matrix.applyToContext(ctx);
			ctx.drawImage(this._canvas || this._image,
					-this._size.width / 2, -this._size.height / 2);
			ctx.restore();
		}
	}
});
<commit_msg>Add comment about upcoming changes relating to bounds.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * All rights reserved.
 */

/**
 * @name Raster
 *
 * @class The Raster item represents an image in a Paper.js project.
 *
 * @extends PlacedItem
 */
var Raster = this.Raster = PlacedItem.extend(/** @lends Raster# */{
	// TODO: Implement url / type, width, height.
	// TODO: Have PlacedSymbol & Raster inherit from a shared class?
	// DOCS: Document Raster constructor.
	/**
	 * Creates a new raster item and places it in the active layer.
	 *
	 * @param {HTMLImageElement|Canvas|string} [object]
	 */
	initialize: function(object) {
		this.base();
		if (object.getContext) {
			this.setCanvas(object);
		} else {
/*#*/ if (options.browser) {
			// If it's a string, get the element with this id first.
			if (typeof object === 'string')
				object = document.getElementById(object);
/*#*/ } else if (options.server) {
			// If we're running on the server and it's a string,
			// load it from disk:
			if (typeof object === 'string') {
				// TODO: load images async
				var data = fs.readFileSync(object);
				object = new Image();
				object.src = data;
			}
/*#*/ } // options.server
			this.setImage(object);
		}
		this._matrix = new Matrix();
	},

	clone: function() {
		var image = this._image;
		if (!image) {
			// If the Raster contains a Canvas object, we need to create
			// a new one and draw this raster's canvas on it.
			image = CanvasProvider.getCanvas(this._size);
			image.getContext('2d').drawImage(this._canvas, 0, 0);
		}
		var copy = new Raster(image);
		copy._matrix = this._matrix.clone();
		return this._clone(copy);
	},

	/**
	 * The size of the raster in pixels.
	 *
	 * @type Size
	 * @bean
	 */
	getSize: function() {
		return this._size;
	},

	setSize: function() {
		var size = Size.read(arguments),
			// Get reference to image before changing canvas
			image = this.getImage();
		// Setting canvas internally sets _size
		this.setCanvas(CanvasProvider.getCanvas(size));
		// Draw image back onto new canvas
		this.getContext(true).drawImage(image, 0, 0, size.width, size.height);
	},

	/**
	 * The width of the raster in pixels.
	 *
	 * @type Number
	 * @bean
	 */
	getWidth: function() {
		return this._size.width;
	},

	/**
	 * The height of the raster in pixels.
	 *
	 * @type Number
	 * @bean
	 */
	getHeight: function() {
		return this._size.height;
	},

	/**
	 * Pixels per inch of the raster at its current size.
	 *
	 * @type Size
	 * @bean
	 */
	getPpi: function() {
		var matrix = this._matrix,
			orig = new Point(0, 0).transform(matrix),
			u = new Point(1, 0).transform(matrix).subtract(orig),
			v = new Point(0, 1).transform(matrix).subtract(orig);
		return new Size(
			72 / u.getLength(),
			72 / v.getLength()
		);
	},

	/**
	 * The Canvas 2d drawing context of the raster.
	 *
	 * @type Context
	 * @bean
	 */
	getContext: function() {
		if (!this._context)
			this._context = this.getCanvas().getContext('2d');
		// Support a hidden parameter that indicates if the context will be used
		// to modify the Raster object. We can notify such changes ahead since
		// they are only used afterwards for redrawing.
		if (arguments[0])
			this._changed(Change.PIXELS);
		return this._context;
	},

	setContext: function(context) {
		this._context = context;
	},

	getCanvas: function() {
		if (!this._canvas) {
			this._canvas = CanvasProvider.getCanvas(this._size);
			if (this._image)
				this.getContext(true).drawImage(this._image, 0, 0);
		}
		return this._canvas;
	},

	setCanvas: function(canvas) {
		if (this._canvas)
			CanvasProvider.returnCanvas(this._canvas);
		this._canvas = canvas;
		this._size = new Size(canvas.width, canvas.height);
		this._image = null;
		this._context = null;
		this._changed(Change.GEOMETRY);
	},

	/**
	 * The HTMLImageElement or Canvas of the raster.
	 *
	 * @type HTMLImageElement|Canvas
	 * @bean
	 */
	getImage: function() {
		return this._image || this.getCanvas();
	},

	// TODO: Support string id of image element.
	setImage: function(image) {
		if (this._canvas)
			CanvasProvider.returnCanvas(this._canvas);
		this._image = image;
/*#*/ if (options.browser) {
		this._size = new Size(image.naturalWidth, image.naturalHeight);
/*#*/ } else if (options.server) {
		this._size = new Size(image.width, image.height);
/*#*/ } // options.server
		this._canvas = null;
		this._context = null;
		this._changed(Change.GEOMETRY);
	},

	// DOCS: document Raster#getSubImage
	/**
	 * @param {Rectangle} rect the boundaries of the sub image in pixel
	 * coordinates
	 *
	 * @return {Canvas}
	 */
	getSubImage: function(rect) {
		rect = Rectangle.read(arguments);
		var canvas = CanvasProvider.getCanvas(rect.getSize());
		canvas.getContext('2d').drawImage(this.getCanvas(), rect.x, rect.y,
				canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
		return canvas;
	},

	/**
	 * Draws an image on the raster.
	 *
	 * @param {HTMLImageELement|Canvas} image
	 * @param {Point} point the offset of the image as a point in pixel
	 * coordinates
	 */
	drawImage: function(image, point) {
		point = Point.read(arguments, 1);
		this.getContext(true).drawImage(image, point.x, point.y);
	},

	/**
	 * Calculates the average color of the image within the given path,
	 * rectangle or point. This can be used for creating raster image
	 * effects.
	 *
	 * @param {Path|Rectangle|Point} object
	 * @return {RgbColor} the average color contained in the area covered by the
	 * specified path, rectangle or point.
	 */
	getAverageColor: function(object) {
		if (!object)
			object = this.getBounds();
		var bounds, path;
		if (object instanceof PathItem) {
			// TODO: What if the path is smaller than 1 px?
			// TODO: How about rounding of bounds.size?
			path = object;
			bounds = object.getBounds();
		} else if (object.width) {
			bounds = new Rectangle(object);
		} else if (object.x) {
			bounds = Rectangle.create(object.x - 0.5, object.y - 0.5, 1, 1);
		}
		// Use a sample size of max 32 x 32 pixels, into which the path is
		// scaled as a clipping path, and then the actual image is drawn in and
		// sampled.
		var sampleSize = 32,
			width = Math.min(bounds.width, sampleSize),
			height = Math.min(bounds.height, sampleSize);
		// Reuse the same sample context for speed. Memory consumption is low
		// since it's only 32 x 32 pixels.
		var ctx = Raster._sampleContext;
		if (!ctx) {
			ctx = Raster._sampleContext = CanvasProvider.getCanvas(
					new Size(sampleSize)).getContext('2d');
		} else {
			// Clear the sample canvas:
			ctx.clearRect(0, 0, sampleSize, sampleSize);
		}
		ctx.save();
		// Scale the context so that the bounds ends up at the given sample size
		ctx.scale(width / bounds.width, height / bounds.height);
		ctx.translate(-bounds.x, -bounds.y);
		// If a path was passed, draw it as a clipping mask:
		if (path)
			path.draw(ctx, { clip: true });
		// Now draw the image clipped into it.
		this._matrix.applyToContext(ctx);
		ctx.drawImage(this._canvas || this._image,
				-this._size.width / 2, -this._size.height / 2);
		ctx.restore();
		// Get pixel data from the context and calculate the average color value
		// from it, taking alpha into account.
		var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
				Math.ceil(height)).data,
			channels = [0, 0, 0],
			total = 0;
		for (var i = 0, l = pixels.length; i < l; i += 4) {
			var alpha = pixels[i + 3];
			total += alpha;
			alpha /= 255;
			channels[0] += pixels[i] * alpha;
			channels[1] += pixels[i + 1] * alpha;
			channels[2] += pixels[i + 2] * alpha;
		}
		for (var i = 0; i < 3; i++)
			channels[i] /= total;
		return total ? Color.read(channels) : null;
	},

	/**
	 * {@grouptitle Pixels}
	 * Gets the color of a pixel in the raster.
	 *
	 * @name Raster#getPixel
	 * @function
	 * @param x the x offset of the pixel in pixel coordinates
	 * @param y the y offset of the pixel in pixel coordinates
	 * @return {RgbColor} the color of the pixel
	 */
	/**
	 * Gets the color of a pixel in the raster.
	 *
	 * @name Raster#getPixel
	 * @function
	 * @param point the offset of the pixel as a point in pixel coordinates
	 * @return {RgbColor} the color of the pixel
	 */
	getPixel: function(point) {
		point = Point.read(arguments);
		var pixels = this.getContext().getImageData(point.x, point.y, 1, 1).data,
			channels = new Array(4);
		for (var i = 0; i < 4; i++)
			channels[i] = pixels[i] / 255;
		return RgbColor.read(channels);
	},

	/**
	 * Sets the color of the specified pixel to the specified color.
	 *
	 * @name Raster#setPixel
	 * @function
	 * @param x the x offset of the pixel in pixel coordinates
	 * @param y the y offset of the pixel in pixel coordinates
	 * @param color the color that the pixel will be set to
	 */
	/**
	 * Sets the color of the specified pixel to the specified color.
	 *
	 * @name Raster#setPixel
	 * @function
	 * @param point the offset of the pixel as a point in pixel coordinates
	 * @param color the color that the pixel will be set to
	 */
	setPixel: function(point, color) {
		var hasPoint = arguments.length == 2;
		point = Point.read(arguments, 0, hasPoint ? 1 : 2);
		color = Color.read(arguments, hasPoint ? 1 : 2);
		var ctx = this.getContext(true),
			imageData = ctx.createImageData(1, 1),
			alpha = color.getAlpha();
		imageData.data[0] = color.getRed() * 255;
		imageData.data[1] = color.getGreen() * 255;
		imageData.data[2] = color.getBlue() * 255;
		imageData.data[3] = alpha != null ? alpha * 255 : 255;
		ctx.putImageData(imageData, point.x, point.y);
	},

	// DOCS: document Raster#createData
	/**
	 * {@grouptitle Image Data}
	 * @param {Size} size
	 * @return {ImageData}
	 */
	createData: function(size) {
		size = Size.read(arguments);
		return this.getContext().createImageData(size.width, size.height);
	},

	// TODO: Rename to #get/setImageData, as it will conflict with Item#getData
	// DOCS: document Raster#getData
	/**
	 * @param {Rectangle} rect
	 * @return {ImageData}
	 */
	getData: function(rect) {
		rect = Rectangle.read(arguments);
		if (rect.isEmpty())
			rect = new Rectangle(this.getSize());
		return this.getContext().getImageData(rect.x, rect.y,
				rect.width, rect.height);
	},

	// DOCS: document Raster#setData
	/**
	 * @param {ImageData} data
	 * @param {Point} point
	 * @return {ImageData}
	 */
	setData: function(data, point) {
		point = Point.read(arguments, 1);
		this.getContext(true).putImageData(data, point.x, point.y);
	},

	_calculateBounds: function(getter, matrix) {
		// The getter is only used for PlacedSymbol, not Raster
		return matrix._transformBounds(
				new Rectangle(this._size).setCenter(0, 0));
	},

	// Since Raster doesn't make the distinction between the different bounds,
	// simply redirect to strokeBounds so the cached values can be reused.
	// TODO: Shouldn't this be moved to PlacedItem

	getHandleBounds: function(/* matrix */) {
		return this.getStrokeBounds(arguments[0]);
	},

	getRoughBounds: function(/* matrix */) {
		return this.getStrokeBounds(arguments[0]);
	},

	_hitTest: function(point, options) {
		point = this._matrix._inverseTransform(point);
		if (point.isInside(new Rectangle(this._size).setCenter(0, 0))) {
			var that = this;
			return new HitResult('pixel', that, {
				offset: point.add(that._size.divide(2)).round(),
				// Becomes HitResult#color
				getColor: function() {
					return that.getPixel(this.offset);
				}
			});
		}
	},

	draw: function(ctx, param) {
		if (param.selection) {
			var bounds = new Rectangle(this._size).setCenter(0, 0);
			Item.drawSelectedBounds(bounds, ctx, this._matrix);
		} else {
			ctx.save();
			this._matrix.applyToContext(ctx);
			ctx.drawImage(this._canvas || this._image,
					-this._size.width / 2, -this._size.height / 2);
			ctx.restore();
		}
	}
});
<|endoftext|>


<commit_before>/**
 * @license
 * This file is written by MemoriesOff (https://github.com/MemoriesOff)
 * you can use it based on the Apache License, Version 2.0
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * =============================================================================
 */

var inputFileAddress = document.getElementById('upload-image');
var imgUrl=document.getElementById('image-url');
var inputImg = document.getElementById('input-image');
var inputImgLarge=document.getElementById('input-image-large');
var stateOutput=document.getElementById('status-message');
var runButton=document.getElementById('run-button');
var fcnType=document.getElementById('fcn-type');
var outputImg=document.getElementById('output-image');
var outputLabel=document.getElementById('output-label');
var inputSizeWidth=document.getElementById('inputSize-width');
var inputSizeHeight=document.getElementById('inputSize-height');

var network=new SemanticSegmentation("../static/semanticDemo/web_model/model.json",[512,512]);
var colorMap=[[155,155,200],[174,199,232],[255,127,14],[255,187,120],[44,160,44],[152,223,138],[214,39,40],[255,152,150],[148,103,189],[197,176,213],[140,86,75],[196,156,148],[227,119,194],[247,182,210],[127,127,127],[31,119,180],[188,189,34],[219,219,141],[23,190,207],[158,218,229],[199,199,199]];
network.load().then(()=>{
	stateOutput.innerHTML="models loading success";
	runButton.classList.remove("is-loading");
});
imgUrl.oninput=function(){
	var url=imgUrl.value;
	var reg=/http:\/\/.+/;
	var reg2=/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/;
	if(!(reg.test(url)&&reg2.test(url))){
		stateOutput.innerHTML="The URL you entered is not valid.";
	}else{
		inputImg.src = url;
		stateOutput.innerHTML="Loading image...";
		document.getElementById("input-card").classList.remove("is-invisible");

	}
};
inputImg.onerror=function(){
	stateOutput.innerHTML="image loading errow";
}
inputImg.onload=function(){
	stateOutput.innerHTML="image loading success";
}

inputFileAddress.onchange = function () {
	//1.获取选中的文件列表
	var fileList = inputFileAddress.files;
	var file = fileList[0];
	//读取文件内容
	var reader = new FileReader();
	reader.readAsDataURL(file);
	reader.onload = function (e) {
		//将结果显示到文本框
		imgUrl.value=inputFileAddress.value;
		//showCanvas(reader.result);
		inputImg.src = reader.result;
		document.getElementById("input-card").classList.remove("is-invisible");
	}
}

runButton.onclick=async function(){
	if(stateOutput.innerHTML!="image loading success"&&stateOutput.innerHTML.indexOf('running finish.')==-1){
		stateOutput.innerHTML="image loading errow";
	}else{
		inputImgLarge.src=inputImg.src;
		stateOutput.innerHTML="start running"
		var start = new Date().getTime();
		const alpha=0.8;
		var hashmap=new Array(21);
		network.modelPixels=[Number(inputSizeHeight.value),Number(inputSizeWidth.value)];
		var netOutput=await network.predict(inputImgLarge,false,fcnType.value=="fcn32").data();
		//var canvas =document.createElement('canvas');
		var canvas =outputImg;
		var ctx = canvas.getContext('2d');
		canvas.width=inputImgLarge.width;
		canvas.height=inputImgLarge.height;
		ctx.drawImage(inputImgLarge, 0, 0, inputImgLarge.width, inputImgLarge.height);
		var imgData=ctx.getImageData(0, 0,inputImgLarge.width, inputImgLarge.height);
		for(var i=0;i<netOutput.length;i++){
			   hashmap[netOutput[i]]=1;
			   imgData.data[4*i+0]=colorMap[netOutput[i]][0]*alpha+imgData.data[4*i+0]*(1-alpha);
			   imgData.data[4*i+1]=colorMap[netOutput[i]][1]*alpha+imgData.data[4*i+1]*(1-alpha);
			   imgData.data[4*i+2]=colorMap[netOutput[i]][2]*alpha+imgData.data[4*i+2]*(1-alpha);
			   imgData.data[4*i+3]=255;
		}
		ctx.putImageData(imgData,0, 0);
		//outputImg.src="url("+canvas.toDataURL("png")+")";
		var label_ctx=outputLabel.getContext('2d');
		var g=0;
		for(var i=0; i<hashmap.length;i++){
			if(hashmap[i]===1) g++;
		}
		outputLabel.height=g*outputLabel.width/4*3;
		for(var i=0; i<hashmap.length;i++){
			if(hashmap[i]===1){

				label_ctx.beginPath()
				label_ctx.rect(0,g,outputLabel.width,outputLabel.width/16*9);
				label_ctx.fillStyle='rgb('+colorMap[i][0]+','+colorMap[i][1]+','+colorMap[i][2]+')';
				label_ctx.fill();
				label_ctx.beginPath()
				label_ctx.font = outputLabel.width/16*2+"px serif";
				label_ctx.fillStyle='#fff';
				label_ctx.textAlign='center';//文本水平对齐方式
				label_ctx.textBaseline='middle';//文本垂直方向，基线位置
				label_ctx.fillText(network.class_names[i], outputLabel.width/2, g+outputLabel.width/32*9);
				g=g+outputLabel.width/4*3;

			}
		}
		document.getElementById("output-card").classList.remove("is-invisible");
		document.getElementById("legend-card").classList.remove("is-invisible");
		var end = new Date().getTime();
		stateOutput.innerHTML="running finish. time: "+(end-start)+" ms";
	}
}
<commit_msg>change model<commit_after>/**
 * @license
 * This file is written by MemoriesOff (https://github.com/MemoriesOff)
 * you can use it based on the Apache License, Version 2.0
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * =============================================================================
 */

var inputFileAddress = document.getElementById('upload-image');
var imgUrl=document.getElementById('image-url');
var inputImg = document.getElementById('input-image');
var inputImgLarge=document.getElementById('input-image-large');
var stateOutput=document.getElementById('status-message');
var runButton=document.getElementById('run-button');
var fcnType=document.getElementById('fcn-type');
var outputImg=document.getElementById('output-image');
var outputLabel=document.getElementById('output-label');
var inputSizeWidth=document.getElementById('inputSize-width');
var inputSizeHeight=document.getElementById('inputSize-height');

var network=new SemanticSegmentation("../static/semanticDemo/web_model2/model.json",[512,512]);
var colorMap=[[155,155,200],[174,199,232],[255,127,14],[255,187,120],[44,160,44],[152,223,138],[214,39,40],[255,152,150],[148,103,189],[197,176,213],[140,86,75],[196,156,148],[227,119,194],[247,182,210],[127,127,127],[31,119,180],[188,189,34],[219,219,141],[23,190,207],[158,218,229],[199,199,199]];
network.load().then(()=>{
	stateOutput.innerHTML="models loading success";
	runButton.classList.remove("is-loading");
});
imgUrl.oninput=function(){
	var url=imgUrl.value;
	var reg=/http:\/\/.+/;
	var reg2=/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/;
	if(!(reg.test(url)&&reg2.test(url))){
		stateOutput.innerHTML="The URL you entered is not valid.";
	}else{
		inputImg.src = url;
		stateOutput.innerHTML="Loading image...";
		document.getElementById("input-card").classList.remove("is-invisible");

	}
};
inputImg.onerror=function(){
	stateOutput.innerHTML="image loading errow";
}
inputImg.onload=function(){
	stateOutput.innerHTML="image loading success";
}

inputFileAddress.onchange = function () {
	//1.获取选中的文件列表
	var fileList = inputFileAddress.files;
	var file = fileList[0];
	//读取文件内容
	var reader = new FileReader();
	reader.readAsDataURL(file);
	reader.onload = function (e) {
		//将结果显示到文本框
		imgUrl.value=inputFileAddress.value;
		//showCanvas(reader.result);
		inputImg.src = reader.result;
		document.getElementById("input-card").classList.remove("is-invisible");
	}
}

runButton.onclick=async function(){
	if(stateOutput.innerHTML!="image loading success"&&stateOutput.innerHTML.indexOf('running finish.')==-1){
		stateOutput.innerHTML="image loading errow";
	}else{
		inputImgLarge.src=inputImg.src;
		stateOutput.innerHTML="start running"
		var start = new Date().getTime();
		const alpha=0.8;
		var hashmap=new Array(21);
		network.modelPixels=[Number(inputSizeHeight.value),Number(inputSizeWidth.value)];
		var netOutput=await network.predict(inputImgLarge,false,fcnType.value=="fcn32").data();
		//var canvas =document.createElement('canvas');
		var canvas =outputImg;
		var ctx = canvas.getContext('2d');
		canvas.width=inputImgLarge.width;
		canvas.height=inputImgLarge.height;
		ctx.drawImage(inputImgLarge, 0, 0, inputImgLarge.width, inputImgLarge.height);
		var imgData=ctx.getImageData(0, 0,inputImgLarge.width, inputImgLarge.height);
		for(var i=0;i<netOutput.length;i++){
			   hashmap[netOutput[i]]=1;
			   imgData.data[4*i+0]=colorMap[netOutput[i]][0]*alpha+imgData.data[4*i+0]*(1-alpha);
			   imgData.data[4*i+1]=colorMap[netOutput[i]][1]*alpha+imgData.data[4*i+1]*(1-alpha);
			   imgData.data[4*i+2]=colorMap[netOutput[i]][2]*alpha+imgData.data[4*i+2]*(1-alpha);
			   imgData.data[4*i+3]=255;
		}
		ctx.putImageData(imgData,0, 0);
		//outputImg.src="url("+canvas.toDataURL("png")+")";
		var label_ctx=outputLabel.getContext('2d');
		var g=0;
		for(var i=0; i<hashmap.length;i++){
			if(hashmap[i]===1) g++;
		}
		outputLabel.height=g*outputLabel.width/4*3;
		for(var i=0; i<hashmap.length;i++){
			if(hashmap[i]===1){

				label_ctx.beginPath()
				label_ctx.rect(0,g,outputLabel.width,outputLabel.width/16*9);
				label_ctx.fillStyle='rgb('+colorMap[i][0]+','+colorMap[i][1]+','+colorMap[i][2]+')';
				label_ctx.fill();
				label_ctx.beginPath()
				label_ctx.font = outputLabel.width/16*2+"px serif";
				label_ctx.fillStyle='#fff';
				label_ctx.textAlign='center';//文本水平对齐方式
				label_ctx.textBaseline='middle';//文本垂直方向，基线位置
				label_ctx.fillText(network.class_names[i], outputLabel.width/2, g+outputLabel.width/32*9);
				g=g+outputLabel.width/4*3;

			}
		}
		document.getElementById("output-card").classList.remove("is-invisible");
		document.getElementById("legend-card").classList.remove("is-invisible");
		var end = new Date().getTime();
		stateOutput.innerHTML="running finish. time: "+(end-start)+" ms";
	}
}
<|endoftext|>


<commit_before>const WORKOUT_SEPARATOR = '\n\n';
const WHITESPACE = /\s/;
var cfg = window.cfg;

function toHtml(text) {
	if (Array.isArray(text))
		return text.map(toHtml).join('
')
	else if (text !== null && text !== undefined)
		return text.replace(/\n/g, '
');
	else
		return '';
}

function getProp(obj, path) {
	const PATH_DELIM = '.';
	if (typeof path === 'string') {
		path = path.split(PATH_DELIM);
	}
	var prop = obj;

	while (path.length && obj && obj !== null) {
		prop = obj[path[0]];
		path = path.slice(1);
	}

	return prop;
}

/**
 * Takes in text containing slash separated date e.g. 2015/03/01
 * returns first date found as unix time
 * returns null if no date found
 * TODO: adjust for timezones
 */
function getDate(text, context) {
	const WORKOUT_HEADER_DATE_REGEXP = /(\d+\/\d+\/\d+)\s/;
	var dateString = getProp(text.match(WORKOUT_HEADER_DATE_REGEXP), [1]);
	if (!dateString) {
		return null;
	} else {
		dateString.replace(/\//g, '-');
		return Date.parse(dateString);
	}
}

/**
 * Takes in text containing unit of weight
 * returns first unit of weight found
 * returns user's default unit of weight if no date found
 */
function getUnitOfWeight(text, context) {
	if (text.contains('lbs') || text.contains('lb'))
		return cfg.unitOfWeight.pounds;
	else if (text.contains('kgs') || text.contains('kg'))
		return cfg.unitOfWeight.kilos;
	else
		return cfg.unitOfWeight.DEFAULT;
}

var getExerciseName = _.identity;

class Workouts {
	// input can have meta sections
	constructor(workoutsArray) {
		this._sections = workoutsArray;
	}

	getAll() {
		return this._sections.slice();
	}
}

class MetaSection {
	constructor(sectionText) {
		this._meta = sectionText;
	}

	render() {
		return '
' +
			toHtml(this._meta) +
		'
';
	}
}

class Workout {
	constructor(header, exercises, meta) {
		this._header = header;
		this._exercises = exercises;
		this._meta = meta;
	}

	isValid() { return this._header.isValid(); }

	static validate(workoutText) { return Workout.parse(workoutText); }

	render() {
		return '
' +
			this._header.render() +
			toHtml(this._exercises.map(exercise => exercise.render())) +
		'
';
	}

}

class WorkoutHeader {
	constructor(headerText) {
		var txt = headerText;
		this._text = txt;

		this._workoutDate = getDate(txt);

		this._workoutUnitOfWeight = getUnitOfWeight(txt);

		this._meta = WorkoutHeader.getMeta(txt);
	}

	isValid() {
		return !!this._workoutDate;
	}

	render() {
		return '
' +
			toHtml(this._text) +
		'
';
	}

	static getMeta(text) {
		return getProp(text.match(/\(([^\)]*)\)/), [1]);
	}
}

class ExerciseSetCollection {
	/**
	 * @param {String} name of exercise from enum of EXERCISES
	 * @param {Array<ExerciseSet>} exerciseSetArray
	 * @parm {ExerciseMeta}
	 */
	constructor(name, exerciseSetArray, exerciseMeta) {
		this._name = name;
		this._sets = exerciseSetArray;
		this._exerciseMeta = exerciseMeta;
	}

	render() {
		return this._name + '\t' +
		       _.invoke(this._sets, 'render').join(', ') + ' ' +
		      this._exerciseMeta.render();
	}
}

class ExerciseMeta {
	constructor (metaText) {
		this._text = metaText ? metaText : '';
	}

	toString() { return this._text; }
	render() { return this._text; }
}

class ExerciseSet {
	constructor(sets, reps, weight, comments) {
		[this._sets, this._reps, this._weight, this._comments] = arguments;
	}

	render() { return this.toString(); }
	isValid() { return true; }

	static toString(sets, reps) {
		return sets + cfg.setsByRepsDelim + reps;
	}

	toString() {
		return ExerciseSet.toString(this._sets, this._reps);
	}

	toShortString() {
		return ExerciseSet.toShortString(this._sets, this._reps);
	}

	static toShortString(sets, reps) {
		if (sets === 1) {
			return reps;
		} else {
			return sets + cfg.setsByRepsDelim + reps;
		}
	}
}

class Workset extends ExerciseSet {
	constructor(sets, reps, weight, comments) {
		this._sets = sets;
		this._reps = reps;
		this._weight = weight;
		this._comments = new ExerciseMeta(comments);
	}

	setWeight(weight) {
		this._weight = weight;
	}

	render() { return this.toString() + ':' + this._weight; }
}

window.WorkoutsView = class WorkoutsView {
	constructor(workouts) {
		if (!(workouts instanceof Workouts)) {
			workouts = parseWorkouts(workouts);
		}

		var html = [];

		workouts.getAll().forEach(function (section) {
			html.push(section.render());
		});

		this._html = html.join('');
	}

	render() { return this._html; }
};

_.each([Workout, ExerciseSet, WorkoutHeader, ExerciseSetCollection, ExerciseMeta],
	o => { o.tryCreate = createMixin; });

//export {Workouts, WorkoutsView};
<commit_msg>add model methods to call in view<commit_after>const WORKOUT_SEPARATOR = '\n\n';
const WHITESPACE = /\s/;
var cfg = window.cfg;

function toHtml(text) {
	if (Array.isArray(text))
		return text.map(toHtml).join('
')
	else if (text !== null && text !== undefined)
		return text.replace(/\n/g, '
');
	else
		return '';
}

function getProp(obj, path) {
	const PATH_DELIM = '.';
	if (typeof path === 'string') {
		path = path.split(PATH_DELIM);
	}
	var prop = obj;

	while (path.length && obj && obj !== null) {
		prop = obj[path[0]];
		path = path.slice(1);
	}

	return prop;
}

/**
 * Takes in text containing slash separated date e.g. 2015/03/01
 * returns first date found as unix time
 * returns null if no date found
 * TODO: adjust for timezones
 */
function getDate(text, context) {
	const WORKOUT_HEADER_DATE_REGEXP = /(\d+\/\d+\/\d+)\s/;
	var dateString = getProp(text.match(WORKOUT_HEADER_DATE_REGEXP), [1]);
	if (!dateString) {
		return null;
	} else {
		dateString.replace(/\//g, '-');
		return Date.parse(dateString);
	}
}

/**
 * Takes in text containing unit of weight
 * returns first unit of weight found
 * returns user's default unit of weight if no date found
 */
function getUnitOfWeight(text, context) {
	if (text.contains('lbs') || text.contains('lb'))
		return cfg.unitOfWeight.pounds;
	else if (text.contains('kgs') || text.contains('kg'))
		return cfg.unitOfWeight.kilos;
	else
		return cfg.unitOfWeight.DEFAULT;
}

var getExerciseName = _.identity;

class Workouts {
	// input can have meta sections
	constructor(workoutsArray) {
		this._sections = workoutsArray;
	}

	getAll() {
		return this._sections.slice();
	}
}

class MetaSection {
	constructor(sectionText) {
		this._meta = sectionText;
	}

	render() {
		return '
' +
			toHtml(this._meta) +
		'
';
	}
}

class Workout {
	/**
	 * @param {WorkoutHeader} header
	 * @param {Array<ExerciseSetCollection>} exerciseSets
	 * @param {ExerciseMeta} meta
	 */
	constructor(header, exerciseSets, meta) {
		this._header = header;
		this._exerciseSets = exerciseSets;
		this._meta = meta;
	}

	getHeader() { return this._header; }
	getExerciseSets() { return this._exerciseSets; }

	isValid() { return this._header.isValid(); }

	static validate(workoutText) { return Workout.parse(workoutText); }

	render() {
		return '
' +
			this._header.render() +
			toHtml(this._exerciseSets.map(exercise => exercise.render())) +
		'
';
	}

}

class WorkoutHeader {
	constructor(headerText) {
		var txt = headerText;
		this._text = txt;

		this._workoutDate = getDate(txt);

		this._workoutUnitOfWeight = getUnitOfWeight(txt);

		this._meta = WorkoutHeader.getMeta(txt);
	}

	isValid() {
		return !!this._workoutDate;
	}

	toString() { return this._text; }

	render() {
		return '
' +
			toHtml(this.toString()) +
		'
';
	}

	static getMeta(text) {
		return getProp(text.match(/\(([^\)]*)\)/), [1]);
	}
}

class ExerciseSetCollection {
	/**
	 * @param {String} name of exercise from enum of EXERCISES
	 * @param {Array<ExerciseSet>} exerciseSetArray
	 * @parm {ExerciseMeta} exerciseMeta
	 */
	constructor(name, exerciseSetArray, exerciseMeta) {
		this._name = name;
		this._sets = exerciseSetArray;
		this._exerciseMeta = exerciseMeta;
	}
	getName() { return this._name; }
	getSets() { return this._sets; }
	getMeta() { return this._exerciseMeta; }

	render() {
		return this._name + '\t' +
		       _.invoke(this._sets, 'render').join(', ') + ' ' +
		      this._exerciseMeta.render();
	}
}

class ExerciseMeta {
	constructor (metaText) {
		this._text = metaText ? metaText : '';
	}

	toString() { return this._text; }
	render() { return this._text; }
}

class ExerciseSet {
	constructor(sets, reps, weight, comments) {
		[this._sets, this._reps, this._weight, this._comments] = arguments;
	}

	render() { return this.toString(); }
	isValid() { return true; }

	static toString(sets, reps) {
		return sets + cfg.setsByRepsDelim + reps;
	}

	toString() {
		return ExerciseSet.toString(this._sets, this._reps);
	}

	toShortString() {
		return ExerciseSet.toShortString(this._sets, this._reps);
	}

	static toShortString(sets, reps) {
		if (sets === 1) {
			return reps;
		} else {
			return sets + cfg.setsByRepsDelim + reps;
		}
	}
}

class Workset extends ExerciseSet {
	constructor(sets, reps, weight, comments) {
		this._sets = sets;
		this._reps = reps;
		this._weight = weight;
		this._comments = new ExerciseMeta(comments);
	}

	setWeight(weight) {
		this._weight = weight;
	}

	render() { return this.toString() + ':' + this._weight; }
}

window.WorkoutsView = class WorkoutsView {
	constructor(workouts) {
		if (!(workouts instanceof Workouts)) {
			workouts = parseWorkouts(workouts);
		}

		var html = [];

		workouts.getAll().forEach(function (section) {
			html.push(section.render());
		});

		this._html = html.join('');
	}

	render() { return this._html; }
};

_.each([Workout, ExerciseSet, WorkoutHeader, ExerciseSetCollection, ExerciseMeta],
	o => { o.tryCreate = createMixin; });

//export {Workouts, WorkoutsView};
<|endoftext|>


<commit_before>import Ember from 'ember';
import SetPageTitle from 'public/mixins/set-page-title';
import GetFutureRuns from 'public/mixins/channel-future-runs-promise';

function filterShows(shows) {
	return shows.filter(function(show) {
		return Ember.get(show, 'showThumbnails.length') > 0 && Ember.get(show, 'cgExempt') === false;
	});
}

export default Ember.Route.extend(SetPageTitle,GetFutureRuns, {

	model() {
		let channel = this.modelFor('application').channel;

    let carouselShows = channel.get('publicSite.carouselSavedSearch').then((search)=>{
      if(search){
        return this.store.query('show',{
          ids: search.get('results').slice(0,20),
          include: 'thumbnail,vod,category,project,producer,reel',
        }).then(filterShows);
      }
    });

    return Ember.RSVP.hash({
      carouselShows,
      futureRuns:this.getFutureRuns(channel),
      defaultShows: this.store.query('show',{page_size: 24, location: channel.get('primaryLocation')}).then(filterShows),
      categories: this.store.findAll('category'),
      projects: this.store.findAll('project'),
      producers: this.store.findAll('producer')
    });
  },

	afterModel() {
		var channel = this.modelFor('application').channel;
		let name = channel.get('publicSite.siteName') || channel.get('name');
		this.setTitle(name);
	}
});
<commit_msg>cc-143 Reset scroll on index route<commit_after>import Ember from 'ember';
import SetPageTitle from 'public/mixins/set-page-title';
import GetFutureRuns from 'public/mixins/channel-future-runs-promise';
import ResetScroll from 'public/mixins/reset-scroll';

function filterShows(shows) {
	return shows.filter(function(show) {
		return Ember.get(show, 'showThumbnails.length') > 0 && Ember.get(show, 'cgExempt') === false;
	});
}

export default Ember.Route.extend(SetPageTitle, GetFutureRuns, ResetScroll, {

	model() {
		let channel = this.modelFor('application').channel;

    let carouselShows = channel.get('publicSite.carouselSavedSearch').then((search)=>{
      if(search){
        return this.store.query('show',{
          ids: search.get('results').slice(0,20),
          include: 'thumbnail,vod,category,project,producer,reel',
        }).then(filterShows);
      }
    });

    return Ember.RSVP.hash({
      carouselShows,
      futureRuns:this.getFutureRuns(channel),
      defaultShows: this.store.query('show',{page_size: 24, location: channel.get('primaryLocation')}).then(filterShows),
      categories: this.store.findAll('category'),
      projects: this.store.findAll('project'),
      producers: this.store.findAll('producer')
    });
  },

	afterModel() {
		var channel = this.modelFor('application').channel;
		let name = channel.get('publicSite.siteName') || channel.get('name');
		this.setTitle(name);
	}
});
<|endoftext|>


<commit_before>export default Ember.Route.extend({
  beforeModel: function () {

    var route = this;

    this.store.find('content-type').then(function (types) {
      if (types.get('length')) {
        route.transitionTo('wh');
      } else {
        route.transitionTo('start');
      }
    });
  }
});
<commit_msg>make sure we redirect to login before trying to load data<commit_after>export default Ember.Route.extend({
  beforeModel: function () {

    this._super.apply(this, arguments);

    var route = this;

    this.store.find('content-type').then(function (types) {
      if (types.get('length')) {
        route.transitionTo('wh');
      } else {
        route.transitionTo('start');
      }
    });
  }
});
<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
//var timeHandler = require(path + '/app/controllers/timekHandler.server.js');

var baseURL = "https://url-shortener-richardsa.c9users.io/";
var isObj = true;
var urls = {};
var id = 0;
var answer;
var notIn = {"error":"No short url found for given input"};
module.exports = function(app, passport) {

  /*	function isLoggedIn (req, res, next) {
  		if (req.isAuthenticated()) {
  			return next();
  		} else {
  			res.redirect('/timestamp');
  		}
  	}*/

  var clickHandler = new ClickHandler();

  app.route('/')
    .get(function(req, res) {
    	res.sendFile(path + '/public/index.html');
    });
  app.route('/:id')
    .get(function(req, res) {
      var short = req.params.id;
      console.log(short);
      returnFull(short);
      console.log(answer);
      if (isObj){
        res.send(notIn);
      } else {

        answer = hasHTTP(answer);
        console.log("redirecting to ..." + answer);
        res.redirect(answer);
      // req.url = "www.reddit.com";
        //res.send(answer);
        return res.end();
      }

    });

app.route('/new/:url*')
  .get(function(req, res) {
    var query = req.params.url;
    console.log(query);
    // valid url reg ex taken from http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url
    if (/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/.test(query)){
      query = inSystem(query);
      var solution = {};
      solution["original_url"] = req.params.url;
      console.log(urls[query]);
      solution["short_url"] = urls[req.params.url];
      res.send(solution);
    } else {

     res.send({"error":"URL invalid"});
    }

  });
function returnFull (urlID){

  for (var key in urls) {
    console.log(urls[key]);
    console.log(urlID);
  if (urls[key] == baseURL + urlID) {
    console.log("urls key " + urls[key]);
    isObj = false;
    answer = key;
    console.log("answer" + answer);
    return answer
  }

  console.log("nope");
} return answer;
}

function hasHTTP(x){
  var http = "http://";
  var https = "https://";
  if (x.substring(0, 7) != http || x.substring(0, 8) != https){

    x = http + x;
  }
  console.log("final x " + x);
  return x;
}
function inSystem (url){
    if (urls.hasOwnProperty(url)){
      console.log("in");
      return urls;
    } else {
      console.log("not in");
      console.log(url);
      var shortened = baseURL + id;
      console.log(shortened);
      urls[url] = shortened;
      id += 1;
      return urls;
  }

}
  /*	app.route('/timestamp')
		 .post(function(req, res) {
		 	var x = req.body.split('');
     //console.log(res.send(req.body.str.split('').reverse().join('')));
     console.log(x);
     res.sendFile(path + '/public/timestamp.html');
    })*/

  /*	app.route('/login')
  		.get(function (req, res) {
  			res.sendFile(path + '/public/login.html');
  		});*/
/*  app.route('/timestamp/')

  .get(function(req, res) {

    res.sendFile(path + '/public/timestamp.html');
  });*/

 /* app.route('/logout')
    .get(function(req, res) {

      res.redirect('/login');
    });

  app.route('/profile')
    .get(function(req, res) {
      res.sendFile(path + '/public/profile.html');
    });

  app.route('/api/:id')
    .get(function(req, res) {
      res.json(req.user.github);
    });

  app.route('/auth/github')
    .get(passport.authenticate('github'));

  app.route('/auth/github/callback')
    .get(passport.authenticate('github', {
      successRedirect: '/',
      failureRedirect: '/login'
    }));*/

  /*app.route('/api/:id/clicks')
  	.get(isLoggedIn, clickHandler.getClicks)
  	.post(isLoggedIn, clickHandler.addClick)
  	.delete(isLoggedIn, clickHandler.resetClicks);*/
};<commit_msg>allow forward slash in routes<commit_after>'use strict';

var path = process.cwd();
var ClickHandler = require(path + '/app/controllers/clickHandler.server.js');
//var timeHandler = require(path + '/app/controllers/timekHandler.server.js');

var baseURL = "https://url-shortener-richardsa.c9users.io/";
var isObj = true;
var urls = {};
var id = 0;
var answer;
var notIn = {"error":"No short url found for given input"};
module.exports = function(app, passport) {

  /*	function isLoggedIn (req, res, next) {
  		if (req.isAuthenticated()) {
  			return next();
  		} else {
  			res.redirect('/timestamp');
  		}
  	}*/

  var clickHandler = new ClickHandler();

  app.route('/')
    .get(function(req, res) {
    	res.sendFile(path + '/public/index.html');
    });
  app.route('/:id') // '/:href(.+)'
    .get(function(req, res) {
      var short = req.params.id;
      console.log(short);
      returnFull(short);
      console.log(answer);
      if (isObj){
        res.send(notIn);
      } else {

        answer = hasHTTP(answer);
        console.log("redirecting to ..." + answer);
        res.redirect(answer);
      // req.url = "www.reddit.com";
        //res.send(answer);
        return res.end();
      }

    });

app.route('/new/:url(*)') // allow forward slashes in route: http://stackoverflow.com/a/24366031
  .get(function(req, res) {
    var query = req.params.url;
    console.log(query);
    // valid url reg ex taken from http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url
    if (/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/.test(query)){
      query = inSystem(query);
      var solution = {};
      solution["original_url"] = req.params.url;
      console.log(urls[query]);
      solution["short_url"] = urls[req.params.url];
      res.send(solution);
    } else {

     res.send({"error":"URL invalid"});
    }

  });
function returnFull (urlID){

  for (var key in urls) {
    console.log(urls[key]);
    console.log(urlID);
  if (urls[key] == baseURL + urlID) {
    console.log("urls key " + urls[key]);
    isObj = false;
    answer = key;
    console.log("answer" + answer);
    return answer
  }

  console.log("nope");
} return answer;
}

function hasHTTP(x){
  var http = "http://";
  var https = "https://";
  console.log(x.substring(0, 7))
  console.log(x.substring(0, 8))
  if (x.substring(0, 7) != http && x.substring(0, 8) != https){

    x = http + x;
  }
  console.log("final x " + x);
  return x;
}
function inSystem (url){
    if (urls.hasOwnProperty(url)){
      console.log("in");
      return urls;
    } else {
      console.log("not in");
      console.log(url);
      var shortened = baseURL + id;
      console.log(shortened);
      urls[url] = shortened;
      id += 1;
      return urls;
  }

}
  /*	app.route('/timestamp')
		 .post(function(req, res) {
		 	var x = req.body.split('');
     //console.log(res.send(req.body.str.split('').reverse().join('')));
     console.log(x);
     res.sendFile(path + '/public/timestamp.html');
    })*/

  /*	app.route('/login')
  		.get(function (req, res) {
  			res.sendFile(path + '/public/login.html');
  		});*/
/*  app.route('/timestamp/')

  .get(function(req, res) {

    res.sendFile(path + '/public/timestamp.html');
  });*/

 /* app.route('/logout')
    .get(function(req, res) {

      res.redirect('/login');
    });

  app.route('/profile')
    .get(function(req, res) {
      res.sendFile(path + '/public/profile.html');
    });

  app.route('/api/:id')
    .get(function(req, res) {
      res.json(req.user.github);
    });

  app.route('/auth/github')
    .get(passport.authenticate('github'));

  app.route('/auth/github/callback')
    .get(passport.authenticate('github', {
      successRedirect: '/',
      failureRedirect: '/login'
    }));*/

  /*app.route('/api/:id/clicks')
  	.get(isLoggedIn, clickHandler.getClicks)
  	.post(isLoggedIn, clickHandler.addClick)
  	.delete(isLoggedIn, clickHandler.resetClicks);*/
};<|endoftext|>


<commit_before>module.exports = {
    purge: [
        './resources/views/**/*.blade.php',
        './resources/css/**/*.css',
        './resources/js/**/*.jsx',
    ],
    theme: {
        extend: {
            colors: {
                primary: {
                    100: '#dbccff',
                    200: '#cbb5ff',
                    300: '#bda1ff',
                    400: '#af8cff',
                    500: '#a078ff',
                    600: '#9263ff',
                    700: '#844fff',
                    800: '#763bff',
                    900: '#6927ff',
                },
                secondary: {
                    100: '#c8b8d9',
                    200: '#c0a9d9',
                    300: '#b99cd9',
                    400: '#b38fd9',
                    500: '#ac82d9',
                    600: '#a575d9',
                    700: '#9d66d9',
                    800: '#9759d9',
                    900: '#914cd9',
                },
                success: {
                    100: '#d1e5be',
                    200: '#c7e5aa',
                    300: '#bce595',
                    400: '#b1e581',
                    500: '#a8e56e',
                    600: '#9de55a',
                    700: '#93e545',
                    800: '#89e532',
                    900: '#7ce61e',
                },
                info: {
                    100: '#abc9d1',
                    200: '#99c5d1',
                    300: '#86c1d1',
                    400: '#73bdd1',
                    500: '#62b9d1',
                    600: '#4fb5d1',
                    700: '#3db1d1',
                    800: '#2cadd1',
                    900: '#19aad1',
                },
                warning: {
                    100: '#ffefcf',
                    200: '#ffebc4',
                    300: '#ffe9bd',
                    400: '#ffe5b2',
                    500: '#ffe2a8',
                    600: '#ffdf9e',
                    700: '#ffdb94',
                    800: '#ffd88a',
                    900: '#ffd581',
                },
                danger: {
                    100: '#ffcce2',
                    200: '#ffb8d7',
                    300: '#ffa3cb',
                    400: '#ff8fbf',
                    500: '#ff7ab4',
                    600: '#ff66a8',
                    700: '#ff529d',
                    800: '#ff3b90',
                    900: '#ff2783',
                },
                'primary-dark': {
                    100: '#433745',
                    200: '#433445',
                    300: '#423045',
                    400: '#412b45',
                    500: '#412845',
                    600: '#402445',
                    700: '#402045',
                    800: '#3f1c45',
                    900: '#3f1845',
                },
                gray: {
                    100: '#fcfcfc',
                    200: '#f7f7f7',
                    300: '#f0f0f0',
                    400: '#e0e0e0',
                    450: '#cccccc',
                    500: '#bfbfbf',
                    600: '#969696',
                    700: '#696969',
                    800: '#474747',
                    900: '#2b2b2b',
                },
            },
            fontFamily: {
                'sans': ['Nunito', 'sans-serif'],
            },
            fontSize: {
                xs: '0.75rem',
                sm: '0.875rem',
                base: '1rem',
                lg: '1.125rem',
                xl: '1.25rem',
                '2xl': '1.5rem',
                '3xl': '1.875rem',
                '4xl': '2.25rem',
                '5xl': '3rem',
                '6xl': '4rem',
                '7xl': '5rem',
                '8xl': '6rem',
                '9xl': '7rem',
                '10xl': '8rem',
                '11xl': '9rem',
                '12xl': '10rem',
            },
            maxHeight: {
                16: '16rem',
                32: '32rem',
            },
        },
    },
    variants: {},
    plugins: [
        require('tailwindcss-shadow-outline-colors')(),
    ],
}
<commit_msg>adjsuted focus styling of buttons<commit_after>module.exports = {
    purge: [
        './resources/views/**/*.blade.php',
        './resources/css/**/*.css',
        './resources/js/**/*.jsx',
    ],
    theme: {
        extend: {
            colors: {
                primary: {
                    100: '#dbccff',
                    200: '#cbb5ff',
                    300: '#bda1ff',
                    400: '#af8cff',
                    500: '#a078ff',
                    600: '#9263ff',
                    700: '#844fff',
                    800: '#763bff',
                    900: '#6927ff',
                },
                secondary: {
                    100: '#c8b8d9',
                    200: '#c0a9d9',
                    300: '#b99cd9',
                    400: '#b38fd9',
                    500: '#ac82d9',
                    600: '#a575d9',
                    700: '#9d66d9',
                    800: '#9759d9',
                    900: '#914cd9',
                },
                success: {
                    100: '#d1e5be',
                    200: '#c7e5aa',
                    300: '#bce595',
                    400: '#b1e581',
                    500: '#a8e56e',
                    600: '#9de55a',
                    700: '#93e545',
                    800: '#89e532',
                    900: '#7ce61e',
                },
                info: {
                    100: '#abc9d1',
                    200: '#99c5d1',
                    300: '#86c1d1',
                    400: '#73bdd1',
                    500: '#62b9d1',
                    600: '#4fb5d1',
                    700: '#3db1d1',
                    800: '#2cadd1',
                    900: '#19aad1',
                },
                warning: {
                    100: '#ffefcf',
                    200: '#ffebc4',
                    300: '#ffe9bd',
                    400: '#ffe5b2',
                    500: '#ffe2a8',
                    600: '#ffdf9e',
                    700: '#ffdb94',
                    800: '#ffd88a',
                    900: '#ffd581',
                },
                danger: {
                    100: '#ffcce2',
                    200: '#ffb8d7',
                    300: '#ffa3cb',
                    400: '#ff8fbf',
                    500: '#ff7ab4',
                    600: '#ff66a8',
                    700: '#ff529d',
                    800: '#ff3b90',
                    900: '#ff2783',
                },
                'primary-dark': {
                    100: '#433745',
                    200: '#433445',
                    300: '#423045',
                    400: '#412b45',
                    500: '#412845',
                    600: '#402445',
                    700: '#402045',
                    800: '#3f1c45',
                    900: '#3f1845',
                },
                gray: {
                    100: '#fcfcfc',
                    200: '#f7f7f7',
                    300: '#f0f0f0',
                    400: '#e0e0e0',
                    450: '#cccccc',
                    500: '#bfbfbf',
                    600: '#969696',
                    700: '#696969',
                    800: '#474747',
                    900: '#2b2b2b',
                },
            },
            fontFamily: {
                'sans': ['Nunito', 'sans-serif'],
            },
            fontSize: {
                xs: '0.75rem',
                sm: '0.875rem',
                base: '1rem',
                lg: '1.125rem',
                xl: '1.25rem',
                '2xl': '1.5rem',
                '3xl': '1.875rem',
                '4xl': '2.25rem',
                '5xl': '3rem',
                '6xl': '4rem',
                '7xl': '5rem',
                '8xl': '6rem',
                '9xl': '7rem',
                '10xl': '8rem',
                '11xl': '9rem',
                '12xl': '10rem',
            },
            maxHeight: {
                16: '16rem',
                32: '32rem',
            },
            shadowOutline: {
                'shadow': '0 0 0 .2em',
                'alpha': '.25'
            },
        },
    },
    variants: {},
    plugins: [
        require('tailwindcss-shadow-outline-colors')(),
    ],
}
<|endoftext|>


<commit_before>'use strict';

var path = process.cwd();
var Graphriend = require(path + '/app/controllers/Graphriend.server.js');
var sess;

module.exports = function (app) {

	function isLoggedIn (req, res, next) {
		sess = req.session;
		if (sess.user) {
			return next();
		} else {
			res.redirect('/');
		}
	}

	var graPhriend = new Graphriend();

	var user = {
		isLogged: false,
		name: 'Jinme',
		username: 'mirabalj'
	}

	app.route('/')
		.get(function (req, res) {
			res.render('main', { user: user, page: 'index' });
		});

/* Example Authenticated verify
	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render('main', { user: sess.user, page: 'profile' });
		});
*/

/* Example REST api
	app.route('/friends')
		.get(isLoggedIn, graPhriend.getFriend)
		.post(isLoggedIn, graPhriend.addFriend)
		.delete(isLoggedIn, graPhriend.delFriend);
*/

};
<commit_msg>Add route to register users<commit_after>'use strict';

var path = process.cwd();
var Graphriend = require(path + '/app/controllers/Graphriend.server.js');
var sess;

module.exports = function (app) {

	function isLoggedIn (req, res, next) {
		sess = req.session;
		if (sess.user) {
			return next();
		} else {
			res.redirect('/');
		}
	}

	var graPhriend = new Graphriend();

	var user = {
		isLogged: false,
		name: 'Jinme',
		username: 'mirabalj'
	}

	app.route('/')
		.get(function (req, res) {
			res.render('main', { user: user, page: 'index' });
		});

	app.post('/api/signup', graPhriend.signUp);

/* Example Authenticated verify
	app.route('/profile')
		.get(isLoggedIn, function (req, res) {
			res.render('main', { user: sess.user, page: 'profile' });
		});
*/

/* Example REST api
	app.route('/friends')
		.get(isLoggedIn, graPhriend.getFriend)
		.post(isLoggedIn, graPhriend.addFriend)
		.delete(isLoggedIn, graPhriend.delFriend);
*/

};
<|endoftext|>


<commit_before>import Morph from "morph/morph";

var xhtmlNamespace = "http://www.w3.org/1999/xhtml";

/*
 * A class wrapping DOM functions to address environment compatibility,
 * namespaces, contextual elements for morph un-escaped content
 * insertion.
 *
 * When entering a template, a DOMHelper should be passed to provide
 * context to the template. The context is most easily expressed as
 * an element:
 *
 *   template(context, { hooks: hooks, dom: new DOMHelper(element) });
 *
 * In this case, the namespace and ownerDocument of the element will
 * provide context.
 *
 * During fragment creation, a new namespace may be needed. In these
 * cases, a dom helper will be created for the new namespace:
 *
 *   dom1 = new dom0.constructor(null, dom0.document, someNamespaceURI);
 *
 * In this case the namespace and document are passed explicitly,
 * as decided by the parser at compile time, instead of asking the
 * DOMHelper to determine them. There is no contextual element passed,
 * but the contextual element should only be required by the morphs
 * at the root of a document anyway.
 *
 * Helpers and hooks can pass a new DOMHelper or another object as
 * is appropriate:
 *
 *   var svg = document.createElementNS(svgNamespace, 'svg');
 *   morph.render(context, {hooks: env.hooks, dom: new DOMHelper(svg)});
 *
 * TODO: support foreignObject as a passed contextual element. It has
 * a namespace (svg) that does not match its internal namespace
 * (xhtml).
 *
 * @class DOMHelper
 * @constructor
 * @param {HTMLDocument} _document The document DOM methods are proxied to
 */
function DOMHelper(_document){
  this.document = _document || window.document;
}

var prototype = DOMHelper.prototype;
prototype.constructor = DOMHelper;

prototype.appendChild = function(element, childElement) {
  element.appendChild(childElement);
};

prototype.appendText = function(element, text) {
  element.appendChild(this.document.createTextNode(text));
};

prototype.setAttribute = function(element, name, value) {
  element.setAttribute(name, value);
};

prototype.createElement = function(tagName) {
  if (this.namespaceURI) {
    return this.document.createElementNS(this.namespaceURI, tagName);
  } else {
    return this.document.createElement(tagName);
  }
};

prototype.createDocumentFragment = function(){
  return this.document.createDocumentFragment();
};

prototype.createTextNode = function(text){
  return this.document.createTextNode(text);
};

prototype.cloneNode = function(element, deep){
  return element.cloneNode(!!deep);
};

prototype.createMorph = function(parent, start, end, contextualElement){
  if (!contextualElement && parent.nodeType === Node.ELEMENT_NODE) {
    contextualElement = parent;
  }
  if (!contextualElement) {
    contextualElement = this.document.body;
  }
  return new Morph(parent, start, end, this, contextualElement);
};

// This helper is just to keep the templates good looking,
// passing integers instead of element references.
prototype.createMorphAt = function(parent, startIndex, endIndex, contextualElement){
  var childNodes = parent.childNodes,
      start = startIndex === -1 ? null : childNodes[startIndex],
      end = endIndex === -1 ? null : childNodes[endIndex];
  return this.createMorph(parent, start, end, contextualElement);
};

prototype.parseHTML = function(html, contextualElement){
  var element = this.cloneNode(contextualElement, false);
  element.innerHTML = html;
  return element.childNodes;
};

export default DOMHelper;
<commit_msg>Update dom helper documentation<commit_after>import Morph from "morph/morph";

var xhtmlNamespace = "http://www.w3.org/1999/xhtml";

/*
 * A class wrapping DOM functions to address environment compatibility,
 * namespaces, contextual elements for morph un-escaped content
 * insertion.
 *
 * When entering a template, a DOMHelper should be passed:
 *
 *   template(context, { hooks: hooks, dom: new DOMHelper() });
 *
 * TODO: support foreignObject as a passed contextual element. It has
 * a namespace (svg) that does not match its internal namespace
 * (xhtml).
 *
 * @class DOMHelper
 * @constructor
 * @param {HTMLDocument} _document The document DOM methods are proxied to
 */
function DOMHelper(_document){
  this.document = _document || window.document;
}

var prototype = DOMHelper.prototype;
prototype.constructor = DOMHelper;

prototype.appendChild = function(element, childElement) {
  element.appendChild(childElement);
};

prototype.appendText = function(element, text) {
  element.appendChild(this.document.createTextNode(text));
};

prototype.setAttribute = function(element, name, value) {
  element.setAttribute(name, value);
};

prototype.createElement = function(tagName) {
  if (this.namespaceURI) {
    return this.document.createElementNS(this.namespaceURI, tagName);
  } else {
    return this.document.createElement(tagName);
  }
};

prototype.createDocumentFragment = function(){
  return this.document.createDocumentFragment();
};

prototype.createTextNode = function(text){
  return this.document.createTextNode(text);
};

prototype.cloneNode = function(element, deep){
  return element.cloneNode(!!deep);
};

prototype.createMorph = function(parent, start, end, contextualElement){
  if (!contextualElement && parent.nodeType === Node.ELEMENT_NODE) {
    contextualElement = parent;
  }
  if (!contextualElement) {
    contextualElement = this.document.body;
  }
  return new Morph(parent, start, end, this, contextualElement);
};

// This helper is just to keep the templates good looking,
// passing integers instead of element references.
prototype.createMorphAt = function(parent, startIndex, endIndex, contextualElement){
  var childNodes = parent.childNodes,
      start = startIndex === -1 ? null : childNodes[startIndex],
      end = endIndex === -1 ? null : childNodes[endIndex];
  return this.createMorph(parent, start, end, contextualElement);
};

prototype.parseHTML = function(html, contextualElement){
  var element = this.cloneNode(contextualElement, false);
  element.innerHTML = html;
  return element.childNodes;
};

export default DOMHelper;
<|endoftext|>


<commit_before><commit_msg>add Element.val() for compliance with current API<commit_after><|endoftext|>


<commit_before>module.exports = {
  theme: {
    customForms: (theme) => ({
      default: {
        input: {
          borderColor: theme('colors.gray.300'),
          borderRadius: theme('borderRadius.default'),
          boxShadow: 'inset 0 1px 1px rgba(0, 0, 0, 0.075)',
          display: 'block',
          color: '#495057',
          paddingTop: '0.375rem',
          paddingBottom: '0.375rem',
          width: '100%',
        },
      },
    }),
    extend: {
      colors: {
        current: 'currentColor',
        light: 'hsl(210, 16.7%, 97.6%)',
        'aa-100': 'hsla(0, 100%, 0%, 0.03)',
        blueish: {
          500: '#4299e1',
          600: '#3182ce',
          700: '#2b6cb0',
          800: '#2c5282',
        },
        greenish: {
          300: '#9ae6b4',
          600: '#38a169',
          700: '#2f855a',
        },
        grey: {
          100: 'hsl(208, 10%, 95%)',
          200: 'hsl(208, 10%, 90%)',
          300: 'hsl(208, 10%, 80%)',
          400: 'hsl(208, 10%, 70%)',
          500: 'hsl(208, 10%, 60%)',
          600: 'hsl(208, 10%, 50%)',
          700: 'hsl(208, 14%, 40%)',
          800: 'hsl(208, 18%, 28%)',
          900: 'hsl(208, 22%, 16%)',
        },
        orangeish: {
          400: '#f6ad55',
          500: '#ed8936',
          600: '#dd6b20',
        },
        redish: {
          600: '#e53e3e',
        },
        tealish: {
          600: '#319795',
          700: '#2c7a7b',
        },

        // Socials
        facebook: {
          600: 'hsl(227, 50%, 38%)',
          700: 'hsl(227, 50%, 28%)',
        },
        github: {
          600: 'hsl(0, 0%, 20%)',
          700: 'hsl(0, 0%, 10%)',
        },
        google: {
          600: 'hsl(5, 68%, 53%)',
          700: 'hsl(5, 68%, 43%)',
        },
        odnoklassniki: {
          600: 'hsl(25, 88%, 56%)',
          700: 'hsl(25, 88%, 46%)',
        },
        telegram: {
          600: 'hsl(200, 66%, 48%)',
          700: 'hsl(200, 66%, 38%)',
        },
        twitter: {
          600: 'hsl(202, 90%, 57%)',
          700: 'hsl(202, 90%, 47%)',
        },
        viber: {
          600: 'hsl(274, 48%, 46%)',
          700: 'hsl(274, 48%, 36%)',
        },
        vk: {
          600: 'hsl(211, 30%, 46%)',
          700: 'hsl(211, 30%, 36%)',
        },
        whatsapp: {
          600: 'hsl(114, 44%, 50%)',
          700: 'hsl(114, 44%, 40%)',
        },
        yandex: {
          600: 'hsl(0, 100%, 50%)',
          700: 'hsl(0, 100%, 40%)',
        },
      },
      flex: {
        'h-full': '1 0 auto',
      },
      fontSize: {
        '2xs': '0.6875rem',
        '2sm': '0.8125rem',
      },
      height: {
        '1/2-screen': '50vh',
      },
      inset: {
        '1/2': '50%',
      },
      maxWidth: {
        none: 'none',
        '400px': '400px',
        '500px': '500px',
        '600px': '600px',
        '700px': '700px',
        '1000px': '1000px',
      },
      padding: {
        '3/4': '75%',
      },
      spacing: {
        '2px': '2px',
      },
    },
    screens: {
      sm: '576px',
      md: '768px',
      lg: '992px',
      xl: '1200px',
      dark: { raw: '(prefers-color-scheme: dark)' },
    },
    container: {
      center: true,
      padding: '1rem',
    },
  },
  variants: {
    textColor: ['responsive', 'hover', 'focus', 'group-hover'],
    textDecoration: ['responsive', 'hover', 'focus', 'group-hover'],
    visibility: ['responsive', 'group-hover'],
  },
  plugins: [
    // eslint-disable-next-line global-require
    require('@tailwindcss/ui'),
  ],
}
<commit_msg>Отключен встроенный purge tailwind<commit_after>module.exports = {
  purge: false,
  theme: {
    customForms: (theme) => ({
      default: {
        input: {
          borderColor: theme('colors.gray.300'),
          borderRadius: theme('borderRadius.default'),
          boxShadow: 'inset 0 1px 1px rgba(0, 0, 0, 0.075)',
          display: 'block',
          color: '#495057',
          paddingTop: '0.375rem',
          paddingBottom: '0.375rem',
          width: '100%',
        },
      },
    }),
    extend: {
      colors: {
        current: 'currentColor',
        light: 'hsl(210, 16.7%, 97.6%)',
        'aa-100': 'hsla(0, 100%, 0%, 0.03)',
        blueish: {
          500: '#4299e1',
          600: '#3182ce',
          700: '#2b6cb0',
          800: '#2c5282',
        },
        greenish: {
          300: '#9ae6b4',
          600: '#38a169',
          700: '#2f855a',
        },
        grey: {
          100: 'hsl(208, 10%, 95%)',
          200: 'hsl(208, 10%, 90%)',
          300: 'hsl(208, 10%, 80%)',
          400: 'hsl(208, 10%, 70%)',
          500: 'hsl(208, 10%, 60%)',
          600: 'hsl(208, 10%, 50%)',
          700: 'hsl(208, 14%, 40%)',
          800: 'hsl(208, 18%, 28%)',
          900: 'hsl(208, 22%, 16%)',
        },
        orangeish: {
          400: '#f6ad55',
          500: '#ed8936',
          600: '#dd6b20',
        },
        redish: {
          600: '#e53e3e',
        },
        tealish: {
          600: '#319795',
          700: '#2c7a7b',
        },

        // Socials
        facebook: {
          600: 'hsl(227, 50%, 38%)',
          700: 'hsl(227, 50%, 28%)',
        },
        github: {
          600: 'hsl(0, 0%, 20%)',
          700: 'hsl(0, 0%, 10%)',
        },
        google: {
          600: 'hsl(5, 68%, 53%)',
          700: 'hsl(5, 68%, 43%)',
        },
        odnoklassniki: {
          600: 'hsl(25, 88%, 56%)',
          700: 'hsl(25, 88%, 46%)',
        },
        telegram: {
          600: 'hsl(200, 66%, 48%)',
          700: 'hsl(200, 66%, 38%)',
        },
        twitter: {
          600: 'hsl(202, 90%, 57%)',
          700: 'hsl(202, 90%, 47%)',
        },
        viber: {
          600: 'hsl(274, 48%, 46%)',
          700: 'hsl(274, 48%, 36%)',
        },
        vk: {
          600: 'hsl(211, 30%, 46%)',
          700: 'hsl(211, 30%, 36%)',
        },
        whatsapp: {
          600: 'hsl(114, 44%, 50%)',
          700: 'hsl(114, 44%, 40%)',
        },
        yandex: {
          600: 'hsl(0, 100%, 50%)',
          700: 'hsl(0, 100%, 40%)',
        },
      },
      flex: {
        'h-full': '1 0 auto',
      },
      fontSize: {
        '2xs': '0.6875rem',
        '2sm': '0.8125rem',
      },
      height: {
        '1/2-screen': '50vh',
      },
      inset: {
        '1/2': '50%',
      },
      maxWidth: {
        none: 'none',
        '400px': '400px',
        '500px': '500px',
        '600px': '600px',
        '700px': '700px',
        '1000px': '1000px',
      },
      padding: {
        '3/4': '75%',
      },
      spacing: {
        '2px': '2px',
      },
    },
    screens: {
      sm: '576px',
      md: '768px',
      lg: '992px',
      xl: '1200px',
      dark: { raw: '(prefers-color-scheme: dark)' },
    },
    container: {
      center: true,
      padding: '1rem',
    },
  },
  variants: {
    textColor: ['responsive', 'hover', 'focus', 'group-hover'],
    textDecoration: ['responsive', 'hover', 'focus', 'group-hover'],
    visibility: ['responsive', 'group-hover'],
  },
  plugins: [
    // eslint-disable-next-line global-require
    require('@tailwindcss/ui'),
  ],
}
<|endoftext|>


<commit_before>angular.module("biblioteca").controller("homeCtrl", ["$scope", "documentoService", function ($scope, documentoService) {
    var MAX = 10;
    $scope.formatDate = _formatDate;
    $scope.formatDateTime = _formatDateTime;
    $scope.getDocumento = _getDocumento;
    $scope.buscar = _buscar;
    $scope.deleteDocumento = _deleteDocumento;

    _buscar();

    function _buscar(page) {
        if (!page) {
            page = 1;
        }

        var offset = MAX * (page-1);

        documentoService.searchDocumento($scope.query, MAX, offset, function (response) {
            $scope.documentos = null;
            $scope.total = 0;
            $scope.paginate = [];
            $scope.actualPage = page;

            if (response.data) {
                $scope.documentos = response.data.documentoList;
                $scope.total = response.data.total;
                montaPaginacao(MAX, $scope.total);
            }
        }, function (response) {
            console.log(response);
        });
    };

    function _getDocumento(id) {
        documentoService.getDocumento(id, function(response) {
            if (response.data) {
                $scope.viewDocumento = response.data;
            }
        }, function(response) {
            console.log(response);
        });
    }

    function _deleteDocumento(id) {
        if (!confirm('Tem certeza que deseja apagar este documento?')) {
            return;
        }

        documentoService.deleteDocumento(id, function(response) {
            _buscar();
            alert('Documento apagado');
        }, function(response) {
            console.log(response);
        });
    }

    function _formatDate(miliseconds) {
        if (!miliseconds) {
            return "";
        }

        var date = new Date(miliseconds);
        var month = date.getMonth() + 1;
        month = (month < 10)?"0" + month:month;
        return date.getDate() + "/" + month + "/" + date.getFullYear();
    }

    function _formatDateTime(miliseconds) {
        if (!miliseconds) {
            return "";
        }

        var date = new Date(miliseconds);
        var month = date.getMonth() + 1;
        month = (month < 10)?"0" + month:month;
        return date.getDate() + "/" + month + "/" + date.getFullYear() + ' - ' + date.getHours() + ':' + date.getMinutes();
    }

    function montaPaginacao(max, total) {
        var pages = total / max;

        if (pages < 1) {
            pages = 1;
        }

        for (var i = 1; i <= pages; i++) {
            $scope.paginate.push(i);
        }
    }
}]);<commit_msg>Correção na paginação<commit_after>angular.module("biblioteca").controller("homeCtrl", ["$scope", "documentoService", function ($scope, documentoService) {
    var MAX = 10;
    $scope.formatDate = _formatDate;
    $scope.formatDateTime = _formatDateTime;
    $scope.getDocumento = _getDocumento;
    $scope.buscar = _buscar;
    $scope.deleteDocumento = _deleteDocumento;

    _buscar();

    function _buscar(page) {
        if (!page) {
            page = 1;
        }

        var offset = MAX * (page-1);

        documentoService.searchDocumento($scope.query, MAX, offset, function (response) {
            $scope.documentos = null;
            $scope.total = 0;
            $scope.paginate = [];
            $scope.actualPage = page;

            if (response.data) {
                $scope.documentos = response.data.documentoList;
                $scope.total = response.data.total;
                montaPaginacao(MAX, $scope.total);
            }
        }, function (response) {
            console.log(response);
        });
    };

    function _getDocumento(id) {
        documentoService.getDocumento(id, function(response) {
            if (response.data) {
                $scope.viewDocumento = response.data;
            }
        }, function(response) {
            console.log(response);
        });
    }

    function _deleteDocumento(id) {
        if (!confirm('Tem certeza que deseja apagar este documento?')) {
            return;
        }

        documentoService.deleteDocumento(id, function(response) {
            _buscar();
            alert('Documento apagado');
        }, function(response) {
            console.log(response);
        });
    }

    function _formatDate(miliseconds) {
        if (!miliseconds) {
            return "";
        }

        var date = new Date(miliseconds);
        var month = date.getMonth() + 1;
        month = (month < 10)?"0" + month:month;
        return date.getDate() + "/" + month + "/" + date.getFullYear();
    }

    function _formatDateTime(miliseconds) {
        if (!miliseconds) {
            return "";
        }

        var date = new Date(miliseconds);
        var month = date.getMonth() + 1;
        month = (month < 10)?"0" + month:month;
        return date.getDate() + "/" + month + "/" + date.getFullYear() + ' - ' + date.getHours() + ':' + date.getMinutes();
    }

    function montaPaginacao(max, total) {
        var pages = total / max;

        if (pages < 1) {
            pages = 1;
        }

        for (var i = 1; i <= Math.ceil(pages); i++) {
            $scope.paginate.push(i);
        }
    }
}]);<|endoftext|>