diff --git a/.gitignore b/.gitignore index 62c8935..355d67b 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ -.idea/ \ No newline at end of file +.idea/ +.node_modules/ +node_modules/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..a575c51 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - "0.10" +before_script: + - export DISPLAY=:99.0 + - sh -e /etc/init.d/xvfb start \ No newline at end of file diff --git a/README.md b/README.md index bad4f6b..97be837 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ -Canvas2Svg +Canvas2Svg [![Build Status](https://travis-ci.org/gliffy/canvas2svg.svg?branch=master)](https://travis-ci.org/gliffy/canvas2svg) ========== -This library turns your Canvas into SVG using javascript. In other words, this library lets you build an SVG document using the canvas api. Why use it? +This library turns your Canvas into SVG using javascript. In other words, this library lets you build an SVG document +using the canvas api. Why use it? * You have a canvas drawing you want to persist as an SVG file. * You like exporting things. * Because you didn't want to transform your custom file format to SVG. @@ -11,7 +12,8 @@ http://gliffy.github.io/canvas2svg/ How it works ========== -We create a mock 2d canvas context. Use the canvas context like you would on a normal canvas. As you call methods, we build up a scene graph in SVG. Yay! +We create a mock 2d canvas context. Use the canvas context like you would on a normal canvas. As you call methods, we +build up a scene graph in SVG. Yay! Usage ========== @@ -31,8 +33,83 @@ var mySerializedSVG = ctx.getSerializedSvg(); //true here, if you need to conver var svg = ctx.getSvg(); ``` +Tests +========== +To run tests: +``` +npm install +npm test +``` + +To run tests against Chrome and Firefox, call karma directly. This is not the default npm test due to the limited +browser selection in travis. +``` +npm install karma-cli -g +karma start +``` + +Debug +========= +Play with canvas2svg in the provided test/playground.html or run test locally in your browser in test/testrunner.html + + +Add An Example Case +========= +Add a test file to the test/example folder. In your file make sure to add the drawing function to the global `C2S_EXAMPLES`, +with your filename as a key. For example `test\example\linewidth.js` should look something like: +```javascript +window.C2S_EXAMPLES['linewidth'] = function(ctx) { + for (var i = 0; i < 10; i++){ + ctx.lineWidth = 1+i; + ctx.beginPath(); + ctx.moveTo(5+i*14,5); + ctx.lineTo(5+i*14,140); + ctx.stroke(); + } +}; +``` +install gulp globally if you haven't done so already +``` +npm install -g gulp +``` +Then run the following to update playground.html and testrunner.html +``` +gulp +``` +You should now be able to select your new example from playground.html or see it run in testrunner.html + +If you find a bug, or want to add functionality, please add a new test case and include it with your pull request. + +Using with node.js +================== + +You can use `canvas2svg` with node.js using [jsdom](https://github.com/tmpvar/jsdom) with [node-canvas](https://github.com/Automattic/node-canvas). To do this first create a new document object, and then create a new instance of `C2S` based on that document: + +```javascript +var canvas = require('canvas'), + jsdom = require('jsdom'), + C2S = require('canvas2svg'); + +var document = jsdom.jsdom(); +var ctx = new C2S({document: document}); + +// ... drawing code goes here ... +``` + +N.B. You may not need node-canvas for some simple operations when using jsdom >= 6.3.0, but it's still recommended that you install it. + Updates ========== +- v1.0.19 Fix __parseFont to not crash +- v1.0.18 clip was not working, the path never made it to the clip area +- v1.0.17 Fix bug with drawing in an empty context. Fix image translation problem. Fix globalAlpha issue. +- v1.0.16 Add npm publishing support, bower file and optimize for arcs with no angles. +- v1.0.15 Setup travis, add testharness and debug playground, and fix regression for __createElement refactor +- v1.0.14 bugfix for gradients, move __createElement to scoped createElement function, so all classes have access. +- v1.0.13 set paint order before stroke and fill to make them behavior like canvas +- v1.0.12 Implementation of ctx.prototype.arcTo. +- v1.0.11 call lineTo instead moveTo in ctx.arc, fixes closePath issue and straight line issue +- v1.0.10 when lineTo called, use M instead of L unless subpath exists - v1.0.9 use currentDefaultPath instead of 's d attribute, fixes stroke's different behavior in SVG and canvas. - v1.0.8 reusing __createElement and adding a properties undefined check - v1.0.7 fixes for multiple transforms and fills and better text support from stafyniaksacha @@ -48,6 +125,17 @@ Misc ========== Some canvas 2d context methods are not implemented yet. Watch out for setTransform and arcTo. +Releasing +========= + +To release a new version: + +* Run `gulp bump` to update the version number +* Add a new entry to the [Updates](#Updates) table +* `git commit -am v1.0.xx` +* `git push` +* `npm publish` + License ========== This library is licensed under the MIT license. diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..f75eb08 --- /dev/null +++ b/bower.json @@ -0,0 +1,5 @@ +{ + "name": "canvas2svg", + "version": "1.0.19", + "main": "./canvas2svg.js" +} diff --git a/canvas2svg.js b/canvas2svg.js index f4106bd..f71d359 100644 --- a/canvas2svg.js +++ b/canvas2svg.js @@ -1,5 +1,5 @@ /*!! - * Canvas 2 Svg v1.0.9 + * Canvas 2 Svg v1.0.19 * A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document. * * Licensed under the MIT license: @@ -11,7 +11,7 @@ * Copyright (c) 2014 Gliffy Inc. */ -;(function() { +;(function () { "use strict"; var STYLES, ctx, CanvasGradient, CanvasPattern, namedEntities; @@ -144,7 +144,7 @@ svgAttr : "opacity", canvas : 1, svg : 1, - apply : "fill stroke" + apply : "fill stroke" }, "font":{ //font converts to multiple svg attributes, there is custom logic for this @@ -167,6 +167,12 @@ }, "textBaseline":{ canvas : "alphabetic" + }, + "lineDash" : { + svgAttr : "stroke-dasharray", + canvas : [], + svg : null, + apply : "stroke" } }; @@ -175,17 +181,18 @@ * @param gradientNode - reference to the gradient * @constructor */ - CanvasGradient = function(gradientNode) { + CanvasGradient = function (gradientNode, ctx) { this.__root = gradientNode; + this.__ctx = ctx; }; /** * Adds a color stop to the gradient root */ - CanvasGradient.prototype.addColorStop = function(offset, color) { - var stop = this.__createElement("stop"), regex, matches; + CanvasGradient.prototype.addColorStop = function (offset, color) { + var stop = this.__ctx.__createElement("stop"), regex, matches; stop.setAttribute("offset", offset); - if(color.indexOf("rgba") !== -1) { + if (color.indexOf("rgba") !== -1) { //separate alpha value, since webkit can't handle it regex = /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d?\.?\d*)\s*\)/gi; matches = regex.exec(color); @@ -197,7 +204,7 @@ this.__root.appendChild(stop); }; - CanvasPattern = function(pattern, ctx) { + CanvasPattern = function (pattern, ctx) { this.__root = pattern; this.__ctx = ctx; }; @@ -205,26 +212,27 @@ /** * The mock canvas context * @param o - options include: + * ctx - existing Context2D to wrap around * width - width of your canvas (defaults to 500) * height - height of your canvas (defaults to 500) * enableMirroring - enables canvas mirroring (get image data) (defaults to false) + * document - the document object (defaults to the current document) */ - ctx = function(o) { - - var defaultOptions = { width:500, height:500, enableMirroring : false }, options; + ctx = function (o) { + var defaultOptions = { width:500, height:500, enableMirroring : false}, options; //keep support for this way of calling C2S: new C2S(width,height) - if(arguments.length > 1) { + if (arguments.length > 1) { options = defaultOptions; options.width = arguments[0]; options.height = arguments[1]; - } else if( !o ) { + } else if ( !o ) { options = defaultOptions; } else { options = o; } - if(!(this instanceof ctx)) { + if (!(this instanceof ctx)) { //did someone call this without new? return new ctx(options); } @@ -235,15 +243,23 @@ this.enableMirroring = options.enableMirroring !== undefined ? options.enableMirroring : defaultOptions.enableMirroring; this.canvas = this; ///point back to this instance! - this.__canvas = document.createElement("canvas"); - this.__ctx = this.__canvas.getContext("2d"); + this.__document = options.document || document; + + // allow passing in an existing context to wrap around + // if a context is passed in, we know a canvas already exist + if (options.ctx) { + this.__ctx = options.ctx; + } else { + this.__canvas = this.__document.createElement("canvas"); + this.__ctx = this.__canvas.getContext("2d"); + } this.__setDefaultStyles(); this.__stack = [this.__getStyleState()]; this.__groupStack = []; //the root svg element - this.__root = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg"); this.__root.setAttribute("version", 1.1); this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg"); this.__root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); @@ -254,31 +270,32 @@ this.__ids = {}; //defs tag - this.__defs = document.createElementNS("http://www.w3.org/2000/svg", "defs"); + this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs"); this.__root.appendChild(this.__defs); //also add a group child. the svg element can't use the transform attribute - this.__currentElement = document.createElementNS("http://www.w3.org/2000/svg", "g"); + this.__currentElement = this.__document.createElementNS("http://www.w3.org/2000/svg", "g"); this.__root.appendChild(this.__currentElement); }; + /** * Creates the specified svg element * @private */ - ctx.prototype.__createElement = function(elementName, properties, resetFill) { + ctx.prototype.__createElement = function (elementName, properties, resetFill) { if (typeof properties === "undefined") { properties = {}; } - var element = document.createElementNS("http://www.w3.org/2000/svg", elementName), + var element = this.__document.createElementNS("http://www.w3.org/2000/svg", elementName), keys = Object.keys(properties), i, key; - if(resetFill) { + if (resetFill) { //if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black. element.setAttribute("fill", "none"); element.setAttribute("stroke", "none"); } - for(i=0; i 0) { + if (parent.childNodes.length > 0) { + if (this.__currentElement.nodeName === "path") { + if (!this.__currentElementsToStyle) this.__currentElementsToStyle = {element: parent, children: []}; + this.__currentElementsToStyle.children.push(this.__currentElement) + this.__applyCurrentDefaultPath(); + } + var group = this.__createElement("g"); parent.appendChild(group); this.__currentElement = group; } var transform = this.__currentElement.getAttribute("transform"); - if(transform) { + if (transform) { transform += " "; } else { transform = ""; @@ -469,8 +519,8 @@ /** * scales the current element */ - ctx.prototype.scale = function(x, y) { - if(y === undefined) { + ctx.prototype.scale = function (x, y) { + if (y === undefined) { y = x; } this.__addTransform(format("scale({x},{y})", {x:x, y:y})); @@ -479,7 +529,7 @@ /** * rotates the current element */ - ctx.prototype.rotate = function(angle){ + ctx.prototype.rotate = function (angle) { var degrees = (angle * 180 / Math.PI); this.__addTransform(format("rotate({angle},{cx},{cy})", {angle:degrees, cx:0, cy:0})); }; @@ -487,26 +537,27 @@ /** * translates the current element */ - ctx.prototype.translate = function(x, y){ + ctx.prototype.translate = function (x, y) { this.__addTransform(format("translate({x},{y})", {x:x,y:y})); }; /** * applies a transform to the current element */ - ctx.prototype.transform = function(a, b, c, d, e, f){ + ctx.prototype.transform = function (a, b, c, d, e, f) { this.__addTransform(format("matrix({a},{b},{c},{d},{e},{f})", {a:a, b:b, c:c, d:d, e:e, f:f})); }; /** * Create a new Path Element */ - ctx.prototype.beginPath = function(){ + ctx.prototype.beginPath = function () { var path, parent; // Note that there is only one current default path, it is not part of the drawing state. // See also: https://html.spec.whatwg.org/multipage/scripting.html#current-default-path this.__currentDefaultPath = ""; + this.__currentPosition = {}; path = this.__createElement("path", {}, true); parent = this.__closestGroupOrSvg(); @@ -518,12 +569,12 @@ * Helper function to apply currentDefaultPath to current path element * @private */ - ctx.prototype.__applyCurrentDefaultPath = function() { - if(this.__currentElement.nodeName === "path") { - var d = this.__currentDefaultPath; - this.__currentElement.setAttribute("d", d); + ctx.prototype.__applyCurrentDefaultPath = function () { + var currentElement = this.__currentElement; + if (currentElement.nodeName === "path") { + currentElement.setAttribute("d", this.__currentDefaultPath); } else { - throw new Error("Attempted to apply path command to node " + this.__currentElement.nodeName); + console.error("Attempted to apply path command to node", currentElement.nodeName); } }; @@ -531,7 +582,7 @@ * Helper function to add path command * @private */ - ctx.prototype.__addPathCommand = function(command){ + ctx.prototype.__addPathCommand = function (command) { this.__currentDefaultPath += " "; this.__currentDefaultPath += command; }; @@ -540,31 +591,42 @@ * Adds the move command to the current path element, * if the currentPathElement is not empty create a new path element */ - ctx.prototype.moveTo = function(x,y){ - if(this.__currentElement.nodeName !== "path") { + ctx.prototype.moveTo = function (x,y) { + if (this.__currentElement.nodeName !== "path") { this.beginPath(); } + + // creates a new subpath with the given point + this.__currentPosition = {x: x, y: y}; this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); }; /** * Closes the current path */ - ctx.prototype.closePath = function(){ - this.__addPathCommand("Z"); + ctx.prototype.closePath = function () { + if (this.__currentDefaultPath) { + this.__addPathCommand("Z"); + } }; /** * Adds a line to command */ - ctx.prototype.lineTo = function(x, y){ - this.__addPathCommand(format("L {x} {y}", {x:x, y:y})); + ctx.prototype.lineTo = function (x, y) { + this.__currentPosition = {x: x, y: y}; + if (this.__currentDefaultPath.indexOf('M') > -1) { + this.__addPathCommand(format("L {x} {y}", {x:x, y:y})); + } else { + this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); + } }; /** * Add a bezier command */ - ctx.prototype.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { + ctx.prototype.bezierCurveTo = function (cp1x, cp1y, cp2x, cp2y, x, y) { + this.__currentPosition = {x: x, y: y}; this.__addPathCommand(format("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}", {cp1x:cp1x, cp1y:cp1y, cp2x:cp2x, cp2y:cp2y, x:x, y:y})); }; @@ -572,14 +634,120 @@ /** * Adds a quadratic curve to command */ - ctx.prototype.quadraticCurveTo = function(cpx, cpy, x, y){ + ctx.prototype.quadraticCurveTo = function (cpx, cpy, x, y) { + this.__currentPosition = {x: x, y: y}; this.__addPathCommand(format("Q {cpx} {cpy} {x} {y}", {cpx:cpx, cpy:cpy, x:x, y:y})); }; + + /** + * Return a new normalized vector of given vector + */ + var normalize = function (vector) { + var len = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]); + return [vector[0] / len, vector[1] / len]; + }; + + /** + * Adds the arcTo to the current path + * + * @see http://www.w3.org/TR/2015/WD-2dcontext-20150514/#dom-context-2d-arcto + */ + ctx.prototype.arcTo = function (x1, y1, x2, y2, radius) { + // Let the point (x0, y0) be the last point in the subpath. + var x0 = this.__currentPosition && this.__currentPosition.x; + var y0 = this.__currentPosition && this.__currentPosition.y; + + // First ensure there is a subpath for (x1, y1). + if (typeof x0 == "undefined" || typeof y0 == "undefined") { + return; + } + + // Negative values for radius must cause the implementation to throw an IndexSizeError exception. + if (radius < 0) { + throw new Error("IndexSizeError: The radius provided (" + radius + ") is negative."); + } + + // If the point (x0, y0) is equal to the point (x1, y1), + // or if the point (x1, y1) is equal to the point (x2, y2), + // or if the radius radius is zero, + // then the method must add the point (x1, y1) to the subpath, + // and connect that point to the previous point (x0, y0) by a straight line. + if (((x0 === x1) && (y0 === y1)) + || ((x1 === x2) && (y1 === y2)) + || (radius === 0)) { + this.lineTo(x1, y1); + return; + } + + // Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line, + // then the method must add the point (x1, y1) to the subpath, + // and connect that point to the previous point (x0, y0) by a straight line. + var unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]); + var unit_vec_p1_p2 = normalize([x2 - x1, y2 - y1]); + if (unit_vec_p1_p0[0] * unit_vec_p1_p2[1] === unit_vec_p1_p0[1] * unit_vec_p1_p2[0]) { + this.lineTo(x1, y1); + return; + } + + // Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius, + // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1), + // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1), and crosses the point (x2, y2). + // The points at which this circle touches these two lines are called the start and end tangent points respectively. + + // note that both vectors are unit vectors, so the length is 1 + var cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]); + var theta = Math.acos(Math.abs(cos)); + + // Calculate origin + var unit_vec_p1_origin = normalize([ + unit_vec_p1_p0[0] + unit_vec_p1_p2[0], + unit_vec_p1_p0[1] + unit_vec_p1_p2[1] + ]); + var len_p1_origin = radius / Math.sin(theta / 2); + var x = x1 + len_p1_origin * unit_vec_p1_origin[0]; + var y = y1 + len_p1_origin * unit_vec_p1_origin[1]; + + // Calculate start angle and end angle + // rotate 90deg clockwise (note that y axis points to its down) + var unit_vec_origin_start_tangent = [ + -unit_vec_p1_p0[1], + unit_vec_p1_p0[0] + ]; + // rotate 90deg counter clockwise (note that y axis points to its down) + var unit_vec_origin_end_tangent = [ + unit_vec_p1_p2[1], + -unit_vec_p1_p2[0] + ]; + var getAngle = function (vector) { + // get angle (clockwise) between vector and (1, 0) + var x = vector[0]; + var y = vector[1]; + if (y >= 0) { // note that y axis points to its down + return Math.acos(x); + } else { + return -Math.acos(x); + } + }; + var startAngle = getAngle(unit_vec_origin_start_tangent); + var endAngle = getAngle(unit_vec_origin_end_tangent); + + // Connect the point (x0, y0) to the start tangent point by a straight line + this.lineTo(x + unit_vec_origin_start_tangent[0] * radius, + y + unit_vec_origin_start_tangent[1] * radius); + + // Connect the start tangent point to the end tangent point by arc + // and adding the end tangent point to the subpath. + this.arc(x, y, radius, startAngle, endAngle); + }; + /** * Sets the stroke property on the current element */ - ctx.prototype.stroke = function(){ + ctx.prototype.stroke = function () { + if (this.__currentElement.nodeName === "path") { + this.__currentElement.setAttribute("paint-order", "fill stroke markers"); + } this.__applyCurrentDefaultPath(); this.__applyStyleToCurrentElement("stroke"); }; @@ -587,7 +755,10 @@ /** * Sets fill properties on the current element */ - ctx.prototype.fill = function(){ + ctx.prototype.fill = function () { + if (this.__currentElement.nodeName === "path") { + this.__currentElement.setAttribute("paint-order", "stroke fill markers"); + } this.__applyCurrentDefaultPath(); this.__applyStyleToCurrentElement("fill"); }; @@ -595,8 +766,8 @@ /** * Adds a rectangle to the path. */ - ctx.prototype.rect = function(x, y, width, height){ - if(this.__currentElement.nodeName !== "path") { + ctx.prototype.rect = function (x, y, width, height) { + if (this.__currentElement.nodeName !== "path") { this.beginPath(); } this.moveTo(x, y); @@ -611,7 +782,7 @@ /** * adds a rectangle element */ - ctx.prototype.fillRect = function(x, y, width, height){ + ctx.prototype.fillRect = function (x, y, width, height) { var rect, parent; rect = this.__createElement("rect", { x : x, @@ -632,7 +803,7 @@ * @param width * @param height */ - ctx.prototype.strokeRect = function(x, y, width, height){ + ctx.prototype.strokeRect = function (x, y, width, height) { var rect, parent; rect = this.__createElement("rect", { x : x, @@ -647,10 +818,38 @@ }; + /** + * Clear entire canvas: + * 1. save current transforms + * 2. remove all the childNodes of the root g element + */ + ctx.prototype.__clearCanvas = function () { + var current = this.__closestGroupOrSvg(), + transform = current.getAttribute("transform"); + var rootGroup = this.__root.childNodes[1]; + var childNodes = rootGroup.childNodes; + for (var i = childNodes.length - 1; i >= 0; i--) { + if (childNodes[i]) { + rootGroup.removeChild(childNodes[i]); + } + } + this.__currentElement = rootGroup; + //reset __groupStack as all the child group nodes are all removed. + this.__groupStack = []; + if (transform) { + this.__addTransform(transform); + } + }; + /** * "Clears" a canvas by just drawing a white rectangle in the current group. */ - ctx.prototype.clearRect = function(x, y, width, height) { + ctx.prototype.clearRect = function (x, y, width, height) { + //clear entire canvas + if (x === 0 && y === 0 && width === this.width && height === this.height) { + this.__clearCanvas(); + return; + } var rect, parent = this.__closestGroupOrSvg(); rect = this.__createElement("rect", { x : x, @@ -666,7 +865,7 @@ * Adds a linear gradient to a defs tag. * Returns a canvas gradient object that has a reference to it's parent def */ - ctx.prototype.createLinearGradient = function(x1, y1, x2, y2){ + ctx.prototype.createLinearGradient = function (x1, y1, x2, y2) { var grad = this.__createElement("linearGradient", { id : randomString(this.__ids), x1 : x1+"px", @@ -676,14 +875,14 @@ "gradientUnits" : "userSpaceOnUse" }, false); this.__defs.appendChild(grad); - return new CanvasGradient(grad); + return new CanvasGradient(grad, this); }; /** * Adds a radial gradient to a defs tag. * Returns a canvas gradient object that has a reference to it's parent def */ - ctx.prototype.createRadialGradient = function(x0, y0, r0, x1, y1, r1){ + ctx.prototype.createRadialGradient = function (x0, y0, r0, x1, y1, r1) { var grad = this.__createElement("radialGradient", { id : randomString(this.__ids), cx : x1+"px", @@ -694,7 +893,7 @@ "gradientUnits" : "userSpaceOnUse" }, false); this.__defs.appendChild(grad); - return new CanvasGradient(grad); + return new CanvasGradient(grad, this); }; @@ -702,8 +901,8 @@ * Parses the font string and returns svg mapping * @private */ - ctx.prototype.__parseFont = function() { - var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/i; + ctx.prototype.__parseFont = function () { + var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z0-9]+?)\s*$/i; var fontPart = regex.exec( this.font ); var data = { style : fontPart[1] || 'normal', @@ -715,12 +914,12 @@ }; //canvas doesn't support underline natively, but we can pass this attribute - if(this.__fontUnderline === "underline") { + if (this.__fontUnderline === "underline") { data.decoration = "underline"; } //canvas also doesn't support linking, but we can pass this as well - if(this.__fontHref) { + if (this.__fontHref) { data.href = this.__fontHref; } @@ -734,8 +933,8 @@ * @return {*} * @private */ - ctx.prototype.__wrapTextLink = function(font, element) { - if(font.href) { + ctx.prototype.__wrapTextLink = function (font, element) { + if (font.href) { var a = this.__createElement("a"); a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", font.href); a.appendChild(element); @@ -752,7 +951,7 @@ * @param action - stroke or fill * @private */ - ctx.prototype.__applyText = function(text, x, y, action) { + ctx.prototype.__applyText = function (text, x, y, action) { var font = this.__parseFont(), parent = this.__closestGroupOrSvg(), textElement = this.__createElement("text", { @@ -767,7 +966,7 @@ "dominant-baseline": getDominantBaseline(this.textBaseline) }, true); - textElement.appendChild(document.createTextNode(text)); + textElement.appendChild(this.__document.createTextNode(text)); this.__currentElement = textElement; this.__applyStyleToCurrentElement(action); parent.appendChild(this.__wrapTextLink(font,textElement)); @@ -779,7 +978,7 @@ * @param x * @param y */ - ctx.prototype.fillText = function(text, x, y){ + ctx.prototype.fillText = function (text, x, y) { this.__applyText(text, x, y, "fill"); }; @@ -789,7 +988,7 @@ * @param x * @param y */ - ctx.prototype.strokeText = function(text, x, y){ + ctx.prototype.strokeText = function (text, x, y) { this.__applyText(text, x, y, "stroke"); }; @@ -798,7 +997,7 @@ * @param text * @return {TextMetrics} */ - ctx.prototype.measureText = function(text){ + ctx.prototype.measureText = function (text) { this.__ctx.font = this.font; return this.__ctx.measureText(text); }; @@ -806,10 +1005,14 @@ /** * Arc command! */ - ctx.prototype.arc = function(x, y, radius, startAngle, endAngle, counterClockwise) { + ctx.prototype.arc = function (x, y, radius, startAngle, endAngle, counterClockwise) { + // in canvas no circle is drawn if no angle is provided. + if (startAngle === endAngle) { + return; + } startAngle = startAngle % (2*Math.PI); endAngle = endAngle % (2*Math.PI); - if(startAngle === endAngle) { + if (startAngle === endAngle) { //circle time! subtract some of the angle so svg is happy (svg elliptical arc can't draw a full circle) endAngle = ((endAngle + (2*Math.PI)) - 0.001 * (counterClockwise ? -1 : 1)) % (2*Math.PI); } @@ -822,11 +1025,11 @@ diff = endAngle - startAngle; // https://github.com/gliffy/canvas2svg/issues/4 - if(diff < 0) { + if (diff < 0) { diff += 2*Math.PI; } - if(counterClockwise) { + if (counterClockwise) { largeArcFlag = diff > Math.PI ? 0 : 1; } else { largeArcFlag = diff > Math.PI ? 1 : 0; @@ -836,17 +1039,19 @@ this.__addPathCommand(format("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}", {rx:radius, ry:radius, xAxisRotation:0, largeArcFlag:largeArcFlag, sweepFlag:sweepFlag, endX:endX, endY:endY})); + this.__currentPosition = {x: endX, y: endY}; }; /** * Generates a ClipPath from the clip command. */ - ctx.prototype.clip = function(){ + ctx.prototype.clip = function () { var group = this.__closestGroupOrSvg(), clipPath = this.__createElement("clipPath"), id = randomString(this.__ids), newGroup = this.__createElement("g"); + this.__applyCurrentDefaultPath(); group.removeChild(this.__currentElement); clipPath.setAttribute("id", id); clipPath.appendChild(this.__currentElement); @@ -869,28 +1074,28 @@ * Note that all svg dom manipulation uses node.childNodes rather than node.children for IE support. * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-drawimage */ - ctx.prototype.drawImage = function(){ + ctx.prototype.drawImage = function () { //convert arguments to a real array var args = Array.prototype.slice.call(arguments), image=args[0], dx, dy, dw, dh, sx=0, sy=0, sw, sh, parent, svg, defs, group, currentElement, svgImage, canvas, context, id; - if(args.length === 3) { + if (args.length === 3) { dx = args[1]; dy = args[2]; sw = image.width; sh = image.height; dw = sw; dh = sh; - } else if(args.length === 5) { + } else if (args.length === 5) { dx = args[1]; dy = args[2]; dw = args[3]; dh = args[4]; sw = image.width; sh = image.height; - } else if(args.length === 9) { + } else if (args.length === 9) { sx = args[1]; sy = args[2]; sw = args[3]; @@ -900,89 +1105,110 @@ dw = args[7]; dh = args[8]; } else { - throw new Error("Inavlid number of arguments passed to drawImage: " + arguments.length); + throw new Error("Invalid number of arguments passed to drawImage: " + arguments.length); } parent = this.__closestGroupOrSvg(); currentElement = this.__currentElement; - - if(image instanceof ctx) { + var translateDirective = "translate(" + dx + ", " + dy + ")"; + if (image instanceof ctx) { //canvas2svg mock canvas context. In the future we may want to clone nodes instead. //also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context. - svg = image.getSvg(); - defs = svg.childNodes[0]; - while(defs.childNodes.length) { - id = defs.childNodes[0].getAttribute("id"); - this.__ids[id] = id; - this.__defs.appendChild(defs.childNodes[0]); + svg = image.getSvg().cloneNode(true); + if (svg.childNodes && svg.childNodes.length > 1) { + defs = svg.childNodes[0]; + while(defs.childNodes.length) { + id = defs.childNodes[0].getAttribute("id"); + this.__ids[id] = id; + this.__defs.appendChild(defs.childNodes[0]); + } + group = svg.childNodes[1]; + if (group) { + //save original transform + var originTransform = group.getAttribute("transform"); + var transformDirective; + if (originTransform) { + transformDirective = originTransform+" "+translateDirective; + } else { + transformDirective = translateDirective; + } + group.setAttribute("transform", transformDirective); + parent.appendChild(group); + } } - group = svg.childNodes[1]; - parent.appendChild(group); - this.__currentElement = group; - this.translate(dx, dy); - this.__currentElement = currentElement; - } else if(image.nodeName === "CANVAS" || image.nodeName === "IMG") { + } else if (image.nodeName === "CANVAS" || image.nodeName === "IMG") { //canvas or image svgImage = this.__createElement("image"); svgImage.setAttribute("width", dw); svgImage.setAttribute("height", dh); svgImage.setAttribute("preserveAspectRatio", "none"); - if(sx || sy || sw !== image.width || sh !== image.height) { + if (sx || sy || sw !== image.width || sh !== image.height) { //crop the image using a temporary canvas - canvas = document.createElement("canvas"); + canvas = this.__document.createElement("canvas"); canvas.width = dw; canvas.height = dh; context = canvas.getContext("2d"); context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh); image = canvas; } - + svgImage.setAttribute("transform", translateDirective); svgImage.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); parent.appendChild(svgImage); - this.__currentElement = svgImage; - this.translate(dx, dy); - this.__currentElement = currentElement; } }; /** * Generates a pattern tag */ - ctx.prototype.createPattern = function(image, repetition){ - var pattern = document.createElementNS("http://www.w3.org/2000/svg", "pattern"), id = randomString(this.__ids), + ctx.prototype.createPattern = function (image, repetition) { + var pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern"), id = randomString(this.__ids), img; pattern.setAttribute("id", id); pattern.setAttribute("width", image.width); pattern.setAttribute("height", image.height); - if(image.nodeName === "CANVAS" || image.nodeName === "IMG") { - img = document.createElementNS("http://www.w3.org/2000/svg", "image"); + if (image.nodeName === "CANVAS" || image.nodeName === "IMG") { + img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image"); img.setAttribute("width", image.width); img.setAttribute("height", image.height); img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); pattern.appendChild(img); this.__defs.appendChild(pattern); - } else if(image instanceof ctx) { + } else if (image instanceof ctx) { pattern.appendChild(image.__root.childNodes[1]); this.__defs.appendChild(pattern); } return new CanvasPattern(pattern, this); }; + ctx.prototype.setLineDash = function (dashArray) { + if (dashArray && dashArray.length > 0) { + this.lineDash = dashArray.join(","); + } else { + this.lineDash = null; + } + }; + /** * Not yet implemented */ - ctx.prototype.drawFocusRing = function(){}; - ctx.prototype.createImageData = function(){}; - ctx.prototype.getImageData = function(){}; - ctx.prototype.putImageData = function(){}; - ctx.prototype.globalCompositeOperation = function(){}; - ctx.prototype.arcTo = function(){}; - ctx.prototype.setTransform = function(){}; + ctx.prototype.drawFocusRing = function () {}; + ctx.prototype.createImageData = function () {}; + ctx.prototype.getImageData = function () {}; + ctx.prototype.putImageData = function () {}; + ctx.prototype.globalCompositeOperation = function () {}; + ctx.prototype.setTransform = function () {}; //add options for alternative namespace - window.C2S = ctx; + if (typeof window === "object") { + window.C2S = ctx; + } + + // CommonJS/Browserify + if (typeof module === "object" && typeof module.exports === "object") { + module.exports = ctx; + } }()); diff --git a/gulpfile.js b/gulpfile.js new file mode 100644 index 0000000..35c3e12 --- /dev/null +++ b/gulpfile.js @@ -0,0 +1,38 @@ +"use strict"; + +var gulp = require('gulp'); +var fs = require('fs'); +var path = require('path'); +var cheerio = require('cheerio'); +var bump = require('gulp-bump'); + + +function updateExample(filename) { + var playground = fs.readFileSync(path.join(__dirname, filename), {'encoding': 'utf8'}); + var filenames = fs.readdirSync(path.join(__dirname,'test/example')); + var $ = cheerio.load(playground); + var $examples = $('#examples'); + var $select = $('#select'); + $examples.empty(); + $select.empty(); + filenames.forEach(function(filename) { + var name = filename.replace('.js', ''); + $examples.append($('')); + $select.append($('')); + }); + fs.writeFileSync(path.join(__dirname, filename), $.html(), {'encoding': 'utf8'}) +} + +// run this after adding an example file to update playground.html, and testrunner.html +gulp.task('update_examples', function() { + updateExample('test/playground.html'); + updateExample('test/testrunner.html'); +}); + +gulp.task('bump', function() { + gulp.src(["./package.json", "./bower.json"]) + .pipe(bump({type:'patch'})) + .pipe(gulp.dest('./')); +}); + +gulp.task('default', ['update_examples']); diff --git a/jasmine-tests/SpecRunner.html b/jasmine-tests/SpecRunner.html deleted file mode 100755 index 2dbf8c7..0000000 --- a/jasmine-tests/SpecRunner.html +++ /dev/null @@ -1,24 +0,0 @@ - - - - - Jasmine Spec Runner v2.0.0 - - - - - - - - - - - - - - - - - - - diff --git a/jasmine-tests/canvassvg.html b/jasmine-tests/canvassvg.html deleted file mode 100644 index 8a9778c..0000000 --- a/jasmine-tests/canvassvg.html +++ /dev/null @@ -1,57 +0,0 @@ - - - - - Canvas2Svg - - - - -
- -
-
- -Render -
- - - diff --git a/jasmine-tests/lib/jasmine-2.0.0/boot.js b/jasmine-tests/lib/jasmine-2.0.0/boot.js deleted file mode 100755 index ec8baa0..0000000 --- a/jasmine-tests/lib/jasmine-2.0.0/boot.js +++ /dev/null @@ -1,181 +0,0 @@ -/** - Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. - - If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. - - The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. - - [jasmine-gem]: http://github.com/pivotal/jasmine-gem - */ - -(function() { - - /** - * ## Require & Instantiate - * - * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. - */ - window.jasmine = jasmineRequire.core(jasmineRequire); - - /** - * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. - */ - jasmineRequire.html(jasmine); - - /** - * Create the Jasmine environment. This is used to run all specs in a project. - */ - var env = jasmine.getEnv(); - - /** - * ## The Global Interface - * - * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. - */ - var jasmineInterface = { - describe: function(description, specDefinitions) { - return env.describe(description, specDefinitions); - }, - - xdescribe: function(description, specDefinitions) { - return env.xdescribe(description, specDefinitions); - }, - - it: function(desc, func) { - return env.it(desc, func); - }, - - xit: function(desc, func) { - return env.xit(desc, func); - }, - - beforeEach: function(beforeEachFunction) { - return env.beforeEach(beforeEachFunction); - }, - - afterEach: function(afterEachFunction) { - return env.afterEach(afterEachFunction); - }, - - expect: function(actual) { - return env.expect(actual); - }, - - pending: function() { - return env.pending(); - }, - - spyOn: function(obj, methodName) { - return env.spyOn(obj, methodName); - }, - - jsApiReporter: new jasmine.JsApiReporter({ - timer: new jasmine.Timer() - }) - }; - - /** - * Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. - */ - if (typeof window == "undefined" && typeof exports == "object") { - extend(exports, jasmineInterface); - } else { - extend(window, jasmineInterface); - } - - /** - * Expose the interface for adding custom equality testers. - */ - jasmine.addCustomEqualityTester = function(tester) { - env.addCustomEqualityTester(tester); - }; - - /** - * Expose the interface for adding custom expectation matchers - */ - jasmine.addMatchers = function(matchers) { - return env.addMatchers(matchers); - }; - - /** - * Expose the mock interface for the JavaScript timeout functions - */ - jasmine.clock = function() { - return env.clock; - }; - - /** - * ## Runner Parameters - * - * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. - */ - - var queryString = new jasmine.QueryString({ - getWindowLocation: function() { return window.location; } - }); - - var catchingExceptions = queryString.getParam("catch"); - env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions); - - /** - * ## Reporters - * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). - */ - var htmlReporter = new jasmine.HtmlReporter({ - env: env, - onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); }, - getContainer: function() { return document.body; }, - createElement: function() { return document.createElement.apply(document, arguments); }, - createTextNode: function() { return document.createTextNode.apply(document, arguments); }, - timer: new jasmine.Timer() - }); - - /** - * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. - */ - env.addReporter(jasmineInterface.jsApiReporter); - env.addReporter(htmlReporter); - - /** - * Filter which specs will be run by matching the start of the full name against the `spec` query param. - */ - var specFilter = new jasmine.HtmlSpecFilter({ - filterString: function() { return queryString.getParam("spec"); } - }); - - env.specFilter = function(spec) { - return specFilter.matches(spec.getFullName()); - }; - - /** - * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. - */ - window.setTimeout = window.setTimeout; - window.setInterval = window.setInterval; - window.clearTimeout = window.clearTimeout; - window.clearInterval = window.clearInterval; - - /** - * ## Execution - * - * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. - */ - var currentWindowOnload = window.onload; - - window.onload = function() { - if (currentWindowOnload) { - currentWindowOnload(); - } - htmlReporter.initialize(); - env.execute(); - }; - - /** - * Helper function for readability above. - */ - function extend(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; - } - -}()); diff --git a/jasmine-tests/lib/jasmine-2.0.0/console.js b/jasmine-tests/lib/jasmine-2.0.0/console.js deleted file mode 100755 index 33c1698..0000000 --- a/jasmine-tests/lib/jasmine-2.0.0/console.js +++ /dev/null @@ -1,160 +0,0 @@ -/* -Copyright (c) 2008-2013 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -function getJasmineRequireObj() { - if (typeof module !== "undefined" && module.exports) { - return exports; - } else { - window.jasmineRequire = window.jasmineRequire || {}; - return window.jasmineRequire; - } -} - -getJasmineRequireObj().console = function(jRequire, j$) { - j$.ConsoleReporter = jRequire.ConsoleReporter(); -}; - -getJasmineRequireObj().ConsoleReporter = function() { - - var noopTimer = { - start: function(){}, - elapsed: function(){ return 0; } - }; - - function ConsoleReporter(options) { - var print = options.print, - showColors = options.showColors || false, - onComplete = options.onComplete || function() {}, - timer = options.timer || noopTimer, - specCount, - failureCount, - failedSpecs = [], - pendingCount, - ansi = { - green: '\x1B[32m', - red: '\x1B[31m', - yellow: '\x1B[33m', - none: '\x1B[0m' - }; - - this.jasmineStarted = function() { - specCount = 0; - failureCount = 0; - pendingCount = 0; - print("Started"); - printNewline(); - timer.start(); - }; - - this.jasmineDone = function() { - printNewline(); - for (var i = 0; i < failedSpecs.length; i++) { - specFailureDetails(failedSpecs[i]); - } - - printNewline(); - var specCounts = specCount + " " + plural("spec", specCount) + ", " + - failureCount + " " + plural("failure", failureCount); - - if (pendingCount) { - specCounts += ", " + pendingCount + " pending " + plural("spec", pendingCount); - } - - print(specCounts); - - printNewline(); - var seconds = timer.elapsed() / 1000; - print("Finished in " + seconds + " " + plural("second", seconds)); - - printNewline(); - - onComplete(failureCount === 0); - }; - - this.specDone = function(result) { - specCount++; - - if (result.status == "pending") { - pendingCount++; - print(colored("yellow", "*")); - return; - } - - if (result.status == "passed") { - print(colored("green", '.')); - return; - } - - if (result.status == "failed") { - failureCount++; - failedSpecs.push(result); - print(colored("red", 'F')); - } - }; - - return this; - - function printNewline() { - print("\n"); - } - - function colored(color, str) { - return showColors ? (ansi[color] + str + ansi.none) : str; - } - - function plural(str, count) { - return count == 1 ? str : str + "s"; - } - - function repeat(thing, times) { - var arr = []; - for (var i = 0; i < times; i++) { - arr.push(thing); - } - return arr; - } - - function indent(str, spaces) { - var lines = (str || '').split("\n"); - var newArr = []; - for (var i = 0; i < lines.length; i++) { - newArr.push(repeat(" ", spaces).join("") + lines[i]); - } - return newArr.join("\n"); - } - - function specFailureDetails(result) { - printNewline(); - print(result.fullName); - - for (var i = 0; i < result.failedExpectations.length; i++) { - var failedExpectation = result.failedExpectations[i]; - printNewline(); - print(indent(failedExpectation.stack, 2)); - } - - printNewline(); - } - } - - return ConsoleReporter; -}; diff --git a/jasmine-tests/lib/jasmine-2.0.0/jasmine-html.js b/jasmine-tests/lib/jasmine-2.0.0/jasmine-html.js deleted file mode 100755 index 985d0d1..0000000 --- a/jasmine-tests/lib/jasmine-2.0.0/jasmine-html.js +++ /dev/null @@ -1,359 +0,0 @@ -/* -Copyright (c) 2008-2013 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -jasmineRequire.html = function(j$) { - j$.ResultsNode = jasmineRequire.ResultsNode(); - j$.HtmlReporter = jasmineRequire.HtmlReporter(j$); - j$.QueryString = jasmineRequire.QueryString(); - j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter(); -}; - -jasmineRequire.HtmlReporter = function(j$) { - - var noopTimer = { - start: function() {}, - elapsed: function() { return 0; } - }; - - function HtmlReporter(options) { - var env = options.env || {}, - getContainer = options.getContainer, - createElement = options.createElement, - createTextNode = options.createTextNode, - onRaiseExceptionsClick = options.onRaiseExceptionsClick || function() {}, - timer = options.timer || noopTimer, - results = [], - specsExecuted = 0, - failureCount = 0, - pendingSpecCount = 0, - htmlReporterMain, - symbols; - - this.initialize = function() { - htmlReporterMain = createDom("div", {className: "html-reporter"}, - createDom("div", {className: "banner"}, - createDom("span", {className: "title"}, "Jasmine"), - createDom("span", {className: "version"}, j$.version) - ), - createDom("ul", {className: "symbol-summary"}), - createDom("div", {className: "alert"}), - createDom("div", {className: "results"}, - createDom("div", {className: "failures"}) - ) - ); - getContainer().appendChild(htmlReporterMain); - - symbols = find(".symbol-summary"); - }; - - var totalSpecsDefined; - this.jasmineStarted = function(options) { - totalSpecsDefined = options.totalSpecsDefined || 0; - timer.start(); - }; - - var summary = createDom("div", {className: "summary"}); - - var topResults = new j$.ResultsNode({}, "", null), - currentParent = topResults; - - this.suiteStarted = function(result) { - currentParent.addChild(result, "suite"); - currentParent = currentParent.last(); - }; - - this.suiteDone = function(result) { - if (currentParent == topResults) { - return; - } - - currentParent = currentParent.parent; - }; - - this.specStarted = function(result) { - currentParent.addChild(result, "spec"); - }; - - var failures = []; - this.specDone = function(result) { - if (result.status != "disabled") { - specsExecuted++; - } - - symbols.appendChild(createDom("li", { - className: result.status, - id: "spec_" + result.id, - title: result.fullName - } - )); - - if (result.status == "failed") { - failureCount++; - - var failure = - createDom("div", {className: "spec-detail failed"}, - createDom("div", {className: "description"}, - createDom("a", {title: result.fullName, href: specHref(result)}, result.fullName) - ), - createDom("div", {className: "messages"}) - ); - var messages = failure.childNodes[1]; - - for (var i = 0; i < result.failedExpectations.length; i++) { - var expectation = result.failedExpectations[i]; - messages.appendChild(createDom("div", {className: "result-message"}, expectation.message)); - messages.appendChild(createDom("div", {className: "stack-trace"}, expectation.stack)); - } - - failures.push(failure); - } - - if (result.status == "pending") { - pendingSpecCount++; - } - }; - - this.jasmineDone = function() { - var banner = find(".banner"); - banner.appendChild(createDom("span", {className: "duration"}, "finished in " + timer.elapsed() / 1000 + "s")); - - var alert = find(".alert"); - - alert.appendChild(createDom("span", { className: "exceptions" }, - createDom("label", { className: "label", 'for': "raise-exceptions" }, "raise exceptions"), - createDom("input", { - className: "raise", - id: "raise-exceptions", - type: "checkbox" - }) - )); - var checkbox = find("input"); - - checkbox.checked = !env.catchingExceptions(); - checkbox.onclick = onRaiseExceptionsClick; - - if (specsExecuted < totalSpecsDefined) { - var skippedMessage = "Ran " + specsExecuted + " of " + totalSpecsDefined + " specs - run all"; - alert.appendChild( - createDom("span", {className: "bar skipped"}, - createDom("a", {href: "?", title: "Run all specs"}, skippedMessage) - ) - ); - } - var statusBarMessage = "" + pluralize("spec", specsExecuted) + ", " + pluralize("failure", failureCount); - if (pendingSpecCount) { statusBarMessage += ", " + pluralize("pending spec", pendingSpecCount); } - - var statusBarClassName = "bar " + ((failureCount > 0) ? "failed" : "passed"); - alert.appendChild(createDom("span", {className: statusBarClassName}, statusBarMessage)); - - var results = find(".results"); - results.appendChild(summary); - - summaryList(topResults, summary); - - function summaryList(resultsTree, domParent) { - var specListNode; - for (var i = 0; i < resultsTree.children.length; i++) { - var resultNode = resultsTree.children[i]; - if (resultNode.type == "suite") { - var suiteListNode = createDom("ul", {className: "suite", id: "suite-" + resultNode.result.id}, - createDom("li", {className: "suite-detail"}, - createDom("a", {href: specHref(resultNode.result)}, resultNode.result.description) - ) - ); - - summaryList(resultNode, suiteListNode); - domParent.appendChild(suiteListNode); - } - if (resultNode.type == "spec") { - if (domParent.getAttribute("class") != "specs") { - specListNode = createDom("ul", {className: "specs"}); - domParent.appendChild(specListNode); - } - specListNode.appendChild( - createDom("li", { - className: resultNode.result.status, - id: "spec-" + resultNode.result.id - }, - createDom("a", {href: specHref(resultNode.result)}, resultNode.result.description) - ) - ); - } - } - } - - if (failures.length) { - alert.appendChild( - createDom('span', {className: "menu bar spec-list"}, - createDom("span", {}, "Spec List | "), - createDom('a', {className: "failures-menu", href: "#"}, "Failures"))); - alert.appendChild( - createDom('span', {className: "menu bar failure-list"}, - createDom('a', {className: "spec-list-menu", href: "#"}, "Spec List"), - createDom("span", {}, " | Failures "))); - - find(".failures-menu").onclick = function() { - setMenuModeTo('failure-list'); - }; - find(".spec-list-menu").onclick = function() { - setMenuModeTo('spec-list'); - }; - - setMenuModeTo('failure-list'); - - var failureNode = find(".failures"); - for (var i = 0; i < failures.length; i++) { - failureNode.appendChild(failures[i]); - } - } - }; - - return this; - - function find(selector) { - return getContainer().querySelector(selector); - } - - function createDom(type, attrs, childrenVarArgs) { - var el = createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(createTextNode(child)); - } else { - if (child) { - el.appendChild(child); - } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; - } - - function pluralize(singular, count) { - var word = (count == 1 ? singular : singular + "s"); - - return "" + count + " " + word; - } - - function specHref(result) { - return "?spec=" + encodeURIComponent(result.fullName); - } - - function setMenuModeTo(mode) { - htmlReporterMain.setAttribute("class", "html-reporter " + mode); - } - } - - return HtmlReporter; -}; - -jasmineRequire.HtmlSpecFilter = function() { - function HtmlSpecFilter(options) { - var filterString = options && options.filterString() && options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); - var filterPattern = new RegExp(filterString); - - this.matches = function(specName) { - return filterPattern.test(specName); - }; - } - - return HtmlSpecFilter; -}; - -jasmineRequire.ResultsNode = function() { - function ResultsNode(result, type, parent) { - this.result = result; - this.type = type; - this.parent = parent; - - this.children = []; - - this.addChild = function(result, type) { - this.children.push(new ResultsNode(result, type, this)); - }; - - this.last = function() { - return this.children[this.children.length - 1]; - }; - } - - return ResultsNode; -}; - -jasmineRequire.QueryString = function() { - function QueryString(options) { - - this.setParam = function(key, value) { - var paramMap = queryStringToParamMap(); - paramMap[key] = value; - options.getWindowLocation().search = toQueryString(paramMap); - }; - - this.getParam = function(key) { - return queryStringToParamMap()[key]; - }; - - return this; - - function toQueryString(paramMap) { - var qStrPairs = []; - for (var prop in paramMap) { - qStrPairs.push(encodeURIComponent(prop) + "=" + encodeURIComponent(paramMap[prop])); - } - return "?" + qStrPairs.join('&'); - } - - function queryStringToParamMap() { - var paramStr = options.getWindowLocation().search.substring(1), - params = [], - paramMap = {}; - - if (paramStr.length > 0) { - params = paramStr.split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - var value = decodeURIComponent(p[1]); - if (value === "true" || value === "false") { - value = JSON.parse(value); - } - paramMap[decodeURIComponent(p[0])] = value; - } - } - - return paramMap; - } - - } - - return QueryString; -}; diff --git a/jasmine-tests/lib/jasmine-2.0.0/jasmine.css b/jasmine-tests/lib/jasmine-2.0.0/jasmine.css deleted file mode 100755 index f4d35b6..0000000 --- a/jasmine-tests/lib/jasmine-2.0.0/jasmine.css +++ /dev/null @@ -1,55 +0,0 @@ -body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; } - -.html-reporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; } -.html-reporter a { text-decoration: none; } -.html-reporter a:hover { text-decoration: underline; } -.html-reporter p, .html-reporter h1, .html-reporter h2, .html-reporter h3, .html-reporter h4, .html-reporter h5, .html-reporter h6 { margin: 0; line-height: 14px; } -.html-reporter .banner, .html-reporter .symbol-summary, .html-reporter .summary, .html-reporter .result-message, .html-reporter .spec .description, .html-reporter .spec-detail .description, .html-reporter .alert .bar, .html-reporter .stack-trace { padding-left: 9px; padding-right: 9px; } -.html-reporter .banner .version { margin-left: 14px; } -.html-reporter #jasmine_content { position: fixed; right: 100%; } -.html-reporter .version { color: #aaaaaa; } -.html-reporter .banner { margin-top: 14px; } -.html-reporter .duration { color: #aaaaaa; float: right; } -.html-reporter .symbol-summary { overflow: hidden; *zoom: 1; margin: 14px 0; } -.html-reporter .symbol-summary li { display: inline-block; height: 8px; width: 14px; font-size: 16px; } -.html-reporter .symbol-summary li.passed { font-size: 14px; } -.html-reporter .symbol-summary li.passed:before { color: #5e7d00; content: "\02022"; } -.html-reporter .symbol-summary li.failed { line-height: 9px; } -.html-reporter .symbol-summary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; } -.html-reporter .symbol-summary li.disabled { font-size: 14px; } -.html-reporter .symbol-summary li.disabled:before { color: #bababa; content: "\02022"; } -.html-reporter .symbol-summary li.pending { line-height: 17px; } -.html-reporter .symbol-summary li.pending:before { color: #ba9d37; content: "*"; } -.html-reporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; } -.html-reporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } -.html-reporter .bar.failed { background-color: #b03911; } -.html-reporter .bar.passed { background-color: #a6b779; } -.html-reporter .bar.skipped { background-color: #bababa; } -.html-reporter .bar.menu { background-color: #fff; color: #aaaaaa; } -.html-reporter .bar.menu a { color: #333333; } -.html-reporter .bar a { color: white; } -.html-reporter.spec-list .bar.menu.failure-list, .html-reporter.spec-list .results .failures { display: none; } -.html-reporter.failure-list .bar.menu.spec-list, .html-reporter.failure-list .summary { display: none; } -.html-reporter .running-alert { background-color: #666666; } -.html-reporter .results { margin-top: 14px; } -.html-reporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; } -.html-reporter.showDetails .summaryMenuItem:hover { text-decoration: underline; } -.html-reporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; } -.html-reporter.showDetails .summary { display: none; } -.html-reporter.showDetails #details { display: block; } -.html-reporter .summaryMenuItem { font-weight: bold; text-decoration: underline; } -.html-reporter .summary { margin-top: 14px; } -.html-reporter .summary ul { list-style-type: none; margin-left: 14px; padding-top: 0; padding-left: 0; } -.html-reporter .summary ul.suite { margin-top: 7px; margin-bottom: 7px; } -.html-reporter .summary li.passed a { color: #5e7d00; } -.html-reporter .summary li.failed a { color: #b03911; } -.html-reporter .summary li.pending a { color: #ba9d37; } -.html-reporter .description + .suite { margin-top: 0; } -.html-reporter .suite { margin-top: 14px; } -.html-reporter .suite a { color: #333333; } -.html-reporter .failures .spec-detail { margin-bottom: 28px; } -.html-reporter .failures .spec-detail .description { background-color: #b03911; } -.html-reporter .failures .spec-detail .description a { color: white; } -.html-reporter .result-message { padding-top: 14px; color: #333333; white-space: pre; } -.html-reporter .result-message span.result { display: block; } -.html-reporter .stack-trace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; } diff --git a/jasmine-tests/lib/jasmine-2.0.0/jasmine.js b/jasmine-tests/lib/jasmine-2.0.0/jasmine.js deleted file mode 100755 index 24463ec..0000000 --- a/jasmine-tests/lib/jasmine-2.0.0/jasmine.js +++ /dev/null @@ -1,2402 +0,0 @@ -/* -Copyright (c) 2008-2013 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ -function getJasmineRequireObj() { - if (typeof module !== "undefined" && module.exports) { - return exports; - } else { - window.jasmineRequire = window.jasmineRequire || {}; - return window.jasmineRequire; - } -} - -getJasmineRequireObj().core = function(jRequire) { - var j$ = {}; - - jRequire.base(j$); - j$.util = jRequire.util(); - j$.Any = jRequire.Any(); - j$.CallTracker = jRequire.CallTracker(); - j$.Clock = jRequire.Clock(); - j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(); - j$.Env = jRequire.Env(j$); - j$.ExceptionFormatter = jRequire.ExceptionFormatter(); - j$.Expectation = jRequire.Expectation(); - j$.buildExpectationResult = jRequire.buildExpectationResult(); - j$.JsApiReporter = jRequire.JsApiReporter(); - j$.matchersUtil = jRequire.matchersUtil(j$); - j$.ObjectContaining = jRequire.ObjectContaining(j$); - j$.pp = jRequire.pp(j$); - j$.QueueRunner = jRequire.QueueRunner(); - j$.ReportDispatcher = jRequire.ReportDispatcher(); - j$.Spec = jRequire.Spec(j$); - j$.SpyStrategy = jRequire.SpyStrategy(); - j$.Suite = jRequire.Suite(); - j$.Timer = jRequire.Timer(); - j$.version = jRequire.version(); - - j$.matchers = jRequire.requireMatchers(jRequire, j$); - - return j$; -}; - -getJasmineRequireObj().requireMatchers = function(jRequire, j$) { - var availableMatchers = [ - "toBe", - "toBeCloseTo", - "toBeDefined", - "toBeFalsy", - "toBeGreaterThan", - "toBeLessThan", - "toBeNaN", - "toBeNull", - "toBeTruthy", - "toBeUndefined", - "toContain", - "toEqual", - "toHaveBeenCalled", - "toHaveBeenCalledWith", - "toMatch", - "toThrow", - "toThrowError" - ], - matchers = {}; - - for (var i = 0; i < availableMatchers.length; i++) { - var name = availableMatchers[i]; - matchers[name] = jRequire[name](j$); - } - - return matchers; -}; - -getJasmineRequireObj().base = function(j$) { - j$.unimplementedMethod_ = function() { - throw new Error("unimplemented method"); - }; - - j$.MAX_PRETTY_PRINT_DEPTH = 40; - j$.DEFAULT_TIMEOUT_INTERVAL = 5000; - - j$.getGlobal = (function() { - var jasmineGlobal = eval.call(null, "this"); - return function() { - return jasmineGlobal; - }; - })(); - - j$.getEnv = function(options) { - var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options); - //jasmine. singletons in here (setTimeout blah blah). - return env; - }; - - j$.isArray_ = function(value) { - return j$.isA_("Array", value); - }; - - j$.isString_ = function(value) { - return j$.isA_("String", value); - }; - - j$.isNumber_ = function(value) { - return j$.isA_("Number", value); - }; - - j$.isA_ = function(typeName, value) { - return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; - }; - - j$.isDomNode = function(obj) { - return obj.nodeType > 0; - }; - - j$.any = function(clazz) { - return new j$.Any(clazz); - }; - - j$.objectContaining = function(sample) { - return new j$.ObjectContaining(sample); - }; - - j$.createSpy = function(name, originalFn) { - - var spyStrategy = new j$.SpyStrategy({ - name: name, - fn: originalFn, - getSpy: function() { return spy; } - }), - callTracker = new j$.CallTracker(), - spy = function() { - callTracker.track({ - object: this, - args: Array.prototype.slice.apply(arguments) - }); - return spyStrategy.exec.apply(this, arguments); - }; - - for (var prop in originalFn) { - if (prop === 'and' || prop === 'calls') { - throw new Error("Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon"); - } - - spy[prop] = originalFn[prop]; - } - - spy.and = spyStrategy; - spy.calls = callTracker; - - return spy; - }; - - j$.isSpy = function(putativeSpy) { - if (!putativeSpy) { - return false; - } - return putativeSpy.and instanceof j$.SpyStrategy && - putativeSpy.calls instanceof j$.CallTracker; - }; - - j$.createSpyObj = function(baseName, methodNames) { - if (!j$.isArray_(methodNames) || methodNames.length === 0) { - throw "createSpyObj requires a non-empty array of method names to create spies for"; - } - var obj = {}; - for (var i = 0; i < methodNames.length; i++) { - obj[methodNames[i]] = j$.createSpy(baseName + '.' + methodNames[i]); - } - return obj; - }; -}; - -getJasmineRequireObj().util = function() { - - var util = {}; - - util.inherit = function(childClass, parentClass) { - var Subclass = function() { - }; - Subclass.prototype = parentClass.prototype; - childClass.prototype = new Subclass(); - }; - - util.htmlEscape = function(str) { - if (!str) { - return str; - } - return str.replace(/&/g, '&') - .replace(//g, '>'); - }; - - util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) { - arrayOfArgs.push(args[i]); - } - return arrayOfArgs; - }; - - util.isUndefined = function(obj) { - return obj === void 0; - }; - - return util; -}; - -getJasmineRequireObj().Spec = function(j$) { - function Spec(attrs) { - this.expectationFactory = attrs.expectationFactory; - this.resultCallback = attrs.resultCallback || function() {}; - this.id = attrs.id; - this.description = attrs.description || ''; - this.fn = attrs.fn; - this.beforeFns = attrs.beforeFns || function() { return []; }; - this.afterFns = attrs.afterFns || function() { return []; }; - this.onStart = attrs.onStart || function() {}; - this.exceptionFormatter = attrs.exceptionFormatter || function() {}; - this.getSpecName = attrs.getSpecName || function() { return ''; }; - this.expectationResultFactory = attrs.expectationResultFactory || function() { }; - this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; - this.catchingExceptions = attrs.catchingExceptions || function() { return true; }; - - this.timer = attrs.timer || {setTimeout: setTimeout, clearTimeout: clearTimeout}; - - if (!this.fn) { - this.pend(); - } - - this.result = { - id: this.id, - description: this.description, - fullName: this.getFullName(), - failedExpectations: [] - }; - } - - Spec.prototype.addExpectationResult = function(passed, data) { - if (passed) { - return; - } - this.result.failedExpectations.push(this.expectationResultFactory(data)); - }; - - Spec.prototype.expect = function(actual) { - return this.expectationFactory(actual, this); - }; - - Spec.prototype.execute = function(onComplete) { - var self = this, - timeout; - - this.onStart(this); - - if (this.markedPending || this.disabled) { - complete(); - return; - } - - function timeoutable(fn) { - return function(done) { - timeout = Function.prototype.apply.apply(self.timer.setTimeout, [j$.getGlobal(), [function() { - onException(new Error('Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.')); - done(); - }, j$.DEFAULT_TIMEOUT_INTERVAL]]); - - var callDone = function() { - clearTimeoutable(); - done(); - }; - - fn.call(this, callDone); //TODO: do we care about more than 1 arg? - }; - } - - function clearTimeoutable() { - Function.prototype.apply.apply(self.timer.clearTimeout, [j$.getGlobal(), [timeout]]); - timeout = void 0; - } - - var allFns = this.beforeFns().concat(this.fn).concat(this.afterFns()), - allTimeoutableFns = []; - for (var i = 0; i < allFns.length; i++) { - var fn = allFns[i]; - allTimeoutableFns.push(fn.length > 0 ? timeoutable(fn) : fn); - } - - this.queueRunnerFactory({ - fns: allTimeoutableFns, - onException: onException, - onComplete: complete - }); - - function onException(e) { - clearTimeoutable(); - if (Spec.isPendingSpecException(e)) { - self.pend(); - return; - } - - self.addExpectationResult(false, { - matcherName: "", - passed: false, - expected: "", - actual: "", - error: e - }); - } - - function complete() { - self.result.status = self.status(); - self.resultCallback(self.result); - - if (onComplete) { - onComplete(); - } - } - }; - - Spec.prototype.disable = function() { - this.disabled = true; - }; - - Spec.prototype.pend = function() { - this.markedPending = true; - }; - - Spec.prototype.status = function() { - if (this.disabled) { - return 'disabled'; - } - - if (this.markedPending) { - return 'pending'; - } - - if (this.result.failedExpectations.length > 0) { - return 'failed'; - } else { - return 'passed'; - } - }; - - Spec.prototype.getFullName = function() { - return this.getSpecName(this); - }; - - Spec.pendingSpecExceptionMessage = "=> marked Pending"; - - Spec.isPendingSpecException = function(e) { - return e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1; - }; - - return Spec; -}; - -if (typeof window == void 0 && typeof exports == "object") { - exports.Spec = jasmineRequire.Spec; -} - -getJasmineRequireObj().Env = function(j$) { - function Env(options) { - options = options || {}; - - var self = this; - var global = options.global || j$.getGlobal(); - - var totalSpecsDefined = 0; - - var catchExceptions = true; - - var realSetTimeout = j$.getGlobal().setTimeout; - var realClearTimeout = j$.getGlobal().clearTimeout; - this.clock = new j$.Clock(global, new j$.DelayedFunctionScheduler()); - - var runnableLookupTable = {}; - - var spies = []; - - var currentSpec = null; - var currentSuite = null; - - var reporter = new j$.ReportDispatcher([ - "jasmineStarted", - "jasmineDone", - "suiteStarted", - "suiteDone", - "specStarted", - "specDone" - ]); - - this.specFilter = function() { - return true; - }; - - var equalityTesters = []; - - var customEqualityTesters = []; - this.addCustomEqualityTester = function(tester) { - customEqualityTesters.push(tester); - }; - - j$.Expectation.addCoreMatchers(j$.matchers); - - var nextSpecId = 0; - var getNextSpecId = function() { - return 'spec' + nextSpecId++; - }; - - var nextSuiteId = 0; - var getNextSuiteId = function() { - return 'suite' + nextSuiteId++; - }; - - var expectationFactory = function(actual, spec) { - return j$.Expectation.Factory({ - util: j$.matchersUtil, - customEqualityTesters: customEqualityTesters, - actual: actual, - addExpectationResult: addExpectationResult - }); - - function addExpectationResult(passed, result) { - return spec.addExpectationResult(passed, result); - } - }; - - var specStarted = function(spec) { - currentSpec = spec; - reporter.specStarted(spec.result); - }; - - var beforeFns = function(suite) { - return function() { - var befores = []; - while(suite) { - befores = befores.concat(suite.beforeFns); - suite = suite.parentSuite; - } - return befores.reverse(); - }; - }; - - var afterFns = function(suite) { - return function() { - var afters = []; - while(suite) { - afters = afters.concat(suite.afterFns); - suite = suite.parentSuite; - } - return afters; - }; - }; - - var getSpecName = function(spec, suite) { - return suite.getFullName() + ' ' + spec.description; - }; - - // TODO: we may just be able to pass in the fn instead of wrapping here - var buildExpectationResult = j$.buildExpectationResult, - exceptionFormatter = new j$.ExceptionFormatter(), - expectationResultFactory = function(attrs) { - attrs.messageFormatter = exceptionFormatter.message; - attrs.stackFormatter = exceptionFormatter.stack; - - return buildExpectationResult(attrs); - }; - - // TODO: fix this naming, and here's where the value comes in - this.catchExceptions = function(value) { - catchExceptions = !!value; - return catchExceptions; - }; - - this.catchingExceptions = function() { - return catchExceptions; - }; - - var maximumSpecCallbackDepth = 20; - var currentSpecCallbackDepth = 0; - - function clearStack(fn) { - currentSpecCallbackDepth++; - if (currentSpecCallbackDepth >= maximumSpecCallbackDepth) { - currentSpecCallbackDepth = 0; - realSetTimeout(fn, 0); - } else { - fn(); - } - } - - var catchException = function(e) { - return j$.Spec.isPendingSpecException(e) || catchExceptions; - }; - - var queueRunnerFactory = function(options) { - options.catchException = catchException; - options.clearStack = options.clearStack || clearStack; - - new j$.QueueRunner(options).execute(); - }; - - var topSuite = new j$.Suite({ - env: this, - id: getNextSuiteId(), - description: 'Jasmine__TopLevel__Suite', - queueRunner: queueRunnerFactory, - resultCallback: function() {} // TODO - hook this up - }); - runnableLookupTable[topSuite.id] = topSuite; - currentSuite = topSuite; - - this.topSuite = function() { - return topSuite; - }; - - this.execute = function(runnablesToRun) { - runnablesToRun = runnablesToRun || [topSuite.id]; - - var allFns = []; - for(var i = 0; i < runnablesToRun.length; i++) { - var runnable = runnableLookupTable[runnablesToRun[i]]; - allFns.push((function(runnable) { return function(done) { runnable.execute(done); }; })(runnable)); - } - - reporter.jasmineStarted({ - totalSpecsDefined: totalSpecsDefined - }); - - queueRunnerFactory({fns: allFns, onComplete: reporter.jasmineDone}); - }; - - this.addReporter = function(reporterToAdd) { - reporter.addReporter(reporterToAdd); - }; - - this.addMatchers = function(matchersToAdd) { - j$.Expectation.addMatchers(matchersToAdd); - }; - - this.spyOn = function(obj, methodName) { - if (j$.util.isUndefined(obj)) { - throw new Error("spyOn could not find an object to spy upon for " + methodName + "()"); - } - - if (j$.util.isUndefined(obj[methodName])) { - throw new Error(methodName + '() method does not exist'); - } - - if (obj[methodName] && j$.isSpy(obj[methodName])) { - //TODO?: should this return the current spy? Downside: may cause user confusion about spy state - throw new Error(methodName + ' has already been spied upon'); - } - - var spy = j$.createSpy(methodName, obj[methodName]); - - spies.push({ - spy: spy, - baseObj: obj, - methodName: methodName, - originalValue: obj[methodName] - }); - - obj[methodName] = spy; - - return spy; - }; - - var suiteFactory = function(description) { - var suite = new j$.Suite({ - env: self, - id: getNextSuiteId(), - description: description, - parentSuite: currentSuite, - queueRunner: queueRunnerFactory, - onStart: suiteStarted, - resultCallback: function(attrs) { - reporter.suiteDone(attrs); - } - }); - - runnableLookupTable[suite.id] = suite; - return suite; - }; - - this.describe = function(description, specDefinitions) { - var suite = suiteFactory(description); - - var parentSuite = currentSuite; - parentSuite.addChild(suite); - currentSuite = suite; - - var declarationError = null; - try { - specDefinitions.call(suite); - } catch (e) { - declarationError = e; - } - - if (declarationError) { - this.it("encountered a declaration exception", function() { - throw declarationError; - }); - } - - currentSuite = parentSuite; - - return suite; - }; - - this.xdescribe = function(description, specDefinitions) { - var suite = this.describe(description, specDefinitions); - suite.disable(); - return suite; - }; - - var specFactory = function(description, fn, suite) { - totalSpecsDefined++; - - var spec = new j$.Spec({ - id: getNextSpecId(), - beforeFns: beforeFns(suite), - afterFns: afterFns(suite), - expectationFactory: expectationFactory, - exceptionFormatter: exceptionFormatter, - resultCallback: specResultCallback, - getSpecName: function(spec) { - return getSpecName(spec, suite); - }, - onStart: specStarted, - description: description, - expectationResultFactory: expectationResultFactory, - queueRunnerFactory: queueRunnerFactory, - fn: fn, - timer: {setTimeout: realSetTimeout, clearTimeout: realClearTimeout} - }); - - runnableLookupTable[spec.id] = spec; - - if (!self.specFilter(spec)) { - spec.disable(); - } - - return spec; - - function removeAllSpies() { - for (var i = 0; i < spies.length; i++) { - var spyEntry = spies[i]; - spyEntry.baseObj[spyEntry.methodName] = spyEntry.originalValue; - } - spies = []; - } - - function specResultCallback(result) { - removeAllSpies(); - j$.Expectation.resetMatchers(); - customEqualityTesters = []; - currentSpec = null; - reporter.specDone(result); - } - }; - - var suiteStarted = function(suite) { - reporter.suiteStarted(suite.result); - }; - - this.it = function(description, fn) { - var spec = specFactory(description, fn, currentSuite); - currentSuite.addChild(spec); - return spec; - }; - - this.xit = function(description, fn) { - var spec = this.it(description, fn); - spec.pend(); - return spec; - }; - - this.expect = function(actual) { - return currentSpec.expect(actual); - }; - - this.beforeEach = function(beforeEachFunction) { - currentSuite.beforeEach(beforeEachFunction); - }; - - this.afterEach = function(afterEachFunction) { - currentSuite.afterEach(afterEachFunction); - }; - - this.pending = function() { - throw j$.Spec.pendingSpecExceptionMessage; - }; - } - - return Env; -}; - -getJasmineRequireObj().JsApiReporter = function() { - - var noopTimer = { - start: function(){}, - elapsed: function(){ return 0; } - }; - - function JsApiReporter(options) { - var timer = options.timer || noopTimer, - status = "loaded"; - - this.started = false; - this.finished = false; - - this.jasmineStarted = function() { - this.started = true; - status = 'started'; - timer.start(); - }; - - var executionTime; - - this.jasmineDone = function() { - this.finished = true; - executionTime = timer.elapsed(); - status = 'done'; - }; - - this.status = function() { - return status; - }; - - var suites = {}; - - this.suiteStarted = function(result) { - storeSuite(result); - }; - - this.suiteDone = function(result) { - storeSuite(result); - }; - - function storeSuite(result) { - suites[result.id] = result; - } - - this.suites = function() { - return suites; - }; - - var specs = []; - this.specStarted = function(result) { }; - - this.specDone = function(result) { - specs.push(result); - }; - - this.specResults = function(index, length) { - return specs.slice(index, index + length); - }; - - this.specs = function() { - return specs; - }; - - this.executionTime = function() { - return executionTime; - }; - - } - - return JsApiReporter; -}; - -getJasmineRequireObj().Any = function() { - - function Any(expectedObject) { - this.expectedObject = expectedObject; - } - - Any.prototype.jasmineMatches = function(other) { - if (this.expectedObject == String) { - return typeof other == 'string' || other instanceof String; - } - - if (this.expectedObject == Number) { - return typeof other == 'number' || other instanceof Number; - } - - if (this.expectedObject == Function) { - return typeof other == 'function' || other instanceof Function; - } - - if (this.expectedObject == Object) { - return typeof other == 'object'; - } - - if (this.expectedObject == Boolean) { - return typeof other == 'boolean'; - } - - return other instanceof this.expectedObject; - }; - - Any.prototype.jasmineToString = function() { - return ''; - }; - - return Any; -}; - -getJasmineRequireObj().CallTracker = function() { - - function CallTracker() { - var calls = []; - - this.track = function(context) { - calls.push(context); - }; - - this.any = function() { - return !!calls.length; - }; - - this.count = function() { - return calls.length; - }; - - this.argsFor = function(index) { - var call = calls[index]; - return call ? call.args : []; - }; - - this.all = function() { - return calls; - }; - - this.allArgs = function() { - var callArgs = []; - for(var i = 0; i < calls.length; i++){ - callArgs.push(calls[i].args); - } - - return callArgs; - }; - - this.first = function() { - return calls[0]; - }; - - this.mostRecent = function() { - return calls[calls.length - 1]; - }; - - this.reset = function() { - calls = []; - }; - } - - return CallTracker; -}; - -getJasmineRequireObj().Clock = function() { - function Clock(global, delayedFunctionScheduler) { - var self = this, - realTimingFunctions = { - setTimeout: global.setTimeout, - clearTimeout: global.clearTimeout, - setInterval: global.setInterval, - clearInterval: global.clearInterval - }, - fakeTimingFunctions = { - setTimeout: setTimeout, - clearTimeout: clearTimeout, - setInterval: setInterval, - clearInterval: clearInterval - }, - installed = false, - timer; - - self.install = function() { - replace(global, fakeTimingFunctions); - timer = fakeTimingFunctions; - installed = true; - }; - - self.uninstall = function() { - delayedFunctionScheduler.reset(); - replace(global, realTimingFunctions); - timer = realTimingFunctions; - installed = false; - }; - - self.setTimeout = function(fn, delay, params) { - if (legacyIE()) { - if (arguments.length > 2) { - throw new Error("IE < 9 cannot support extra params to setTimeout without a polyfill"); - } - return timer.setTimeout(fn, delay); - } - return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]); - }; - - self.setInterval = function(fn, delay, params) { - if (legacyIE()) { - if (arguments.length > 2) { - throw new Error("IE < 9 cannot support extra params to setInterval without a polyfill"); - } - return timer.setInterval(fn, delay); - } - return Function.prototype.apply.apply(timer.setInterval, [global, arguments]); - }; - - self.clearTimeout = function(id) { - return Function.prototype.call.apply(timer.clearTimeout, [global, id]); - }; - - self.clearInterval = function(id) { - return Function.prototype.call.apply(timer.clearInterval, [global, id]); - }; - - self.tick = function(millis) { - if (installed) { - delayedFunctionScheduler.tick(millis); - } else { - throw new Error("Mock clock is not installed, use jasmine.clock().install()"); - } - }; - - return self; - - function legacyIE() { - //if these methods are polyfilled, apply will be present - return !(realTimingFunctions.setTimeout || realTimingFunctions.setInterval).apply; - } - - function replace(dest, source) { - for (var prop in source) { - dest[prop] = source[prop]; - } - } - - function setTimeout(fn, delay) { - return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2)); - } - - function clearTimeout(id) { - return delayedFunctionScheduler.removeFunctionWithId(id); - } - - function setInterval(fn, interval) { - return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true); - } - - function clearInterval(id) { - return delayedFunctionScheduler.removeFunctionWithId(id); - } - - function argSlice(argsObj, n) { - return Array.prototype.slice.call(argsObj, 2); - } - } - - return Clock; -}; - -getJasmineRequireObj().DelayedFunctionScheduler = function() { - function DelayedFunctionScheduler() { - var self = this; - var scheduledLookup = []; - var scheduledFunctions = {}; - var currentTime = 0; - var delayedFnCount = 0; - - self.tick = function(millis) { - millis = millis || 0; - var endTime = currentTime + millis; - - runScheduledFunctions(endTime); - currentTime = endTime; - }; - - self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) { - var f; - if (typeof(funcToCall) === 'string') { - /* jshint evil: true */ - f = function() { return eval(funcToCall); }; - /* jshint evil: false */ - } else { - f = funcToCall; - } - - millis = millis || 0; - timeoutKey = timeoutKey || ++delayedFnCount; - runAtMillis = runAtMillis || (currentTime + millis); - - var funcToSchedule = { - runAtMillis: runAtMillis, - funcToCall: f, - recurring: recurring, - params: params, - timeoutKey: timeoutKey, - millis: millis - }; - - if (runAtMillis in scheduledFunctions) { - scheduledFunctions[runAtMillis].push(funcToSchedule); - } else { - scheduledFunctions[runAtMillis] = [funcToSchedule]; - scheduledLookup.push(runAtMillis); - scheduledLookup.sort(function (a, b) { - return a - b; - }); - } - - return timeoutKey; - }; - - self.removeFunctionWithId = function(timeoutKey) { - for (var runAtMillis in scheduledFunctions) { - var funcs = scheduledFunctions[runAtMillis]; - var i = indexOfFirstToPass(funcs, function (func) { - return func.timeoutKey === timeoutKey; - }); - - if (i > -1) { - if (funcs.length === 1) { - delete scheduledFunctions[runAtMillis]; - deleteFromLookup(runAtMillis); - } else { - funcs.splice(i, 1); - } - - // intervals get rescheduled when executed, so there's never more - // than a single scheduled function with a given timeoutKey - break; - } - } - }; - - self.reset = function() { - currentTime = 0; - scheduledLookup = []; - scheduledFunctions = {}; - delayedFnCount = 0; - }; - - return self; - - function indexOfFirstToPass(array, testFn) { - var index = -1; - - for (var i = 0; i < array.length; ++i) { - if (testFn(array[i])) { - index = i; - break; - } - } - - return index; - } - - function deleteFromLookup(key) { - var value = Number(key); - var i = indexOfFirstToPass(scheduledLookup, function (millis) { - return millis === value; - }); - - if (i > -1) { - scheduledLookup.splice(i, 1); - } - } - - function reschedule(scheduledFn) { - self.scheduleFunction(scheduledFn.funcToCall, - scheduledFn.millis, - scheduledFn.params, - true, - scheduledFn.timeoutKey, - scheduledFn.runAtMillis + scheduledFn.millis); - } - - function runScheduledFunctions(endTime) { - if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) { - return; - } - - do { - currentTime = scheduledLookup.shift(); - - var funcsToRun = scheduledFunctions[currentTime]; - delete scheduledFunctions[currentTime]; - - for (var i = 0; i < funcsToRun.length; ++i) { - var funcToRun = funcsToRun[i]; - funcToRun.funcToCall.apply(null, funcToRun.params || []); - - if (funcToRun.recurring) { - reschedule(funcToRun); - } - } - } while (scheduledLookup.length > 0 && - // checking first if we're out of time prevents setTimeout(0) - // scheduled in a funcToRun from forcing an extra iteration - currentTime !== endTime && - scheduledLookup[0] <= endTime); - } - } - - return DelayedFunctionScheduler; -}; - -getJasmineRequireObj().ExceptionFormatter = function() { - function ExceptionFormatter() { - this.message = function(error) { - var message = error.name + - ': ' + - error.message; - - if (error.fileName || error.sourceURL) { - message += " in " + (error.fileName || error.sourceURL); - } - - if (error.line || error.lineNumber) { - message += " (line " + (error.line || error.lineNumber) + ")"; - } - - return message; - }; - - this.stack = function(error) { - return error ? error.stack : null; - }; - } - - return ExceptionFormatter; -}; - -getJasmineRequireObj().Expectation = function() { - - var matchers = {}; - - function Expectation(options) { - this.util = options.util || { buildFailureMessage: function() {} }; - this.customEqualityTesters = options.customEqualityTesters || []; - this.actual = options.actual; - this.addExpectationResult = options.addExpectationResult || function(){}; - this.isNot = options.isNot; - - for (var matcherName in matchers) { - this[matcherName] = matchers[matcherName]; - } - } - - Expectation.prototype.wrapCompare = function(name, matcherFactory) { - return function() { - var args = Array.prototype.slice.call(arguments, 0), - expected = args.slice(0), - message = ""; - - args.unshift(this.actual); - - var matcher = matcherFactory(this.util, this.customEqualityTesters), - matcherCompare = matcher.compare; - - function defaultNegativeCompare() { - var result = matcher.compare.apply(null, args); - result.pass = !result.pass; - return result; - } - - if (this.isNot) { - matcherCompare = matcher.negativeCompare || defaultNegativeCompare; - } - - var result = matcherCompare.apply(null, args); - - if (!result.pass) { - if (!result.message) { - args.unshift(this.isNot); - args.unshift(name); - message = this.util.buildFailureMessage.apply(null, args); - } else { - message = result.message; - } - } - - if (expected.length == 1) { - expected = expected[0]; - } - - // TODO: how many of these params are needed? - this.addExpectationResult( - result.pass, - { - matcherName: name, - passed: result.pass, - message: message, - actual: this.actual, - expected: expected // TODO: this may need to be arrayified/sliced - } - ); - }; - }; - - Expectation.addCoreMatchers = function(matchers) { - var prototype = Expectation.prototype; - for (var matcherName in matchers) { - var matcher = matchers[matcherName]; - prototype[matcherName] = prototype.wrapCompare(matcherName, matcher); - } - }; - - Expectation.addMatchers = function(matchersToAdd) { - for (var name in matchersToAdd) { - var matcher = matchersToAdd[name]; - matchers[name] = Expectation.prototype.wrapCompare(name, matcher); - } - }; - - Expectation.resetMatchers = function() { - for (var name in matchers) { - delete matchers[name]; - } - }; - - Expectation.Factory = function(options) { - options = options || {}; - - var expect = new Expectation(options); - - // TODO: this would be nice as its own Object - NegativeExpectation - // TODO: copy instead of mutate options - options.isNot = true; - expect.not = new Expectation(options); - - return expect; - }; - - return Expectation; -}; - -//TODO: expectation result may make more sense as a presentation of an expectation. -getJasmineRequireObj().buildExpectationResult = function() { - function buildExpectationResult(options) { - var messageFormatter = options.messageFormatter || function() {}, - stackFormatter = options.stackFormatter || function() {}; - - return { - matcherName: options.matcherName, - expected: options.expected, - actual: options.actual, - message: message(), - stack: stack(), - passed: options.passed - }; - - function message() { - if (options.passed) { - return "Passed."; - } else if (options.message) { - return options.message; - } else if (options.error) { - return messageFormatter(options.error); - } - return ""; - } - - function stack() { - if (options.passed) { - return ""; - } - - var error = options.error; - if (!error) { - try { - throw new Error(message()); - } catch (e) { - error = e; - } - } - return stackFormatter(error); - } - } - - return buildExpectationResult; -}; - -getJasmineRequireObj().ObjectContaining = function(j$) { - - function ObjectContaining(sample) { - this.sample = sample; - } - - ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { - if (typeof(this.sample) !== "object") { throw new Error("You must provide an object to objectContaining, not '"+this.sample+"'."); } - - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - var hasKey = function(obj, keyName) { - return obj !== null && !j$.util.isUndefined(obj[keyName]); - }; - - for (var property in this.sample) { - if (!hasKey(other, property) && hasKey(this.sample, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - else if (!j$.matchersUtil.equals(this.sample[property], other[property])) { - mismatchValues.push("'" + property + "' was '" + (other[property] ? j$.util.htmlEscape(other[property].toString()) : other[property]) + "' in actual, but was '" + (this.sample[property] ? j$.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in expected."); - } - } - - return (mismatchKeys.length === 0 && mismatchValues.length === 0); - }; - - ObjectContaining.prototype.jasmineToString = function() { - return ""; - }; - - return ObjectContaining; -}; - -getJasmineRequireObj().pp = function(j$) { - - function PrettyPrinter() { - this.ppNestLevel_ = 0; - } - - PrettyPrinter.prototype.format = function(value) { - this.ppNestLevel_++; - try { - if (j$.util.isUndefined(value)) { - this.emitScalar('undefined'); - } else if (value === null) { - this.emitScalar('null'); - } else if (value === j$.getGlobal()) { - this.emitScalar(''); - } else if (value.jasmineToString) { - this.emitScalar(value.jasmineToString()); - } else if (typeof value === 'string') { - this.emitString(value); - } else if (j$.isSpy(value)) { - this.emitScalar("spy on " + value.and.identity()); - } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); - } else if (typeof value === 'function') { - this.emitScalar('Function'); - } else if (typeof value.nodeType === 'number') { - this.emitScalar('HTMLNode'); - } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); - } else if (value.__Jasmine_been_here_before__) { - this.emitScalar(''); - } else if (j$.isArray_(value) || j$.isA_('Object', value)) { - value.__Jasmine_been_here_before__ = true; - if (j$.isArray_(value)) { - this.emitArray(value); - } else { - this.emitObject(value); - } - delete value.__Jasmine_been_here_before__; - } else { - this.emitScalar(value.toString()); - } - } finally { - this.ppNestLevel_--; - } - }; - - PrettyPrinter.prototype.iterateObject = function(obj, fn) { - for (var property in obj) { - if (!obj.hasOwnProperty(property)) { continue; } - if (property == '__Jasmine_been_here_before__') { continue; } - fn(property, obj.__lookupGetter__ ? (!j$.util.isUndefined(obj.__lookupGetter__(property)) && - obj.__lookupGetter__(property) !== null) : false); - } - }; - - PrettyPrinter.prototype.emitArray = j$.unimplementedMethod_; - PrettyPrinter.prototype.emitObject = j$.unimplementedMethod_; - PrettyPrinter.prototype.emitScalar = j$.unimplementedMethod_; - PrettyPrinter.prototype.emitString = j$.unimplementedMethod_; - - function StringPrettyPrinter() { - PrettyPrinter.call(this); - - this.string = ''; - } - - j$.util.inherit(StringPrettyPrinter, PrettyPrinter); - - StringPrettyPrinter.prototype.emitScalar = function(value) { - this.append(value); - }; - - StringPrettyPrinter.prototype.emitString = function(value) { - this.append("'" + value + "'"); - }; - - StringPrettyPrinter.prototype.emitArray = function(array) { - if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { - this.append("Array"); - return; - } - - this.append('[ '); - for (var i = 0; i < array.length; i++) { - if (i > 0) { - this.append(', '); - } - this.format(array[i]); - } - this.append(' ]'); - }; - - StringPrettyPrinter.prototype.emitObject = function(obj) { - if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { - this.append("Object"); - return; - } - - var self = this; - this.append('{ '); - var first = true; - - this.iterateObject(obj, function(property, isGetter) { - if (first) { - first = false; - } else { - self.append(', '); - } - - self.append(property); - self.append(' : '); - if (isGetter) { - self.append(''); - } else { - self.format(obj[property]); - } - }); - - this.append(' }'); - }; - - StringPrettyPrinter.prototype.append = function(value) { - this.string += value; - }; - - return function(value) { - var stringPrettyPrinter = new StringPrettyPrinter(); - stringPrettyPrinter.format(value); - return stringPrettyPrinter.string; - }; -}; - -getJasmineRequireObj().QueueRunner = function() { - - function QueueRunner(attrs) { - this.fns = attrs.fns || []; - this.onComplete = attrs.onComplete || function() {}; - this.clearStack = attrs.clearStack || function(fn) {fn();}; - this.onException = attrs.onException || function() {}; - this.catchException = attrs.catchException || function() { return true; }; - this.userContext = {}; - } - - QueueRunner.prototype.execute = function() { - this.run(this.fns, 0); - }; - - QueueRunner.prototype.run = function(fns, recursiveIndex) { - var length = fns.length, - self = this, - iterativeIndex; - - for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) { - var fn = fns[iterativeIndex]; - if (fn.length > 0) { - return attemptAsync(fn); - } else { - attemptSync(fn); - } - } - - var runnerDone = iterativeIndex >= length; - - if (runnerDone) { - this.clearStack(this.onComplete); - } - - function attemptSync(fn) { - try { - fn.call(self.userContext); - } catch (e) { - handleException(e); - } - } - - function attemptAsync(fn) { - var next = function () { self.run(fns, iterativeIndex + 1); }; - - try { - fn.call(self.userContext, next); - } catch (e) { - handleException(e); - next(); - } - } - - function handleException(e) { - self.onException(e); - if (!self.catchException(e)) { - //TODO: set a var when we catch an exception and - //use a finally block to close the loop in a nice way.. - throw e; - } - } - }; - - return QueueRunner; -}; - -getJasmineRequireObj().ReportDispatcher = function() { - function ReportDispatcher(methods) { - - var dispatchedMethods = methods || []; - - for (var i = 0; i < dispatchedMethods.length; i++) { - var method = dispatchedMethods[i]; - this[method] = (function(m) { - return function() { - dispatch(m, arguments); - }; - }(method)); - } - - var reporters = []; - - this.addReporter = function(reporter) { - reporters.push(reporter); - }; - - return this; - - function dispatch(method, args) { - for (var i = 0; i < reporters.length; i++) { - var reporter = reporters[i]; - if (reporter[method]) { - reporter[method].apply(reporter, args); - } - } - } - } - - return ReportDispatcher; -}; - - -getJasmineRequireObj().SpyStrategy = function() { - - function SpyStrategy(options) { - options = options || {}; - - var identity = options.name || "unknown", - originalFn = options.fn || function() {}, - getSpy = options.getSpy || function() {}, - plan = function() {}; - - this.identity = function() { - return identity; - }; - - this.exec = function() { - return plan.apply(this, arguments); - }; - - this.callThrough = function() { - plan = originalFn; - return getSpy(); - }; - - this.returnValue = function(value) { - plan = function() { - return value; - }; - return getSpy(); - }; - - this.throwError = function(something) { - var error = (something instanceof Error) ? something : new Error(something); - plan = function() { - throw error; - }; - return getSpy(); - }; - - this.callFake = function(fn) { - plan = fn; - return getSpy(); - }; - - this.stub = function(fn) { - plan = function() {}; - return getSpy(); - }; - } - - return SpyStrategy; -}; - -getJasmineRequireObj().Suite = function() { - function Suite(attrs) { - this.env = attrs.env; - this.id = attrs.id; - this.parentSuite = attrs.parentSuite; - this.description = attrs.description; - this.onStart = attrs.onStart || function() {}; - this.resultCallback = attrs.resultCallback || function() {}; - this.clearStack = attrs.clearStack || function(fn) {fn();}; - - this.beforeFns = []; - this.afterFns = []; - this.queueRunner = attrs.queueRunner || function() {}; - this.disabled = false; - - this.children = []; - - this.result = { - id: this.id, - status: this.disabled ? 'disabled' : '', - description: this.description, - fullName: this.getFullName() - }; - } - - Suite.prototype.getFullName = function() { - var fullName = this.description; - for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { - if (parentSuite.parentSuite) { - fullName = parentSuite.description + ' ' + fullName; - } - } - return fullName; - }; - - Suite.prototype.disable = function() { - this.disabled = true; - }; - - Suite.prototype.beforeEach = function(fn) { - this.beforeFns.unshift(fn); - }; - - Suite.prototype.afterEach = function(fn) { - this.afterFns.unshift(fn); - }; - - Suite.prototype.addChild = function(child) { - this.children.push(child); - }; - - Suite.prototype.execute = function(onComplete) { - var self = this; - if (this.disabled) { - complete(); - return; - } - - var allFns = []; - - for (var i = 0; i < this.children.length; i++) { - allFns.push(wrapChildAsAsync(this.children[i])); - } - - this.onStart(this); - - this.queueRunner({ - fns: allFns, - onComplete: complete - }); - - function complete() { - self.resultCallback(self.result); - - if (onComplete) { - onComplete(); - } - } - - function wrapChildAsAsync(child) { - return function(done) { child.execute(done); }; - } - }; - - return Suite; -}; - -if (typeof window == void 0 && typeof exports == "object") { - exports.Suite = jasmineRequire.Suite; -} - -getJasmineRequireObj().Timer = function() { - function Timer(options) { - options = options || {}; - - var now = options.now || function() { return new Date().getTime(); }, - startTime; - - this.start = function() { - startTime = now(); - }; - - this.elapsed = function() { - return now() - startTime; - }; - } - - return Timer; -}; - -getJasmineRequireObj().matchersUtil = function(j$) { - // TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter? - - return { - equals: function(a, b, customTesters) { - customTesters = customTesters || []; - - return eq(a, b, [], [], customTesters); - }, - - contains: function(haystack, needle, customTesters) { - customTesters = customTesters || []; - - if (Object.prototype.toString.apply(haystack) === "[object Array]") { - for (var i = 0; i < haystack.length; i++) { - if (eq(haystack[i], needle, [], [], customTesters)) { - return true; - } - } - return false; - } - return haystack.indexOf(needle) >= 0; - }, - - buildFailureMessage: function() { - var args = Array.prototype.slice.call(arguments, 0), - matcherName = args[0], - isNot = args[1], - actual = args[2], - expected = args.slice(3), - englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); - - var message = "Expected " + - j$.pp(actual) + - (isNot ? " not " : " ") + - englishyPredicate; - - if (expected.length > 0) { - for (var i = 0; i < expected.length; i++) { - if (i > 0) { - message += ","; - } - message += " " + j$.pp(expected[i]); - } - } - - return message + "."; - } - }; - - // Equality function lovingly adapted from isEqual in - // [Underscore](http://underscorejs.org) - function eq(a, b, aStack, bStack, customTesters) { - var result = true; - - for (var i = 0; i < customTesters.length; i++) { - var customTesterResult = customTesters[i](a, b); - if (!j$.util.isUndefined(customTesterResult)) { - return customTesterResult; - } - } - - if (a instanceof j$.Any) { - result = a.jasmineMatches(b); - if (result) { - return true; - } - } - - if (b instanceof j$.Any) { - result = b.jasmineMatches(a); - if (result) { - return true; - } - } - - if (b instanceof j$.ObjectContaining) { - result = b.jasmineMatches(a); - if (result) { - return true; - } - } - - if (a instanceof Error && b instanceof Error) { - return a.message == b.message; - } - - // Identical objects are equal. `0 === -0`, but they aren't identical. - // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). - if (a === b) { return a !== 0 || 1 / a == 1 / b; } - // A strict comparison is necessary because `null == undefined`. - if (a === null || b === null) { return a === b; } - var className = Object.prototype.toString.call(a); - if (className != Object.prototype.toString.call(b)) { return false; } - switch (className) { - // Strings, numbers, dates, and booleans are compared by value. - case '[object String]': - // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is - // equivalent to `new String("5")`. - return a == String(b); - case '[object Number]': - // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for - // other numeric values. - return a != +a ? b != +b : (a === 0 ? 1 / a == 1 / b : a == +b); - case '[object Date]': - case '[object Boolean]': - // Coerce dates and booleans to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are not equivalent. - return +a == +b; - // RegExps are compared by their source patterns and flags. - case '[object RegExp]': - return a.source == b.source && - a.global == b.global && - a.multiline == b.multiline && - a.ignoreCase == b.ignoreCase; - } - if (typeof a != 'object' || typeof b != 'object') { return false; } - // Assume equality for cyclic structures. The algorithm for detecting cyclic - // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - var length = aStack.length; - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - if (aStack[length] == a) { return bStack[length] == b; } - } - // Add the first object to the stack of traversed objects. - aStack.push(a); - bStack.push(b); - var size = 0; - // Recursively compare objects and arrays. - if (className == '[object Array]') { - // Compare array lengths to determine if a deep comparison is necessary. - size = a.length; - result = size == b.length; - if (result) { - // Deep compare the contents, ignoring non-numeric properties. - while (size--) { - if (!(result = eq(a[size], b[size], aStack, bStack, customTesters))) { break; } - } - } - } else { - // Objects with different constructors are not equivalent, but `Object`s - // from different frames are. - var aCtor = a.constructor, bCtor = b.constructor; - if (aCtor !== bCtor && !(isFunction(aCtor) && (aCtor instanceof aCtor) && - isFunction(bCtor) && (bCtor instanceof bCtor))) { - return false; - } - // Deep compare objects. - for (var key in a) { - if (has(a, key)) { - // Count the expected number of properties. - size++; - // Deep compare each member. - if (!(result = has(b, key) && eq(a[key], b[key], aStack, bStack, customTesters))) { break; } - } - } - // Ensure that both objects contain the same number of properties. - if (result) { - for (key in b) { - if (has(b, key) && !(size--)) { break; } - } - result = !size; - } - } - // Remove the first object from the stack of traversed objects. - aStack.pop(); - bStack.pop(); - - return result; - - function has(obj, key) { - return obj.hasOwnProperty(key); - } - - function isFunction(obj) { - return typeof obj === 'function'; - } - } -}; - -getJasmineRequireObj().toBe = function() { - function toBe() { - return { - compare: function(actual, expected) { - return { - pass: actual === expected - }; - } - }; - } - - return toBe; -}; - -getJasmineRequireObj().toBeCloseTo = function() { - - function toBeCloseTo() { - return { - compare: function(actual, expected, precision) { - if (precision !== 0) { - precision = precision || 2; - } - - return { - pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2) - }; - } - }; - } - - return toBeCloseTo; -}; - -getJasmineRequireObj().toBeDefined = function() { - function toBeDefined() { - return { - compare: function(actual) { - return { - pass: (void 0 !== actual) - }; - } - }; - } - - return toBeDefined; -}; - -getJasmineRequireObj().toBeFalsy = function() { - function toBeFalsy() { - return { - compare: function(actual) { - return { - pass: !!!actual - }; - } - }; - } - - return toBeFalsy; -}; - -getJasmineRequireObj().toBeGreaterThan = function() { - - function toBeGreaterThan() { - return { - compare: function(actual, expected) { - return { - pass: actual > expected - }; - } - }; - } - - return toBeGreaterThan; -}; - - -getJasmineRequireObj().toBeLessThan = function() { - function toBeLessThan() { - return { - - compare: function(actual, expected) { - return { - pass: actual < expected - }; - } - }; - } - - return toBeLessThan; -}; -getJasmineRequireObj().toBeNaN = function(j$) { - - function toBeNaN() { - return { - compare: function(actual) { - var result = { - pass: (actual !== actual) - }; - - if (result.pass) { - result.message = "Expected actual not to be NaN."; - } else { - result.message = "Expected " + j$.pp(actual) + " to be NaN."; - } - - return result; - } - }; - } - - return toBeNaN; -}; - -getJasmineRequireObj().toBeNull = function() { - - function toBeNull() { - return { - compare: function(actual) { - return { - pass: actual === null - }; - } - }; - } - - return toBeNull; -}; - -getJasmineRequireObj().toBeTruthy = function() { - - function toBeTruthy() { - return { - compare: function(actual) { - return { - pass: !!actual - }; - } - }; - } - - return toBeTruthy; -}; - -getJasmineRequireObj().toBeUndefined = function() { - - function toBeUndefined() { - return { - compare: function(actual) { - return { - pass: void 0 === actual - }; - } - }; - } - - return toBeUndefined; -}; - -getJasmineRequireObj().toContain = function() { - function toContain(util, customEqualityTesters) { - customEqualityTesters = customEqualityTesters || []; - - return { - compare: function(actual, expected) { - - return { - pass: util.contains(actual, expected, customEqualityTesters) - }; - } - }; - } - - return toContain; -}; - -getJasmineRequireObj().toEqual = function() { - - function toEqual(util, customEqualityTesters) { - customEqualityTesters = customEqualityTesters || []; - - return { - compare: function(actual, expected) { - var result = { - pass: false - }; - - result.pass = util.equals(actual, expected, customEqualityTesters); - - return result; - } - }; - } - - return toEqual; -}; - -getJasmineRequireObj().toHaveBeenCalled = function(j$) { - - function toHaveBeenCalled() { - return { - compare: function(actual) { - var result = {}; - - if (!j$.isSpy(actual)) { - throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.'); - } - - if (arguments.length > 1) { - throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); - } - - result.pass = actual.calls.any(); - - result.message = result.pass ? - "Expected spy " + actual.and.identity() + " not to have been called." : - "Expected spy " + actual.and.identity() + " to have been called."; - - return result; - } - }; - } - - return toHaveBeenCalled; -}; - -getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { - - function toHaveBeenCalledWith(util) { - return { - compare: function() { - var args = Array.prototype.slice.call(arguments, 0), - actual = args[0], - expectedArgs = args.slice(1), - result = { pass: false }; - - if (!j$.isSpy(actual)) { - throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.'); - } - - if (!actual.calls.any()) { - result.message = "Expected spy " + actual.and.identity() + " to have been called with " + j$.pp(expectedArgs) + " but it was never called."; - return result; - } - - if (util.contains(actual.calls.allArgs(), expectedArgs)) { - result.pass = true; - result.message = "Expected spy " + actual.and.identity() + " not to have been called with " + j$.pp(expectedArgs) + " but it was."; - } else { - result.message = "Expected spy " + actual.and.identity() + " to have been called with " + j$.pp(expectedArgs) + " but actual calls were " + j$.pp(actual.calls.allArgs()).replace(/^\[ | \]$/g, '') + "."; - } - - return result; - } - }; - } - - return toHaveBeenCalledWith; -}; - -getJasmineRequireObj().toMatch = function() { - - function toMatch() { - return { - compare: function(actual, expected) { - var regexp = new RegExp(expected); - - return { - pass: regexp.test(actual) - }; - } - }; - } - - return toMatch; -}; - -getJasmineRequireObj().toThrow = function(j$) { - - function toThrow(util) { - return { - compare: function(actual, expected) { - var result = { pass: false }, - threw = false, - thrown; - - if (typeof actual != "function") { - throw new Error("Actual is not a Function"); - } - - try { - actual(); - } catch (e) { - threw = true; - thrown = e; - } - - if (!threw) { - result.message = "Expected function to throw an exception."; - return result; - } - - if (arguments.length == 1) { - result.pass = true; - result.message = "Expected function not to throw, but it threw " + j$.pp(thrown) + "."; - - return result; - } - - if (util.equals(thrown, expected)) { - result.pass = true; - result.message = "Expected function not to throw " + j$.pp(expected) + "."; - } else { - result.message = "Expected function to throw " + j$.pp(expected) + ", but it threw " + j$.pp(thrown) + "."; - } - - return result; - } - }; - } - - return toThrow; -}; - -getJasmineRequireObj().toThrowError = function(j$) { - function toThrowError (util) { - return { - compare: function(actual) { - var threw = false, - thrown, - errorType, - message, - regexp, - name, - constructorName; - - if (typeof actual != "function") { - throw new Error("Actual is not a Function"); - } - - extractExpectedParams.apply(null, arguments); - - try { - actual(); - } catch (e) { - threw = true; - thrown = e; - } - - if (!threw) { - return fail("Expected function to throw an Error."); - } - - if (!(thrown instanceof Error)) { - return fail("Expected function to throw an Error, but it threw " + thrown + "."); - } - - if (arguments.length == 1) { - return pass("Expected function not to throw an Error, but it threw " + fnNameFor(thrown) + "."); - } - - if (errorType) { - name = fnNameFor(errorType); - constructorName = fnNameFor(thrown.constructor); - } - - if (errorType && message) { - if (thrown.constructor == errorType && util.equals(thrown.message, message)) { - return pass("Expected function not to throw " + name + " with message \"" + message + "\"."); - } else { - return fail("Expected function to throw " + name + " with message \"" + message + - "\", but it threw " + constructorName + " with message \"" + thrown.message + "\"."); - } - } - - if (errorType && regexp) { - if (thrown.constructor == errorType && regexp.test(thrown.message)) { - return pass("Expected function not to throw " + name + " with message matching " + regexp + "."); - } else { - return fail("Expected function to throw " + name + " with message matching " + regexp + - ", but it threw " + constructorName + " with message \"" + thrown.message + "\"."); - } - } - - if (errorType) { - if (thrown.constructor == errorType) { - return pass("Expected function not to throw " + name + "."); - } else { - return fail("Expected function to throw " + name + ", but it threw " + constructorName + "."); - } - } - - if (message) { - if (thrown.message == message) { - return pass("Expected function not to throw an exception with message " + j$.pp(message) + "."); - } else { - return fail("Expected function to throw an exception with message " + j$.pp(message) + - ", but it threw an exception with message " + j$.pp(thrown.message) + "."); - } - } - - if (regexp) { - if (regexp.test(thrown.message)) { - return pass("Expected function not to throw an exception with a message matching " + j$.pp(regexp) + "."); - } else { - return fail("Expected function to throw an exception with a message matching " + j$.pp(regexp) + - ", but it threw an exception with message " + j$.pp(thrown.message) + "."); - } - } - - function fnNameFor(func) { - return func.name || func.toString().match(/^\s*function\s*(\w*)\s*\(/)[1]; - } - - function pass(notMessage) { - return { - pass: true, - message: notMessage - }; - } - - function fail(message) { - return { - pass: false, - message: message - }; - } - - function extractExpectedParams() { - if (arguments.length == 1) { - return; - } - - if (arguments.length == 2) { - var expected = arguments[1]; - - if (expected instanceof RegExp) { - regexp = expected; - } else if (typeof expected == "string") { - message = expected; - } else if (checkForAnErrorType(expected)) { - errorType = expected; - } - - if (!(errorType || message || regexp)) { - throw new Error("Expected is not an Error, string, or RegExp."); - } - } else { - if (checkForAnErrorType(arguments[1])) { - errorType = arguments[1]; - } else { - throw new Error("Expected error type is not an Error."); - } - - if (arguments[2] instanceof RegExp) { - regexp = arguments[2]; - } else if (typeof arguments[2] == "string") { - message = arguments[2]; - } else { - throw new Error("Expected error message is not a string or RegExp."); - } - } - } - - function checkForAnErrorType(type) { - if (typeof type !== "function") { - return false; - } - - var Surrogate = function() {}; - Surrogate.prototype = type.prototype; - return (new Surrogate()) instanceof Error; - } - } - }; - } - - return toThrowError; -}; - -getJasmineRequireObj().version = function() { - return "2.0.0"; -}; diff --git a/jasmine-tests/lib/jasmine-2.0.0/jasmine_favicon.png b/jasmine-tests/lib/jasmine-2.0.0/jasmine_favicon.png deleted file mode 100755 index 3562e27..0000000 Binary files a/jasmine-tests/lib/jasmine-2.0.0/jasmine_favicon.png and /dev/null differ diff --git a/jasmine-tests/spec/canvas2svgspec.js b/jasmine-tests/spec/canvas2svgspec.js deleted file mode 100755 index 4761c81..0000000 --- a/jasmine-tests/spec/canvas2svgspec.js +++ /dev/null @@ -1,343 +0,0 @@ -describe("canvas2svg", function() { - - describe("can by created", function() { - - it("with options", function() { - var ctx = new C2S({width:100, height:200, enableMirroring:true}); - expect(ctx instanceof C2S).toBe(true); - expect(ctx.width).toEqual(100); - expect(ctx.height).toEqual(200); - expect(ctx.enableMirroring).toEqual(true); - - var ctx2 = new C2S(300,400); - expect(ctx2 instanceof C2S).toBe(true); - expect(ctx2.width).toEqual(300); - expect(ctx2.height).toEqual(400); - expect(ctx2.enableMirroring).toEqual(false); - }); - - it("with no options and have defaults", function() { - var ctx = new C2S(); - expect(ctx instanceof C2S).toBe(true); - expect(ctx.width).toEqual(500); - expect(ctx.height).toEqual(500); - expect(ctx.enableMirroring).toEqual(false); - }); - - it("even if it's called as a function", function() { - //notice the lack of new! - var ctx = C2S({width:100, height:200, enableMirroring:true}); - expect(ctx instanceof C2S).toBe(true); - expect(ctx.width).toEqual(100); - expect(ctx.height).toEqual(200); - expect(ctx.enableMirroring).toEqual(true); - - var ctx2 = C2S(300,400); - expect(ctx2 instanceof C2S).toBe(true); - expect(ctx2.width).toEqual(300); - expect(ctx2.height).toEqual(400); - expect(ctx2.enableMirroring).toEqual(false); - - var ctx3 = C2S(); - expect(ctx3 instanceof C2S).toBe(true); - expect(ctx3.width).toEqual(500); - expect(ctx3.height).toEqual(500); - expect(ctx3.enableMirroring).toEqual(false); - - }); - - - }); - - describe("has implemented methods", function() { - var ctx, - methods = - [ - "save", - "restore", - "scale", - "rotate", - "translate", - "transform", - "beginPath", - "moveTo", - "closePath", - "lineTo", - "bezierCurveTo", - "quadraticCurveTo", - "stroke", - "fill", - "rect", - "fillRect", - "strokeRect", - "clearRect", - "createLinearGradient", - "createRadialGradient", - "fillText", - "strokeText", - "measureText", - "arc", - "clip", - "drawImage", - "createPattern" - ]; - - beforeEach(function() { - ctx = new C2S(); - }); - - //TODO: better tests for each method - for(var i=0; i'); - - }); - }); - - describe("with multiple transforms and fill/strokes", function() { - - it("creates new groups", function() { - var ctx = new C2S(); - ctx.translate(0, 20); - ctx.fillRect(0, 0, 10, 10); - - ctx.translate(10, 20); - ctx.fillRect(0, 0, 10, 10); - - ctx.translate(20, 20); - ctx.fillRect(0, 0, 10, 10); - - var svg = ctx.getSvg(); - var firstGroup = svg.querySelector("g"); - expect(firstGroup.getAttribute("transform")).toEqual("translate(0,20)"); - var secondGroup = firstGroup.querySelector("g"); - expect(secondGroup.getAttribute("transform")).toEqual("translate(10,20)"); - var thirdGroup = secondGroup.querySelector("g"); - expect(thirdGroup.getAttribute("transform")).toEqual("translate(20,20)"); - - }); - - it("save and restore still works", function() { - var ctx = new C2S(); - - ctx.translate(0, 10); - ctx.fillRect(0, 0, 10, 10); - - ctx.save(); - ctx.translate(40, 40); - ctx.fillRect(0, 0, 10, 10); - - ctx.restore(); - - ctx.translate(0, 10); - ctx.fillRect(0, 0, 10, 10); - - var svg = ctx.getSvg(); - var firstGroup = svg.querySelector("g"); - expect(firstGroup.getAttribute("transform")).toEqual("translate(0,10)"); - var secondGroup = firstGroup.childNodes[1]; - expect(secondGroup.getAttribute("transform")).toEqual("translate(40,40)"); - var thirdGroup = firstGroup.childNodes[2]; - expect(thirdGroup.getAttribute("transform")).toEqual("translate(0,10)"); - - }); - }); - - describe("it will generate ids", function() { - - it("that start with a letter", function() { - var ctx = new C2S(); - ctx.createRadialGradient(6E1, 6E1, 0.0, 6E1, 6E1, 5E1); - var svg = ctx.getSvg(); - var id = svg.children[0].children[0].id; - var test = /^[A-Za-z]/.test(id); - expect(test).toEqual(true); - }); - }); - - describe("will split up rgba", function() { - //while browsers support rgba values for fill/stroke, this is not accepted in visio/illustrator - it("to fill and fill-opacity", function() { - var ctx = new C2S(); - ctx.fillStyle="rgba(20,40,50,0.5)"; - ctx.fillRect(100,100,100,100); - var svg = ctx.getSvg(); - expect(svg.querySelector("rect").getAttribute("fill")).toBe("rgb(20,40,50)"); - expect(svg.querySelector("rect").getAttribute("fill-opacity")).toBe("0.5"); - }); - - it("to stroke and stroke-opacity", function() { - var ctx = new C2S(); - ctx.strokeStyle="rgba(10,20,30,0.4)"; - ctx.strokeRect(100,100,100,100); - var svg = ctx.getSvg(); - expect(svg.querySelector("rect").getAttribute("stroke")).toBe("rgb(10,20,30)"); - expect(svg.querySelector("rect").getAttribute("stroke-opacity")).toBe("0.4"); - }); - }); - - describe("supports path commands", function() { - - it("and moveTo may be called without beginPath, but is not recommended", function() { - var ctx = new C2S(); - ctx.moveTo(0,0); - ctx.lineTo(100,100); - ctx.stroke(); - }); - }); - - describe("supports text align", function() { - - it("not specifying a value defaults to 'start'", function() { - - var ctx = new C2S(); - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("text-anchor")).toBe("start"); - - }); - - it("assuming ltr, left maps to 'start'", function() { - - var ctx = new C2S(); - ctx.textAlign = "left"; - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("text-anchor")).toBe("start"); - - }); - - it("assuming ltr, right maps to 'end'", function() { - - var ctx = new C2S(); - ctx.textAlign = "right"; - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("text-anchor")).toBe("end"); - - }); - - it("center maps to 'middle'", function() { - - var ctx = new C2S(); - ctx.textAlign = "center"; - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("text-anchor")).toBe("middle"); - - }); - - it("stores the proper values on save and restore", function() { - var ctx = new C2S(); - ctx.textAlign = "center"; - expect(ctx.textAlign).toBe("center"); - ctx.save(); - expect(ctx.textAlign).toBe("center"); - ctx.textAlign = "right"; - expect(ctx.textAlign).toBe("right"); - ctx.restore(); - expect(ctx.textAlign).toBe("center"); - }); - - }); - - describe("supports text baseline", function() { - - it("not specifying a value defaults to alphabetic", function() { - var ctx = new C2S(); - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("alphabetic"); - }); - - it("not specifying a valid value defaults to alphabetic", function() { - var ctx = new C2S(); - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.textBaseline = "werwerwer"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("alphabetic"); - }); - - it("hanging maps to hanging ", function() { - var ctx = new C2S(); - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.textBaseline = "hanging"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("hanging"); - }); - - it("top maps to text-before-edge ", function() { - var ctx = new C2S(); - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.textBaseline = "top"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("text-before-edge"); - }); - - it("bottom maps to text-after-edge ", function() { - var ctx = new C2S(); - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.textBaseline = "bottom"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("text-after-edge"); - }); - - it("middle maps to central ", function() { - var ctx = new C2S(); - ctx.font = "normal 36px Times"; - ctx.fillStyle = "#000000"; - ctx.textBaseline = "middle"; - ctx.fillText("A Text Example", 0, 50); - var svg = ctx.getSvg(); - expect(svg.querySelector("text").getAttribute("dominant-baseline")).toBe("central"); - }); - - }); - -}); diff --git a/karma.conf.js b/karma.conf.js new file mode 100644 index 0000000..6027e59 --- /dev/null +++ b/karma.conf.js @@ -0,0 +1,32 @@ +module.exports = function(config) { + config.set({ + basePath: '', + frameworks: ['mocha', 'chai'], + plugins: [ + 'karma-mocha', + 'karma-chai', + 'karma-mocha-reporter', + 'karma-chrome-launcher', + 'karma-firefox-launcher' + ], + client: { + }, + files: [ + 'node_modules/resemblejs/resemble.js', + 'canvas2svg.js', + 'test/globals.js', + 'test/example/*.js', + 'test/unit.spec.js', + 'test/example.spec.js' + ], + preprocessors: { + }, + reporters: ['mocha'], + port: 9876, + colors: true, + logLevel: config.LOG_DISABLE, + autoWatch: false, + browsers: ['Firefox', 'Chrome'], + singleRun: true + }); +}; \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..b95475d --- /dev/null +++ b/package.json @@ -0,0 +1,35 @@ +{ + "name": "canvas2svg", + "version": "1.0.19", + "description": "canvas2svg", + "main": "canvas2svg.js", + "homepage": "http://gliffy.github.io/canvas2svg/", + "directories": { + "test": "test" + }, + "scripts": { + "test": "./node_modules/.bin/karma start --browsers Firefox --single-run" + }, + "keywords": [ + "canvas", + "svg", + "canvas2svg" + ], + "author": "Kerry Liu", + "license": "MIT", + "dependencies": {}, + "devDependencies": { + "chai": "^2.1.1", + "cheerio": "^0.19.0", + "gulp": "^3.9.0", + "gulp-bump": "^0.3.1", + "karma": "^0.12.36", + "karma-chai": "^0.1.0", + "karma-chrome-launcher": "^0.1.12", + "karma-firefox-launcher": "^0.1.6", + "karma-mocha": "^0.1.10", + "karma-mocha-reporter": "^1.0.2", + "mocha": "^2.2.5", + "resemblejs": "^1.2.1" + } +} diff --git a/test/css/normalize.css b/test/css/normalize.css new file mode 100644 index 0000000..81c6f31 --- /dev/null +++ b/test/css/normalize.css @@ -0,0 +1,427 @@ +/*! normalize.css v3.0.2 | MIT License | git.io/normalize */ + +/** + * 1. Set default font family to sans-serif. + * 2. Prevent iOS text size adjust after orientation change, without disabling + * user zoom. + */ + +html { + font-family: sans-serif; /* 1 */ + -ms-text-size-adjust: 100%; /* 2 */ + -webkit-text-size-adjust: 100%; /* 2 */ +} + +/** + * Remove default margin. + */ + +body { + margin: 0; +} + +/* HTML5 display definitions + ========================================================================== */ + +/** + * Correct `block` display not defined for any HTML5 element in IE 8/9. + * Correct `block` display not defined for `details` or `summary` in IE 10/11 + * and Firefox. + * Correct `block` display not defined for `main` in IE 11. + */ + +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +main, +menu, +nav, +section, +summary { + display: block; +} + +/** + * 1. Correct `inline-block` display not defined in IE 8/9. + * 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera. + */ + +audio, +canvas, +progress, +video { + display: inline-block; /* 1 */ + vertical-align: baseline; /* 2 */ +} + +/** + * Prevent modern browsers from displaying `audio` without controls. + * Remove excess height in iOS 5 devices. + */ + +audio:not([controls]) { + display: none; + height: 0; +} + +/** + * Address `[hidden]` styling not present in IE 8/9/10. + * Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22. + */ + +[hidden], +template { + display: none; +} + +/* Links + ========================================================================== */ + +/** + * Remove the gray background color from active links in IE 10. + */ + +a { + background-color: transparent; +} + +/** + * Improve readability when focused and also mouse hovered in all browsers. + */ + +a:active, +a:hover { + outline: 0; +} + +/* Text-level semantics + ========================================================================== */ + +/** + * Address styling not present in IE 8/9/10/11, Safari, and Chrome. + */ + +abbr[title] { + border-bottom: 1px dotted; +} + +/** + * Address style set to `bolder` in Firefox 4+, Safari, and Chrome. + */ + +b, +strong { + font-weight: bold; +} + +/** + * Address styling not present in Safari and Chrome. + */ + +dfn { + font-style: italic; +} + +/** + * Address variable `h1` font-size and margin within `section` and `article` + * contexts in Firefox 4+, Safari, and Chrome. + */ + +h1 { + font-size: 2em; + margin: 0.67em 0; +} + +/** + * Address styling not present in IE 8/9. + */ + +mark { + background: #ff0; + color: #000; +} + +/** + * Address inconsistent and variable font size in all browsers. + */ + +small { + font-size: 80%; +} + +/** + * Prevent `sub` and `sup` affecting `line-height` in all browsers. + */ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sup { + top: -0.5em; +} + +sub { + bottom: -0.25em; +} + +/* Embedded content + ========================================================================== */ + +/** + * Remove border when inside `a` element in IE 8/9/10. + */ + +img { + border: 0; +} + +/** + * Correct overflow not hidden in IE 9/10/11. + */ + +svg:not(:root) { + overflow: hidden; +} + +/* Grouping content + ========================================================================== */ + +/** + * Address margin not present in IE 8/9 and Safari. + */ + +figure { + margin: 1em 40px; +} + +/** + * Address differences between Firefox and other browsers. + */ + +hr { + -moz-box-sizing: content-box; + box-sizing: content-box; + height: 0; +} + +/** + * Contain overflow in all browsers. + */ + +pre { + overflow: auto; +} + +/** + * Address odd `em`-unit font size rendering in all browsers. + */ + +code, +kbd, +pre, +samp { + font-family: monospace, monospace; + font-size: 1em; +} + +/* Forms + ========================================================================== */ + +/** + * Known limitation: by default, Chrome and Safari on OS X allow very limited + * styling of `select`, unless a `border` property is set. + */ + +/** + * 1. Correct color not being inherited. + * Known issue: affects color of disabled elements. + * 2. Correct font properties not being inherited. + * 3. Address margins set differently in Firefox 4+, Safari, and Chrome. + */ + +button, +input, +optgroup, +select, +textarea { + color: inherit; /* 1 */ + font: inherit; /* 2 */ + margin: 0; /* 3 */ +} + +/** + * Address `overflow` set to `hidden` in IE 8/9/10/11. + */ + +button { + overflow: visible; +} + +/** + * Address inconsistent `text-transform` inheritance for `button` and `select`. + * All other form control elements do not inherit `text-transform` values. + * Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera. + * Correct `select` style inheritance in Firefox. + */ + +button, +select { + text-transform: none; +} + +/** + * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` + * and `video` controls. + * 2. Correct inability to style clickable `input` types in iOS. + * 3. Improve usability and consistency of cursor style between image-type + * `input` and others. + */ + +button, +html input[type="button"], /* 1 */ +input[type="reset"], +input[type="submit"] { + -webkit-appearance: button; /* 2 */ + cursor: pointer; /* 3 */ +} + +/** + * Re-set default cursor for disabled elements. + */ + +button[disabled], +html input[disabled] { + cursor: default; +} + +/** + * Remove inner padding and border in Firefox 4+. + */ + +button::-moz-focus-inner, +input::-moz-focus-inner { + border: 0; + padding: 0; +} + +/** + * Address Firefox 4+ setting `line-height` on `input` using `!important` in + * the UA stylesheet. + */ + +input { + line-height: normal; +} + +/** + * It's recommended that you don't attempt to style these elements. + * Firefox's implementation doesn't respect box-sizing, padding, or width. + * + * 1. Address box sizing set to `content-box` in IE 8/9/10. + * 2. Remove excess padding in IE 8/9/10. + */ + +input[type="checkbox"], +input[type="radio"] { + box-sizing: border-box; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * Fix the cursor style for Chrome's increment/decrement buttons. For certain + * `font-size` values of the `input`, it causes the cursor style of the + * decrement button to change from `default` to `text`. + */ + +input[type="number"]::-webkit-inner-spin-button, +input[type="number"]::-webkit-outer-spin-button { + height: auto; +} + +/** + * 1. Address `appearance` set to `searchfield` in Safari and Chrome. + * 2. Address `box-sizing` set to `border-box` in Safari and Chrome + * (include `-moz` to future-proof). + */ + +input[type="search"] { + -webkit-appearance: textfield; /* 1 */ + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; /* 2 */ + box-sizing: content-box; +} + +/** + * Remove inner padding and search cancel button in Safari and Chrome on OS X. + * Safari (but not Chrome) clips the cancel button when the search input has + * padding (and `textfield` appearance). + */ + +input[type="search"]::-webkit-search-cancel-button, +input[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} + +/** + * Define consistent border, margin, and padding. + */ + +fieldset { + border: 1px solid #c0c0c0; + margin: 0 2px; + padding: 0.35em 0.625em 0.75em; +} + +/** + * 1. Correct `color` not being inherited in IE 8/9/10/11. + * 2. Remove padding so people aren't caught out if they zero out fieldsets. + */ + +legend { + border: 0; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * Remove default vertical scrollbar in IE 8/9/10/11. + */ + +textarea { + overflow: auto; +} + +/** + * Don't inherit the `font-weight` (applied by a rule above). + * NOTE: the default cannot safely be changed in Chrome and Safari on OS X. + */ + +optgroup { + font-weight: bold; +} + +/* Tables + ========================================================================== */ + +/** + * Remove most spacing between table cells. + */ + +table { + border-collapse: collapse; + border-spacing: 0; +} + +td, +th { + padding: 0; +} \ No newline at end of file diff --git a/test/css/playground.css b/test/css/playground.css new file mode 100644 index 0000000..baabe29 --- /dev/null +++ b/test/css/playground.css @@ -0,0 +1,15 @@ +#canvas, +#svg { + border: 1px solid #CCC; +} +#svg { + width: 460px; + height: 460px; + overflow: hidden; +} + +.container, +.try { + margin-top: 20px; +} + diff --git a/test/css/skeleton.css b/test/css/skeleton.css new file mode 100644 index 0000000..f28bf6c --- /dev/null +++ b/test/css/skeleton.css @@ -0,0 +1,418 @@ +/* +* Skeleton V2.0.4 +* Copyright 2014, Dave Gamache +* www.getskeleton.com +* Free to use under the MIT license. +* http://www.opensource.org/licenses/mit-license.php +* 12/29/2014 +*/ + + +/* Table of contents +–––––––––––––––––––––––––––––––––––––––––––––––––– +- Grid +- Base Styles +- Typography +- Links +- Buttons +- Forms +- Lists +- Code +- Tables +- Spacing +- Utilities +- Clearing +- Media Queries +*/ + + +/* Grid +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +.container { + position: relative; + width: 100%; + max-width: 960px; + margin: 0 auto; + padding: 0 20px; + box-sizing: border-box; } +.column, +.columns { + width: 100%; + float: left; + box-sizing: border-box; } + +/* For devices larger than 400px */ +@media (min-width: 400px) { + .container { + width: 85%; + padding: 0; } +} + +/* For devices larger than 550px */ +@media (min-width: 550px) { + .container { + width: 80%; } + .column, + .columns { + margin-left: 4%; } + .column:first-child, + .columns:first-child { + margin-left: 0; } + + .one.column, + .one.columns { width: 4.66666666667%; } + .two.columns { width: 13.3333333333%; } + .three.columns { width: 22%; } + .four.columns { width: 30.6666666667%; } + .five.columns { width: 39.3333333333%; } + .six.columns { width: 48%; } + .seven.columns { width: 56.6666666667%; } + .eight.columns { width: 65.3333333333%; } + .nine.columns { width: 74.0%; } + .ten.columns { width: 82.6666666667%; } + .eleven.columns { width: 91.3333333333%; } + .twelve.columns { width: 100%; margin-left: 0; } + + .one-third.column { width: 30.6666666667%; } + .two-thirds.column { width: 65.3333333333%; } + + .one-half.column { width: 48%; } + + /* Offsets */ + .offset-by-one.column, + .offset-by-one.columns { margin-left: 8.66666666667%; } + .offset-by-two.column, + .offset-by-two.columns { margin-left: 17.3333333333%; } + .offset-by-three.column, + .offset-by-three.columns { margin-left: 26%; } + .offset-by-four.column, + .offset-by-four.columns { margin-left: 34.6666666667%; } + .offset-by-five.column, + .offset-by-five.columns { margin-left: 43.3333333333%; } + .offset-by-six.column, + .offset-by-six.columns { margin-left: 52%; } + .offset-by-seven.column, + .offset-by-seven.columns { margin-left: 60.6666666667%; } + .offset-by-eight.column, + .offset-by-eight.columns { margin-left: 69.3333333333%; } + .offset-by-nine.column, + .offset-by-nine.columns { margin-left: 78.0%; } + .offset-by-ten.column, + .offset-by-ten.columns { margin-left: 86.6666666667%; } + .offset-by-eleven.column, + .offset-by-eleven.columns { margin-left: 95.3333333333%; } + + .offset-by-one-third.column, + .offset-by-one-third.columns { margin-left: 34.6666666667%; } + .offset-by-two-thirds.column, + .offset-by-two-thirds.columns { margin-left: 69.3333333333%; } + + .offset-by-one-half.column, + .offset-by-one-half.columns { margin-left: 52%; } + +} + + +/* Base Styles +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +/* NOTE +html is set to 62.5% so that all the REM measurements throughout Skeleton +are based on 10px sizing. So basically 1.5rem = 15px :) */ +html { + font-size: 62.5%; } +body { + font-size: 1.5em; /* currently ems cause chrome bug misinterpreting rems on body element */ + line-height: 1.6; + font-weight: 400; + font-family: "Raleway", "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif; + color: #222; } + + +/* Typography +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +h1, h2, h3, h4, h5, h6 { + margin-top: 0; + margin-bottom: 2rem; + font-weight: 300; } +h1 { font-size: 4.0rem; line-height: 1.2; letter-spacing: -.1rem;} +h2 { font-size: 3.6rem; line-height: 1.25; letter-spacing: -.1rem; } +h3 { font-size: 3.0rem; line-height: 1.3; letter-spacing: -.1rem; } +h4 { font-size: 2.4rem; line-height: 1.35; letter-spacing: -.08rem; } +h5 { font-size: 1.8rem; line-height: 1.5; letter-spacing: -.05rem; } +h6 { font-size: 1.5rem; line-height: 1.6; letter-spacing: 0; } + +/* Larger than phablet */ +@media (min-width: 550px) { + h1 { font-size: 5.0rem; } + h2 { font-size: 4.2rem; } + h3 { font-size: 3.6rem; } + h4 { font-size: 3.0rem; } + h5 { font-size: 2.4rem; } + h6 { font-size: 1.5rem; } +} + +p { + margin-top: 0; } + + +/* Links +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +a { + color: #1EAEDB; } +a:hover { + color: #0FA0CE; } + + +/* Buttons +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +.button, +button, +input[type="submit"], +input[type="reset"], +input[type="button"] { + display: inline-block; + height: 38px; + padding: 0 30px; + color: #555; + text-align: center; + font-size: 11px; + font-weight: 600; + line-height: 38px; + letter-spacing: .1rem; + text-transform: uppercase; + text-decoration: none; + white-space: nowrap; + background-color: transparent; + border-radius: 4px; + border: 1px solid #bbb; + cursor: pointer; + box-sizing: border-box; } +.button:hover, +button:hover, +input[type="submit"]:hover, +input[type="reset"]:hover, +input[type="button"]:hover, +.button:focus, +button:focus, +input[type="submit"]:focus, +input[type="reset"]:focus, +input[type="button"]:focus { + color: #333; + border-color: #888; + outline: 0; } +.button.button-primary, +button.button-primary, +input[type="submit"].button-primary, +input[type="reset"].button-primary, +input[type="button"].button-primary { + color: #FFF; + background-color: #33C3F0; + border-color: #33C3F0; } +.button.button-primary:hover, +button.button-primary:hover, +input[type="submit"].button-primary:hover, +input[type="reset"].button-primary:hover, +input[type="button"].button-primary:hover, +.button.button-primary:focus, +button.button-primary:focus, +input[type="submit"].button-primary:focus, +input[type="reset"].button-primary:focus, +input[type="button"].button-primary:focus { + color: #FFF; + background-color: #1EAEDB; + border-color: #1EAEDB; } + + +/* Forms +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +input[type="email"], +input[type="number"], +input[type="search"], +input[type="text"], +input[type="tel"], +input[type="url"], +input[type="password"], +textarea, +select { + height: 38px; + padding: 6px 10px; /* The 6px vertically centers text on FF, ignored by Webkit */ + background-color: #fff; + border: 1px solid #D1D1D1; + border-radius: 4px; + box-shadow: none; + box-sizing: border-box; } +/* Removes awkward default styles on some inputs for iOS */ +input[type="email"], +input[type="number"], +input[type="search"], +input[type="text"], +input[type="tel"], +input[type="url"], +input[type="password"], +textarea { + -webkit-appearance: none; + -moz-appearance: none; + appearance: none; } +textarea { + min-height: 65px; + padding-top: 6px; + padding-bottom: 6px; } +input[type="email"]:focus, +input[type="number"]:focus, +input[type="search"]:focus, +input[type="text"]:focus, +input[type="tel"]:focus, +input[type="url"]:focus, +input[type="password"]:focus, +textarea:focus, +select:focus { + border: 1px solid #33C3F0; + outline: 0; } +label, +legend { + display: block; + margin-bottom: .5rem; + font-weight: 600; } +fieldset { + padding: 0; + border-width: 0; } +input[type="checkbox"], +input[type="radio"] { + display: inline; } +label > .label-body { + display: inline-block; + margin-left: .5rem; + font-weight: normal; } + + +/* Lists +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +ul { + list-style: circle inside; } +ol { + list-style: decimal inside; } +ol, ul { + padding-left: 0; + margin-top: 0; } +ul ul, +ul ol, +ol ol, +ol ul { + margin: 1.5rem 0 1.5rem 3rem; + font-size: 90%; } +li { + margin-bottom: 1rem; } + + +/* Code +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +code { + padding: .2rem .5rem; + margin: 0 .2rem; + font-size: 90%; + white-space: nowrap; + background: #F1F1F1; + border: 1px solid #E1E1E1; + border-radius: 4px; } +pre > code { + display: block; + padding: 1rem 1.5rem; + white-space: pre; } + + +/* Tables +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +th, +td { + padding: 12px 15px; + text-align: left; + border-bottom: 1px solid #E1E1E1; } +th:first-child, +td:first-child { + padding-left: 0; } +th:last-child, +td:last-child { + padding-right: 0; } + + +/* Spacing +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +button, +.button { + margin-bottom: 1rem; } +input, +textarea, +select, +fieldset { + margin-bottom: 1.5rem; } +pre, +blockquote, +dl, +figure, +table, +p, +ul, +ol, +form { + margin-bottom: 2.5rem; } + + +/* Utilities +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +.u-full-width { + width: 100%; + box-sizing: border-box; } +.u-max-full-width { + max-width: 100%; + box-sizing: border-box; } +.u-pull-right { + float: right; } +.u-pull-left { + float: left; } + + +/* Misc +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +hr { + margin-top: 3rem; + margin-bottom: 3.5rem; + border-width: 0; + border-top: 1px solid #E1E1E1; } + + +/* Clearing +–––––––––––––––––––––––––––––––––––––––––––––––––– */ + +/* Self Clearing Goodness */ +.container:after, +.row:after, +.u-cf { + content: ""; + display: table; + clear: both; } + + +/* Media Queries +–––––––––––––––––––––––––––––––––––––––––––––––––– */ +/* +Note: The best way to structure the use of media queries is to create the queries +near the relevant code. For example, if you wanted to change the styles for buttons +on small devices, paste the mobile query code up in the buttons section and style it +there. +*/ + + +/* Larger than mobile */ +@media (min-width: 400px) {} + +/* Larger than phablet (also point when grid becomes active) */ +@media (min-width: 550px) {} + +/* Larger than tablet */ +@media (min-width: 750px) {} + +/* Larger than desktop */ +@media (min-width: 1000px) {} + +/* Larger than Desktop HD */ +@media (min-width: 1200px) {} diff --git a/test/example.spec.js b/test/example.spec.js new file mode 100644 index 0000000..8cd8915 --- /dev/null +++ b/test/example.spec.js @@ -0,0 +1,85 @@ +describe('canvas2svg exports', function() { + + var examples = Object.keys(C2S_EXAMPLES); + var C2S_WIDTH = 600; + var C2S_HEIGHT = 600; + var imgdata, svgimgdata, diffdata; + + function drawExample (example) { + var canvas = document.createElement('canvas'); + canvas.setAttribute('width', C2S_WIDTH); + canvas.setAttribute('height', C2S_HEIGHT); + document.body.appendChild(canvas); + var ctx = canvas.getContext("2d"); + ctx.clearRect(0, 0, C2S_WIDTH, C2S_HEIGHT); + var c2s = new C2S(C2S_WIDTH, C2S_HEIGHT); + + example(ctx); + example(c2s); + + imgdata = canvas.toDataURL(); + svgimgdata = "data:image/svg+xml;charset=utf-8,"+c2s.getSerializedSvg(true); + } + + function cleanUp () { + var canvases = document.querySelectorAll('canvas'); + var i; + //Node Array doesn't implement array methods :/ + for(i=0; i 0) { + //append svg + canvas images + var li = lis[lis.length - 2]; + var image = document.createElement('img'); + image.setAttribute('src', imgdata); + image.setAttribute('style', 'display:inline-block;'); + + var svgimage = document.createElement('img'); + svgimage.setAttribute('src', svgimgdata); + svgimage.setAttribute('style', 'display:inline-block;'); + li.appendChild(image); + li.appendChild(svgimage); + + // append diff data + li = lis[lis.length-1]; + var diffimage = document.createElement('img'); + diffimage.setAttribute('src', diffdata.getImageDataUrl()); + diffimage.setAttribute('style', 'display:inline-block;'); + li.appendChild(diffimage); + } + }); + + }); + + }); +}); \ No newline at end of file diff --git a/test/example/arc.js b/test/example/arc.js new file mode 100644 index 0000000..8af818f --- /dev/null +++ b/test/example/arc.js @@ -0,0 +1,24 @@ +window.C2S_EXAMPLES['arc'] = function(ctx) { + + // Draw shapes + for (i = 0; i < 4; i++) { + for (j = 0; j < 3; j++) { + ctx.beginPath(); + var x = 25 + j * 50; // x coordinate + var y = 25 + i * 50; // y coordinate + var radius = 20; // Arc radius + var startAngle = 0; // Starting point on circle + var endAngle = Math.PI + (Math.PI * j) / 2; // End point on circle + var clockwise = i % 2 == 0 ? false : true; // clockwise or anticlockwise + + ctx.arc(x, y, radius, startAngle, endAngle, clockwise); + + if (i > 1) { + ctx.fill(); + } else { + ctx.stroke(); + } + } + } + +}; \ No newline at end of file diff --git a/test/example/arcTo.js b/test/example/arcTo.js new file mode 100644 index 0000000..36995ed --- /dev/null +++ b/test/example/arcTo.js @@ -0,0 +1,16 @@ +window.C2S_EXAMPLES['arcTo'] = function (ctx) { + ctx.beginPath(); + ctx.moveTo(150, 20); + ctx.arcTo(150, 100, 50, 20, 30); + ctx.stroke(); + + ctx.fillStyle = 'blue'; + // base point + ctx.fillRect(150, 20, 10, 10); + + ctx.fillStyle = 'red'; + // control point one + ctx.fillRect(150, 100, 10, 10); + // control point two + ctx.fillRect(50, 20, 10, 10); +}; \ No newline at end of file diff --git a/test/example/arcTo2.js b/test/example/arcTo2.js new file mode 100644 index 0000000..8a53240 --- /dev/null +++ b/test/example/arcTo2.js @@ -0,0 +1,7 @@ +window.C2S_EXAMPLES['arcTo2'] = function(ctx) { + ctx.beginPath(); + ctx.moveTo(100, 225); // P0 + ctx.arcTo(300, 25, 500, 225, 75); // P1, P2 and the radius + ctx.lineTo(500, 225); // P2 + ctx.stroke(); +}; \ No newline at end of file diff --git a/test/example/emptyArc.js b/test/example/emptyArc.js new file mode 100644 index 0000000..0ad71f9 --- /dev/null +++ b/test/example/emptyArc.js @@ -0,0 +1,12 @@ +window.C2S_EXAMPLES['emptyArc'] = function(ctx) { + + // Draw shapes + for (i = 0; i < 4; i++) { + for (j = 0; j < 3; j++) { + ctx.beginPath(); + ctx.arc(100, 100, 100, Math.PI, Math.PI); + ctx.fill(); + } + } + +}; diff --git a/test/example/fillstyle.js b/test/example/fillstyle.js new file mode 100644 index 0000000..12a5d87 --- /dev/null +++ b/test/example/fillstyle.js @@ -0,0 +1,9 @@ +window.C2S_EXAMPLES['fillstyle'] = function(ctx) { + for (var i = 0; i < 6; i++) { + for (var j = 0; j < 6; j++) { + ctx.fillStyle = 'rgb(' + Math.floor(255 - 42.5 * i) + ',' + + Math.floor(255 - 42.5 * j) + ',0)'; + ctx.fillRect(j * 25, i * 25, 25, 25); + } + } +}; \ No newline at end of file diff --git a/test/example/globalalpha.js b/test/example/globalalpha.js new file mode 100644 index 0000000..fbb25c8 --- /dev/null +++ b/test/example/globalalpha.js @@ -0,0 +1,23 @@ +window.C2S_EXAMPLES['globalalpha'] = function(ctx) { + ctx.fillStyle = '#FD0'; + ctx.fillRect(0,0,75,75); + ctx.fillStyle = '#6C0'; + ctx.fillRect(75,0,75,75); + ctx.fillStyle = '#09F'; + ctx.fillRect(0,75,75,75); + ctx.fillStyle = '#F30'; + ctx.fillRect(75,75,75,75); + ctx.fillStyle = '#FFF'; + + // set transparency value + ctx.globalAlpha = 0.2; + + // Draw semi transparent circles + for (i=0;i<7;i++){ + ctx.beginPath(); + ctx.arc(75,75,10+10*i,0,Math.PI*2,true); + ctx.fill(); + } + + ctx.globalAlpha = 1.0; +}; \ No newline at end of file diff --git a/test/example/gradient.js b/test/example/gradient.js new file mode 100644 index 0000000..d191784 --- /dev/null +++ b/test/example/gradient.js @@ -0,0 +1,49 @@ +window.C2S_EXAMPLES['gradient'] = function(ctx) { + ctx.save(); + ctx.strokeStyle='rgba(0,0,0,0)'; + ctx.lineCap='butt'; + ctx.lineJoin='miter'; + ctx.miterLimit=10.0; + ctx.font='10px sans-serif'; + ctx.save(); + var radialGradient_1389130830351 = ctx.createRadialGradient(6E1,6E1,0.0,6E1,6E1,5E1); + radialGradient_1389130830351.addColorStop(0E0,'red'); + radialGradient_1389130830351.addColorStop(1E0,'blue'); + ctx.fillStyle=radialGradient_1389130830351; + ctx.font='10px sans-serif'; + ctx.beginPath(); + ctx.moveTo(2.5E1,1E1); + ctx.lineTo(9.5E1,1E1); + ctx.quadraticCurveTo(1.1E2,1E1,1.1E2,2.5E1); + ctx.lineTo(1.1E2,9.5E1); + ctx.quadraticCurveTo(1.1E2,1.1E2,9.5E1,1.1E2); + ctx.lineTo(2.5E1,1.1E2); + ctx.quadraticCurveTo(1E1,1.1E2,1E1,9.5E1); + ctx.lineTo(1E1,2.5E1); + ctx.quadraticCurveTo(1E1,1E1,2.5E1,1E1); + ctx.closePath(); + ctx.fill(); + ctx.stroke(); + ctx.restore(); + ctx.save(); + var radialGradient_1389130830351 = ctx.createRadialGradient(3.5E1,1.45E2,0.0,3.5E1,1.45E2,2.5E1); + radialGradient_1389130830351.addColorStop(0E0,'red'); + radialGradient_1389130830351.addColorStop(1E0,'blue'); + ctx.fillStyle=radialGradient_1389130830351; + ctx.font='10px sans-serif'; + ctx.beginPath(); + ctx.moveTo(2.5E1,1.2E2); + ctx.lineTo(9.5E1,1.2E2); + ctx.quadraticCurveTo(1.1E2,1.2E2,1.1E2,1.35E2); + ctx.lineTo(1.1E2,2.05E2); + ctx.quadraticCurveTo(1.1E2,2.2E2,9.5E1,2.2E2); + ctx.lineTo(2.5E1,2.2E2); + ctx.quadraticCurveTo(1E1,2.2E2,1E1,2.05E2); + ctx.lineTo(1E1,1.35E2); + ctx.quadraticCurveTo(1E1,1.2E2,2.5E1,1.2E2); + ctx.closePath(); + ctx.fill(); + ctx.stroke(); + ctx.restore(); + ctx.restore(); +}; diff --git a/test/example/linecap.js b/test/example/linecap.js new file mode 100644 index 0000000..d0f48bb --- /dev/null +++ b/test/example/linecap.js @@ -0,0 +1,23 @@ +window.C2S_EXAMPLES['linecap'] = function(ctx) { + var lineCap = ['butt','round','square']; + + // Draw guides + ctx.strokeStyle = '#09f'; + ctx.beginPath(); + ctx.moveTo(10,10); + ctx.lineTo(140,10); + ctx.moveTo(10,140); + ctx.lineTo(140,140); + ctx.stroke(); + + // Draw lines + ctx.strokeStyle = 'black'; + for (var i=0;i + + + + Canvas2Svg Playground + + + + + +
+
+
+
+
Select an example
+
+
+
+
+
+
+ + +
+
+
+
+
+
Canvas
+
+
+
SVG
+
+
+
+
+ +
+
+
+
+
+
+
+
Or try your own!
+
+
+
+
+ +
+
+
+
+ Render +
+
+
+ + + + + + +
+ + + + \ No newline at end of file diff --git a/test/playground_wrapped_Context2D.html b/test/playground_wrapped_Context2D.html new file mode 100644 index 0000000..d6fa1d8 --- /dev/null +++ b/test/playground_wrapped_Context2D.html @@ -0,0 +1,110 @@ + + + + + Canvas2Svg Playground + + + + + +
+
+
+
+
Select an example
+
+
+
+
+
+
+ + +
+
+
+
+
+
Canvas
+
+
+
SVG
+
+
+
+
+ +
+
+ +
+
+
+
+
+
Or try your own!
+
+
+
+
+ +
+
+
+
+ Render +
+
+
+ + + + + + +
+ + + + \ No newline at end of file diff --git a/test/testrunner.html b/test/testrunner.html new file mode 100644 index 0000000..c55da99 --- /dev/null +++ b/test/testrunner.html @@ -0,0 +1,28 @@ + + + + + Canvas2Svg Unit Tests + + + +
+ + + + + + + +
+ + + + + \ No newline at end of file diff --git a/test/unit.spec.js b/test/unit.spec.js new file mode 100644 index 0000000..63dc637 --- /dev/null +++ b/test/unit.spec.js @@ -0,0 +1,360 @@ +describe('canvas2svg', function() { + + describe('it can be created', function(){ + + it("with options", function() { + var ctx = new C2S({width:100, height:200, enableMirroring:true}); + expect(ctx instanceof C2S).to.equal(true); + expect(ctx.width).to.equal(100); + expect(ctx.height).to.equal(200); + expect(ctx.enableMirroring).to.equal(true); + + var ctx2 = new C2S(300,400); + expect(ctx2 instanceof C2S).to.equal(true); + expect(ctx2.width).to.equal(300); + expect(ctx2.height).to.equal(400); + expect(ctx2.enableMirroring).to.equal(false); + }); + + it("with no options and have defaults", function() { + var ctx = new C2S(); + expect(ctx instanceof C2S).to.equal(true); + expect(ctx.width).to.equal(500); + expect(ctx.height).to.equal(500); + expect(ctx.enableMirroring).to.equal(false); + }); + + it("even if it's called as a function", function() { + //notice the lack of new! + var ctx = C2S({width:100, height:200, enableMirroring:true}); + expect(ctx instanceof C2S).to.equal(true); + expect(ctx.width).to.equal(100); + expect(ctx.height).to.equal(200); + expect(ctx.enableMirroring).to.equal(true); + + var ctx2 = C2S(300,400); + expect(ctx2 instanceof C2S).to.equal(true); + expect(ctx2.width).to.equal(300); + expect(ctx2.height).to.equal(400); + expect(ctx2.enableMirroring).to.equal(false); + + var ctx3 = C2S(); + expect(ctx3 instanceof C2S).to.equal(true); + expect(ctx3.width).to.equal(500); + expect(ctx3.height).to.equal(500); + expect(ctx3.enableMirroring).to.equal(false); + + }); + + it("can be created on another document", function () { + var otherDoc = document.implementation.createHTMLDocument(); + var ctx = C2S({document: otherDoc}); + expect(ctx.getSvg().ownerDocument).to.equal(otherDoc); + }); + + }); + + describe("can export to", function() { + + it("inline svg", function() { + var ctx = new C2S(); + ctx.fillStyle="red"; + ctx.fillRect(100,100,100,100); + //svg is of course not attached to the document + var svg = ctx.getSvg(); + expect(svg.nodeType).to.equal(1); + expect(svg.nodeName).to.equal("svg"); + }); + + it("serialized svg", function() { + var ctx = new C2S(); + ctx.fillStyle="red"; + ctx.fillRect(100,100,100,100); + //Standalone SVG doesn't support named entities, which document.createTextNode encodes. + //passing in true will attempt to find all named entities and encode it as a numeric entity. + var string = ctx.getSerializedSvg(true); + expect(typeof string).to.equal("string"); + expect(string).to.equal(''); + + }); + }); + + describe("with multiple transforms and fill/strokes", function() { + + it("creates new groups", function() { + var ctx = new C2S(); + ctx.translate(0, 20); + ctx.fillRect(0, 0, 10, 10); + + ctx.translate(10, 20); + ctx.fillRect(0, 0, 10, 10); + + ctx.translate(20, 20); + ctx.fillRect(0, 0, 10, 10); + + var svg = ctx.getSvg(); + var firstGroup = svg.querySelector("g"); + expect(firstGroup.getAttribute("transform")).to.equal("translate(0,20)"); + var secondGroup = firstGroup.querySelector("g"); + expect(secondGroup.getAttribute("transform")).to.equal("translate(10,20)"); + var thirdGroup = secondGroup.querySelector("g"); + expect(thirdGroup.getAttribute("transform")).to.equal("translate(20,20)"); + + }); + + it("save and restore still works", function() { + var ctx = new C2S(); + + ctx.translate(0, 10); + ctx.fillRect(0, 0, 10, 10); + + ctx.save(); + ctx.translate(40, 40); + ctx.fillRect(0, 0, 10, 10); + + ctx.restore(); + + ctx.translate(0, 10); + ctx.fillRect(0, 0, 10, 10); + + var svg = ctx.getSvg(); + var firstGroup = svg.querySelector("g"); + expect(firstGroup.getAttribute("transform")).to.equal("translate(0,10)"); + var secondGroup = firstGroup.childNodes[1]; + expect(secondGroup.getAttribute("transform")).to.equal("translate(40,40)"); + var thirdGroup = firstGroup.childNodes[2]; + expect(thirdGroup.getAttribute("transform")).to.equal("translate(0,10)"); + + }); + }); + + describe("it will generate ids", function() { + + it("that start with a letter", function() { + var ctx = new C2S(); + ctx.createRadialGradient(6E1, 6E1, 0.0, 6E1, 6E1, 5E1); + var svg = ctx.getSvg(); + var id = svg.children[0].children[0].id; + var test = /^[A-Za-z]/.test(id); + expect(test).to.equal(true); + }); + }); + + describe("will split up rgba", function() { + //while browsers support rgba values for fill/stroke, this is not accepted in visio/illustrator + it("to fill and fill-opacity", function() { + var ctx = new C2S(); + ctx.fillStyle="rgba(20,40,50,0.5)"; + ctx.fillRect(100,100,100,100); + var svg = ctx.getSvg(); + expect(svg.querySelector("rect").getAttribute("fill")).to.equal("rgb(20,40,50)"); + expect(svg.querySelector("rect").getAttribute("fill-opacity")).to.equal("0.5"); + }); + + it("to stroke and stroke-opacity", function() { + var ctx = new C2S(); + ctx.strokeStyle="rgba(10,20,30,0.4)"; + ctx.strokeRect(100,100,100,100); + var svg = ctx.getSvg(); + expect(svg.querySelector("rect").getAttribute("stroke")).to.equal("rgb(10,20,30)"); + expect(svg.querySelector("rect").getAttribute("stroke-opacity")).to.equal("0.4"); + }); + }); + + describe("supports path commands", function() { + + it("and moveTo may be called without beginPath, but is not recommended", function() { + var ctx = new C2S(); + ctx.moveTo(0,0); + ctx.lineTo(100,100); + ctx.stroke(); + }); + }); + + describe("supports text align", function() { + + it("not specifying a value defaults to 'start'", function() { + + var ctx = new C2S(); + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("text-anchor")).to.equal("start"); + + }); + + it("assuming ltr, left maps to 'start'", function() { + + var ctx = new C2S(); + ctx.textAlign = "left"; + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("text-anchor")).to.equal("start"); + + }); + + it("assuming ltr, right maps to 'end'", function() { + + var ctx = new C2S(); + ctx.textAlign = "right"; + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("text-anchor")).to.equal("end"); + + }); + + it("center maps to 'middle'", function() { + + var ctx = new C2S(); + ctx.textAlign = "center"; + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("text-anchor")).to.equal("middle"); + + }); + + it("stores the proper values on save and restore", function() { + var ctx = new C2S(); + ctx.textAlign = "center"; + expect(ctx.textAlign).to.equal("center"); + ctx.save(); + expect(ctx.textAlign).to.equal("center"); + ctx.textAlign = "right"; + expect(ctx.textAlign).to.equal("right"); + ctx.restore(); + expect(ctx.textAlign).to.equal("center"); + }); + + }); + + describe("supports text baseline", function() { + + it("not specifying a value defaults to alphabetic", function() { + var ctx = new C2S(); + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("alphabetic"); + }); + + it("not specifying a valid value defaults to alphabetic", function() { + var ctx = new C2S(); + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.textBaseline = "werwerwer"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("alphabetic"); + }); + + it("hanging maps to hanging", function() { + var ctx = new C2S(); + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.textBaseline = "hanging"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("hanging"); + }); + + it("top maps to text-before-edge", function() { + var ctx = new C2S(); + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.textBaseline = "top"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("text-before-edge"); + }); + + it("bottom maps to text-after-edge", function() { + var ctx = new C2S(); + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.textBaseline = "bottom"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("text-after-edge"); + }); + + it("middle maps to central", function() { + var ctx = new C2S(); + ctx.font = "normal 36px Times"; + ctx.fillStyle = "#000000"; + ctx.textBaseline = "middle"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("dominant-baseline")).to.equal("central"); + }); + + }); + + describe("supports fonts", function () { + it("doesn't crash when using a font", function () { + var ctx = new C2S(); + ctx.font = "normal 12px 'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"; + ctx.fillText("A Text Example", 0, 50); + var svg = ctx.getSvg(); + expect(svg.querySelector("text").getAttribute("font-family")).to.equal("\'Helvetica Neue\', \'Helvetica\', \'Arial\', sans-serif"); + expect(svg.querySelector("text").getAttribute("font-size")).to.equal("12px"); + expect(svg.querySelector("text").getAttribute("font-weight")).to.equal("normal"); + expect(svg.querySelector("text").getAttribute("font-style")).to.equal("normal"); + }); + }); + + describe("supports globalOpacity", function() { + it("set stroke-opacity when stroking and set fill-opacity when filling",function() { + var ctx = new C2S(); + ctx.globalAlpha = 0.5; + ctx.moveTo(5,5); + ctx.lineTo(15,15); + ctx.stroke(); + var svg = ctx.getSvg(); + expect(svg.querySelector("path").getAttribute("stroke-opacity")).to.equal('0.5'); + ctx.globalAlpha = 0.1; + ctx.fillStyle = "#000000"; + ctx.fill(); + expect(svg.querySelector("path").getAttribute("fill-opacity")).to.equal('0.1'); + //stroke-opacity stays o.5 + expect(svg.querySelector("path").getAttribute("stroke-opacity")).to.equal('0.5'); + }); + + it("added into color opacity when stroking or filling with rgba style color. ",function() { + var ctx = new C2S(); + ctx.strokeStyle="rgba(0,0,0,0.8)"; + ctx.globalAlpha = 0.5; + ctx.moveTo(5,5); + ctx.lineTo(15,15); + ctx.stroke(); + var svg = ctx.getSvg(); + expect(svg.querySelector("path").getAttribute("stroke")).to.equal('rgb(0,0,0)'); + //stroke-opacity should be globalAlpha*(alpha in rgba) + expect(svg.querySelector("path").getAttribute("stroke-opacity")).to.equal(''+0.8*0.5); + ctx.globalAlpha = 0.6; + ctx.fillStyle = "rgba(0,0,0,0.6)"; + ctx.fill(); + expect(svg.querySelector("path").getAttribute("fill-opacity")).to.equal(''+0.6*0.6); + expect(svg.querySelector("path").getAttribute("stroke-opacity")).to.equal(''+0.8*0.5); + }); + }); + + describe("supports clip", function() { + it("adds clippath", function() { + var ctx = new C2S(); + ctx.rect(200, 200, 400, 400); + ctx.clip(); + ctx.fillStyle = "#000000"; + ctx.rect(100, 100, 300, 300); + var svg = ctx.getSvg(); + expect(svg.querySelector("clipPath > path").getAttribute("d")).to.not.equal(null); + }); + }); +});