diff --git a/.eslintignore b/.eslintignore index 92d1e86d..032642aa 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,5 +1,6 @@ node_modules +# Vendor/minified files editor/jquery.js editor/jspdf/jspdf.min.js editor/jspdf/underscore-min.js diff --git a/docs/SvgCanvas.md b/docs/SvgCanvas.md index 2b51cfde..331ef47e 100644 --- a/docs/SvgCanvas.md +++ b/docs/SvgCanvas.md @@ -736,7 +736,7 @@ Rounds a given value to a float with number of digits defined in save_options #### Returns -If a string/number was given, returns a Float. If an array, return a string with comma-seperated floats +If a string/number was given, returns a Float. If an array, return a string with comma-separated floats ## `getStrokedBBox` diff --git a/editor/browser.js b/editor/browser.js index 7ebe82e9..8b5e5b4a 100644 --- a/editor/browser.js +++ b/editor/browser.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals $, svgedit */ /** * Package: svgedit.browser @@ -119,7 +119,7 @@ var supportsHVLineContainerBBox_ = (function () { var bbox = g.getBBox(); document.documentElement.removeChild(svgcontent); // Webkit gives 0, FF gives 10, Opera (correctly) gives 15 - return (bbox.width == 15); + return (bbox.width === 15); }()); var supportsEditableText_ = (function () { @@ -153,13 +153,13 @@ var supportsNativeSVGTransformLists_ = (function () { rxform.appendItem(t1); var r1 = rxform.getItem(0); return r1 instanceof SVGTransform && t1 instanceof SVGTransform && - r1.type == t1.type && r1.angle == t1.angle && - r1.matrix.a == t1.matrix.a && - r1.matrix.b == t1.matrix.b && - r1.matrix.c == t1.matrix.c && - r1.matrix.d == t1.matrix.d && - r1.matrix.e == t1.matrix.e && - r1.matrix.f == t1.matrix.f; + r1.type === t1.type && r1.angle === t1.angle && + r1.matrix.a === t1.matrix.a && + r1.matrix.b === t1.matrix.b && + r1.matrix.c === t1.matrix.c && + r1.matrix.d === t1.matrix.d && + r1.matrix.e === t1.matrix.e && + r1.matrix.f === t1.matrix.f; }()); // Public API diff --git a/editor/contextmenu.js b/editor/contextmenu.js index d0c059dc..986c462c 100644 --- a/editor/contextmenu.js +++ b/editor/contextmenu.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals $, svgEditor */ /** * Package: svgedit.contextmenu @@ -17,7 +17,7 @@ if (!svgedit.contextmenu) { } self.contextMenuExtensions = {}; var menuItemIsValid = function (menuItem) { - return menuItem && menuItem.id && menuItem.label && menuItem.action && typeof menuItem.action == 'function'; + return menuItem && menuItem.id && menuItem.label && menuItem.action && typeof menuItem.action === 'function'; }; var addContextMenuItem = function (menuItem) { // menuItem: {id, label, shortcut, action} diff --git a/editor/coords.js b/editor/coords.js index 45bd3560..6e839f80 100644 --- a/editor/coords.js +++ b/editor/coords.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals $, svgroot */ /** * Coords. @@ -103,9 +103,9 @@ svgedit.coords.remapElement = function (selected, changes, m) { var elName = selected.tagName; var chlist, mt; - if (elName === 'g' || elName === 'text' || elName == 'tspan' || elName === 'use') { + if (elName === 'g' || elName === 'text' || elName === 'tspan' || elName === 'use') { // if it was a translate, then just update x,y - if (m.a == 1 && m.b == 0 && m.c == 0 && m.d == 1 && (m.e != 0 || m.f != 0)) { + if (m.a === 1 && m.b === 0 && m.c === 0 && m.d === 1 && (m.e !== 0 || m.f !== 0)) { // [T][M] = [M][T'] // therefore [T'] = [M_inv][T][M] var existing = svgedit.math.transformListToTransform(selected).matrix, @@ -239,9 +239,9 @@ svgedit.coords.remapElement = function (selected, changes, m) { type = seg.type; // if absolute or first segment, we want to remap x, y, x1, y1, x2, y2 // if relative, we want to scalew, scaleh - if (type % 2 == 0) { // absolute - var thisx = (seg.x != undefined) ? seg.x : currentpt.x, // for V commands - thisy = (seg.y != undefined) ? seg.y : currentpt.y; // for H commands + if (type % 2 === 0) { // absolute + var thisx = (seg.x !== undefined) ? seg.x : currentpt.x, // for V commands + thisy = (seg.y !== undefined) ? seg.y : currentpt.y; // for H commands pt = remap(thisx, thisy); pt1 = remap(seg.x1, seg.y1); pt2 = remap(seg.x2, seg.y2); diff --git a/editor/draw.js b/editor/draw.js index 44e6b07d..9799cd9f 100644 --- a/editor/draw.js +++ b/editor/draw.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals $, svgedit */ /** * Package: svgedit.draw @@ -42,9 +42,9 @@ svgedit.draw.randomizeIds = function (enableRandomization, currentDrawing) { ? RandomizeModes.NEVER_RANDOMIZE : RandomizeModes.ALWAYS_RANDOMIZE; - if (randomizeIds == RandomizeModes.ALWAYS_RANDOMIZE && !currentDrawing.getNonce()) { + if (randomizeIds === RandomizeModes.ALWAYS_RANDOMIZE && !currentDrawing.getNonce()) { currentDrawing.setNonce(Math.floor(Math.random() * 100001)); - } else if (randomizeIds == RandomizeModes.NEVER_RANDOMIZE && currentDrawing.getNonce()) { + } else if (randomizeIds === RandomizeModes.NEVER_RANDOMIZE && currentDrawing.getNonce()) { currentDrawing.clearNonce(); } }; @@ -58,7 +58,7 @@ svgedit.draw.randomizeIds = function (enableRandomization, currentDrawing) { */ svgedit.draw.Drawing = function (svgElem, optIdPrefix) { if (!svgElem || !svgElem.tagName || !svgElem.namespaceURI || - svgElem.tagName != 'svg' || svgElem.namespaceURI != NS.SVG) { + svgElem.tagName !== 'svg' || svgElem.namespaceURI !== NS.SVG) { throw new Error('Error: svgedit.draw.Drawing instance initialized without a element'); } @@ -118,9 +118,9 @@ svgedit.draw.Drawing = function (svgElem, optIdPrefix) { var n = this.svgElem_.getAttributeNS(NS.SE, 'nonce'); // If already set in the DOM, use the nonce throughout the document // else, if randomizeIds(true) has been called, create and set the nonce. - if (!!n && randomizeIds != RandomizeModes.NEVER_RANDOMIZE) { + if (!!n && randomizeIds !== RandomizeModes.NEVER_RANDOMIZE) { this.nonce_ = n; - } else if (randomizeIds == RandomizeModes.ALWAYS_RANDOMIZE) { + } else if (randomizeIds === RandomizeModes.ALWAYS_RANDOMIZE) { this.setNonce(Math.floor(Math.random() * 100001)); } }; @@ -234,7 +234,7 @@ svgedit.draw.Drawing.prototype.releaseId = function (id) { // if we didn't get a positive number or we already released this number // then return false. - if (typeof num !== 'number' || num <= 0 || this.releasedNums.indexOf(num) != -1) { + if (typeof num !== 'number' || num <= 0 || this.releasedNums.indexOf(num) !== -1) { return false; } @@ -326,12 +326,12 @@ svgedit.draw.Drawing.prototype.setCurrentLayerPosition = function (newpos) { var oldpos; for (oldpos = 0; oldpos < layerCount; ++oldpos) { - if (this.all_layers[oldpos] == this.current_layer) { break; } + if (this.all_layers[oldpos] === this.current_layer) { break; } } // some unknown error condition (current_layer not in all_layers) - if (oldpos == layerCount) { return null; } + if (oldpos === layerCount) { return null; } - if (oldpos != newpos) { + if (oldpos !== newpos) { // if our new position is below us, we need to insert before the node after newpos var refGroup = null; var currentGroup = this.current_layer.getGroup(); @@ -369,7 +369,7 @@ svgedit.draw.Drawing.prototype.mergeLayer = function (hrService) { while (currentGroup.firstChild) { var child = currentGroup.firstChild; - if (child.localName == 'title') { + if (child.localName === 'title') { hrService.removeElement(child, child.nextSibling, currentGroup); currentGroup.removeChild(child); continue; @@ -480,7 +480,7 @@ svgedit.draw.Drawing.prototype.identifyLayers = function () { for (var i = 0; i < numchildren; ++i) { var child = this.svgElem_.childNodes.item(i); // for each g, find its layer name - if (child && child.nodeType == 1) { + if (child && child.nodeType === 1) { if (child.tagName === 'g') { childgroups = true; var name = findLayerNameInGroup(child); @@ -569,7 +569,7 @@ svgedit.draw.Drawing.prototype.cloneLayer = function (name, hrService) { var index; for (index = 0; index < children.length; index++) { var ch = children[index]; - if (ch.localName == 'title') { continue; } + if (ch.localName === 'title') { continue; } group.appendChild(this.copyElem(ch)); } diff --git a/editor/math.js b/editor/math.js index 79a95ede..b84e6dfd 100644 --- a/editor/math.js +++ b/editor/math.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals svgedit */ /** * Package: svedit.math @@ -88,7 +88,7 @@ svgedit.math.hasMatrixTransform = function (tlist) { var num = tlist.numberOfItems; while (num--) { var xform = tlist.getItem(num); - if (xform.type == 1 && !svgedit.math.isIdentity(xform.matrix)) { return true; } + if (xform.type === 1 && !svgedit.math.isIdentity(xform.matrix)) { return true; } } return false; }; diff --git a/editor/path.js b/editor/path.js index 2f7d7b05..46dca2e9 100644 --- a/editor/path.js +++ b/editor/path.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals $, svgedit, svgroot */ /** * Package: svgedit.path @@ -85,7 +85,7 @@ svgedit.path.insertItemBefore = function (elem, newseg, index) { } list.clear(); for (i = 0; i < len; i++) { - if (i == index) { // index + 1 + if (i === index) { // index + 1 list.appendItem(newseg); } list.appendItem(arr[i]); @@ -301,7 +301,7 @@ svgedit.path.replacePathSeg = function (type, index, pts, elem) { } segList.clear(); for (i = 0; i < len; i++) { - if (i == index) { + if (i === index) { segList.appendItem(seg); } else { segList.appendItem(arr[i]); @@ -370,7 +370,7 @@ svgedit.path.smoothControlPoints = function (ct1, ct2, pt) { x2 = ct2.x - pt.x, y2 = ct2.y - pt.y; - if ((x1 != 0 || y1 != 0) && (x2 != 0 || y2 != 0)) { + if ((x1 !== 0 || y1 !== 0) && (x2 !== 0 || y2 !== 0)) { var anglea = Math.atan2(y1, x1), angleb = Math.atan2(y2, x2), r1 = Math.sqrt(x1 * x1 + y1 * y1), @@ -509,7 +509,7 @@ svgedit.path.Segment.prototype.move = function (dx, dy) { svgedit.path.Segment.prototype.setLinked = function (num) { var seg, anum, pt; - if (num == 2) { + if (num === 2) { anum = 1; seg = this.next; if (!seg) { return; } @@ -744,7 +744,7 @@ svgedit.path.Path.prototype.subpathIsClosed = function (index) { svgedit.path.Path.prototype.removePtFromSelection = function (index) { var pos = this.selected_pts.indexOf(index); - if (pos == -1) { + if (pos === -1) { return; } this.segs[index].select(false); @@ -810,7 +810,7 @@ svgedit.path.Path.prototype.setSegType = function (newType) { // Toggle segment to curve/straight line var oldType = cur.type; - newType = (oldType == 6) ? 4 : 6; + newType = (oldType === 6) ? 4 : 6; } newType = Number(newType); @@ -965,7 +965,7 @@ svgedit.path.recalcRotatedPath = function () { i -= 1; var seg = list.getItem(i), type = seg.pathSegType; - if (type == 1) { continue; } + if (type === 1) { continue; } var rvals = getRotVals(seg.x, seg.y), points = [rvals.x, rvals.y]; diff --git a/editor/pathseg.js b/editor/pathseg.js index b9c1398b..648721d2 100644 --- a/editor/pathseg.js +++ b/editor/pathseg.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq, no-redeclare */ +/* eslint-disable no-var, no-redeclare */ // SVGPathSeg API polyfill // https://github.com/progers/pathseg // @@ -651,11 +651,11 @@ if (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.pro Source.prototype._nextCommandHelper = function (lookahead, previousCommand) { // Check for remaining coordinates in the current command. - if ((lookahead === '+' || lookahead === '-' || lookahead === '.' || (lookahead >= '0' && lookahead <= '9')) && previousCommand != window.SVGPathSeg.PATHSEG_CLOSEPATH) { - if (previousCommand == window.SVGPathSeg.PATHSEG_MOVETO_ABS) { + if ((lookahead === '+' || lookahead === '-' || lookahead === '.' || (lookahead >= '0' && lookahead <= '9')) && previousCommand !== window.SVGPathSeg.PATHSEG_CLOSEPATH) { + if (previousCommand === window.SVGPathSeg.PATHSEG_MOVETO_ABS) { return window.SVGPathSeg.PATHSEG_LINETO_ABS; } - if (previousCommand == window.SVGPathSeg.PATHSEG_MOVETO_REL) { + if (previousCommand === window.SVGPathSeg.PATHSEG_MOVETO_REL) { return window.SVGPathSeg.PATHSEG_LINETO_REL; } return previousCommand; @@ -670,7 +670,7 @@ if (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.pro } var command = this.peekSegmentType(); // Path must start with moveTo. - return command == window.SVGPathSeg.PATHSEG_MOVETO_ABS || command == window.SVGPathSeg.PATHSEG_MOVETO_REL; + return command === window.SVGPathSeg.PATHSEG_MOVETO_ABS || command === window.SVGPathSeg.PATHSEG_MOVETO_REL; }; // Parse a number from an SVG path. This very closely follows genericParseNumber(...) from Source/core/svg/SVGParserUtilities.cpp. @@ -695,7 +695,7 @@ if (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.pro sign = -1; } - if (this._currentIndex == this._endIndex || ((this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') && this._string.charAt(this._currentIndex) !== '.')) { + if (this._currentIndex === this._endIndex || ((this._string.charAt(this._currentIndex) < '0' || this._string.charAt(this._currentIndex) > '9') && this._string.charAt(this._currentIndex) !== '.')) { // The first character of a number must be one of [0-9+-.]. return undefined; } @@ -706,7 +706,7 @@ if (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.pro this._currentIndex++; // Advance to first non-digit. } - if (this._currentIndex != startIntPartIndex) { + if (this._currentIndex !== startIntPartIndex) { var scanIntPartIndex = this._currentIndex - 1; var multiplier = 1; while (scanIntPartIndex >= startIntPartIndex) { @@ -731,7 +731,7 @@ if (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.pro } // Read the exponent part. - if (this._currentIndex != startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) === 'e' || this._string.charAt(this._currentIndex) === 'E') && (this._string.charAt(this._currentIndex + 1) !== 'x' && this._string.charAt(this._currentIndex + 1) !== 'm')) { + if (this._currentIndex !== startIndex && this._currentIndex + 1 < this._endIndex && (this._string.charAt(this._currentIndex) === 'e' || this._string.charAt(this._currentIndex) === 'E') && (this._string.charAt(this._currentIndex + 1) !== 'x' && this._string.charAt(this._currentIndex + 1) !== 'm')) { this._currentIndex++; // Read the sign of the exponent. @@ -761,7 +761,7 @@ if (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.pro number *= Math.pow(10, expsign * exponent); } - if (startIndex == this._currentIndex) { + if (startIndex === this._currentIndex) { return undefined; } @@ -791,13 +791,13 @@ if (!('SVGPathSegList' in window) || !('appendItem' in window.SVGPathSegList.pro Source.prototype.parseSegment = function () { var lookahead = this._string[this._currentIndex]; var command = this._pathSegTypeFromChar(lookahead); - if (command == window.SVGPathSeg.PATHSEG_UNKNOWN) { + if (command === window.SVGPathSeg.PATHSEG_UNKNOWN) { // Possibly an implicit command. Not allowed if this is the first command. - if (this._previousCommand == window.SVGPathSeg.PATHSEG_UNKNOWN) { + if (this._previousCommand === window.SVGPathSeg.PATHSEG_UNKNOWN) { return null; } command = this._nextCommandHelper(lookahead, this._previousCommand); - if (command == window.SVGPathSeg.PATHSEG_UNKNOWN) { + if (command === window.SVGPathSeg.PATHSEG_UNKNOWN) { return null; } } else { diff --git a/editor/recalculate.js b/editor/recalculate.js index 1b7dc687..a2e3d702 100644 --- a/editor/recalculate.js +++ b/editor/recalculate.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq, no-redeclare */ +/* eslint-disable no-var, no-redeclare */ /* globals $, getRefElem */ /** * Recalculate. @@ -98,7 +98,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { } // if this element had no transforms, we are done - if (!tlist || tlist.numberOfItems == 0) { + if (!tlist || tlist.numberOfItems === 0) { // Chrome has a bug that requires clearing the attribute first. selected.setAttribute('transform', ''); selected.removeAttribute('transform'); @@ -227,7 +227,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { initial.transform = context_.getStartTransform() || ''; // if it's a regular group, we have special processing to flatten transforms - if ((selected.tagName == 'g' && !gsvg) || selected.tagName === 'a') { + if ((selected.tagName === 'g' && !gsvg) || selected.tagName === 'a') { var box = svgedit.utilities.getBBox(selected), oldcenter = {x: box.x + box.width / 2, y: box.y + box.height / 2}, newcenter = svgedit.math.transformPoint(box.x + box.width / 2, @@ -248,7 +248,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { var i; for (i = 0; i < tlist.numberOfItems; ++i) { var xform = tlist.getItem(i); - if (xform.type == 4) { + if (xform.type === 4) { // extract old center through mystical arts var rm = xform.matrix; oldcenter.y = (s * rm.e + rm.f) / 2; @@ -267,8 +267,8 @@ svgedit.recalculate.recalculateDimensions = function (selected) { } // first, if it was a scale then the second-last transform will be it - if (N >= 3 && tlist.getItem(N - 2).type == 3 && - tlist.getItem(N - 3).type == 2 && tlist.getItem(N - 1).type == 2) { + if (N >= 3 && tlist.getItem(N - 2).type === 3 && + tlist.getItem(N - 3).type === 2 && tlist.getItem(N - 1).type === 2) { operation = 3; // scale // if the children are unrotated, pass the scale down directly @@ -283,7 +283,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { var child = children.item(c); tx = 0; ty = 0; - if (child.nodeType == 1) { + if (child.nodeType === 1) { var childTlist = svgedit.transformlist.getTransformList(child); // some children might not have a transform (, , etc) @@ -375,7 +375,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { tlist.removeItem(N - 1); tlist.removeItem(N - 2); tlist.removeItem(N - 3); - } else if (N >= 3 && tlist.getItem(N - 1).type == 1) { + } else if (N >= 3 && tlist.getItem(N - 1).type === 1) { operation = 3; // scale m = svgedit.math.transformListToTransform(tlist).matrix; var e2t = svgroot.createSVGTransform(); @@ -385,8 +385,8 @@ svgedit.recalculate.recalculateDimensions = function (selected) { // next, check if the first transform was a translate // if we had [ T1 ] [ M ] we want to transform this into [ M ] [ T2 ] // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] - } else if ((N == 1 || (N > 1 && tlist.getItem(1).type != 3)) && - tlist.getItem(0).type == 2) { + } else if ((N === 1 || (N > 1 && tlist.getItem(1).type !== 3)) && + tlist.getItem(0).type === 2) { operation = 2; // translate var T_M = svgedit.math.transformListToTransform(tlist).matrix; tlist.removeItem(0); @@ -396,7 +396,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { tx = M2.e; ty = M2.f; - if (tx != 0 || ty != 0) { + if (tx !== 0 || ty !== 0) { // we pass the translates down to the individual children var children = selected.childNodes; var c = children.length; @@ -438,7 +438,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { var u = uses.length; while (u--) { var useElem = uses.item(u); - if (href == svgedit.utilities.getHref(useElem)) { + if (href === svgedit.utilities.getHref(useElem)) { var usexlate = svgroot.createSVGTransform(); usexlate.setTranslate(-tx, -ty); svgedit.transformlist.getTransformList(useElem).insertItemBefore(usexlate, 0); @@ -455,7 +455,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { } // else, a matrix imposition from a parent group // keep pushing it down to the children - } else if (N == 1 && tlist.getItem(0).type == 1 && !gangle) { + } else if (N === 1 && tlist.getItem(0).type === 1 && !gangle) { operation = 1; var m = tlist.getItem(0).matrix, children = selected.childNodes, @@ -499,14 +499,14 @@ svgedit.recalculate.recalculateDimensions = function (selected) { tlist.appendItem(newRot); } } - if (tlist.numberOfItems == 0) { + if (tlist.numberOfItems === 0) { selected.removeAttribute('transform'); } return null; } // if it was a translate, put back the rotate at the new center - if (operation == 2) { + if (operation === 2) { if (gangle) { newcenter = { x: oldcenter.x + firstM.e, @@ -522,7 +522,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { } } // if it was a resize - } else if (operation == 3) { + } else if (operation === 3) { var m = svgedit.math.transformListToTransform(tlist).matrix; var roldt = svgroot.createSVGTransform(); roldt.setRotate(gangle, oldcenter.x, oldcenter.y); @@ -536,14 +536,14 @@ svgedit.recalculate.recalculateDimensions = function (selected) { tx = extrat.e; ty = extrat.f; - if (tx != 0 || ty != 0) { + if (tx !== 0 || ty !== 0) { // now push this transform down to the children // we pass the translates down to the individual children var children = selected.childNodes; var c = children.length; while (c--) { var child = children.item(c); - if (child.nodeType == 1) { + if (child.nodeType === 1) { var oldStartTransform = context_.getStartTransform(); context_.setStartTransform(child.getAttribute('transform')); var childTlist = svgedit.transformlist.getTransformList(child); @@ -579,7 +579,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { // TODO: Figure out how to get BBox from these elements in case they // have a rotation transform - if (!box && selected.tagName != 'path') return null; + if (!box && selected.tagName !== 'path') return null; var m = svgroot.createSVGMatrix(), // temporarily strip off the rotate and save the old center @@ -598,7 +598,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { } for (var i = 0; i < tlist.numberOfItems; ++i) { var xform = tlist.getItem(i); - if (xform.type == 4) { + if (xform.type === 4) { // extract old center through mystical arts var rm = xform.matrix; oldcenter.y = (s * rm.e + rm.f) / 2; @@ -639,8 +639,8 @@ svgedit.recalculate.recalculateDimensions = function (selected) { // transform will be the [S] // if we had [M][T][S][T] we want to extract the matrix equivalent of // [T][S][T] and push it down to the element - if (N >= 3 && tlist.getItem(N - 2).type == 3 && - tlist.getItem(N - 3).type == 2 && tlist.getItem(N - 1).type == 2) { + if (N >= 3 && tlist.getItem(N - 2).type === 3 && + tlist.getItem(N - 3).type === 2 && tlist.getItem(N - 1).type === 2) { // Removed this so a with a given [T][S][T] would convert to a matrix. // Is that bad? // && selected.nodeName != 'use' @@ -651,7 +651,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { tlist.removeItem(N - 3); // if we had [T][S][-T][M], then this was a skewed element being resized // Thus, we simply combine it all into one matrix - } else if (N == 4 && tlist.getItem(N - 1).type == 1) { + } else if (N === 4 && tlist.getItem(N - 1).type === 1) { operation = 3; // scale m = svgedit.math.transformListToTransform(tlist).matrix; var e2t = svgroot.createSVGTransform(); @@ -664,8 +664,8 @@ svgedit.recalculate.recalculateDimensions = function (selected) { // if we had [T1][M] we want to transform this into [M][T2] // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] and we can push [T2] // down to the element - } else if ((N == 1 || (N > 1 && tlist.getItem(1).type != 3)) && - tlist.getItem(0).type == 2) { + } else if ((N === 1 || (N > 1 && tlist.getItem(1).type !== 3)) && + tlist.getItem(0).type === 2) { operation = 2; // translate var oldxlate = tlist.getItem(0).matrix, meq = svgedit.math.transformListToTransform(tlist, 1).matrix, @@ -674,7 +674,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { tlist.removeItem(0); // else if this child now has a matrix imposition (from a parent group) // we might be able to simplify - } else if (N == 1 && tlist.getItem(0).type == 1 && !angle) { + } else if (N === 1 && tlist.getItem(0).type === 1 && !angle) { // Remap all point-based elements m = svgedit.math.transformListToTransform(tlist).matrix; switch (selected.tagName) { @@ -716,19 +716,19 @@ svgedit.recalculate.recalculateDimensions = function (selected) { tlist.appendItem(newRot); } } - if (tlist.numberOfItems == 0) { + if (tlist.numberOfItems === 0) { selected.removeAttribute('transform'); } return null; } // if it was a translate or resize, we need to remap the element and absorb the xform - if (operation == 1 || operation == 2 || operation == 3) { + if (operation === 1 || operation === 2 || operation === 3) { svgedit.coords.remapElement(selected, changes, m); } // if we are remapping // if it was a translate, put back the rotate at the new center - if (operation == 2) { + if (operation === 2) { if (angle) { if (!svgedit.math.hasMatrixTransform(tlist)) { newcenter = { @@ -747,12 +747,12 @@ svgedit.recalculate.recalculateDimensions = function (selected) { // We have special processing for tspans: Tspans are not transformable // but they can have x,y coordinates (sigh). Thus, if this was a translate, // on a text element, also translate any tspan children. - if (selected.tagName == 'text') { + if (selected.tagName === 'text') { var children = selected.childNodes; var c = children.length; while (c--) { var child = children.item(c); - if (child.tagName == 'tspan') { + if (child.tagName === 'tspan') { var tspanChanges = { x: $(child).attr('x') || 0, y: $(child).attr('y') || 0 @@ -765,7 +765,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { // we want it to be [Rnew][M][Tr] where Tr is the // translation required to re-center it // Therefore, [Tr] = [M_inv][Rnew_inv][Rold][M] - } else if (operation == 3 && angle) { + } else if (operation === 3 && angle) { var m = svgedit.math.transformListToTransform(tlist).matrix; var roldt = svgroot.createSVGTransform(); roldt.setRotate(angle, oldcenter.x, oldcenter.y); @@ -788,7 +788,7 @@ svgedit.recalculate.recalculateDimensions = function (selected) { } // a non-group // if the transform list has been emptied, remove it - if (tlist.numberOfItems == 0) { + if (tlist.numberOfItems === 0) { selected.removeAttribute('transform'); } diff --git a/editor/sanitize.js b/editor/sanitize.js index 85a02b28..8c237bc3 100644 --- a/editor/sanitize.js +++ b/editor/sanitize.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals $, svgedit */ /** * Package: svgedit.sanitize @@ -104,7 +104,7 @@ $.each(svgWhiteList_, function (elt, atts) { var v = att.split(':'); attNS[v[1]] = NS[(v[0]).toUpperCase()]; } else { - attNS[att] = att == 'xmlns' ? NS.XMLNS : null; + attNS[att] = att === 'xmlns' ? NS.XMLNS : null; } }); svgWhiteListNS_[elt] = attNS; @@ -118,7 +118,7 @@ $.each(svgWhiteList_, function (elt, atts) { // node - The DOM element to be checked (we'll also check its children) svgedit.sanitize.sanitizeSvg = function (node) { // Cleanup text nodes - if (node.nodeType == 3) { // 3 == TEXT_NODE + if (node.nodeType === 3) { // 3 == TEXT_NODE // Trim whitespace node.nodeValue = node.nodeValue.replace(/^\s+|\s+$/g, ''); // Remove if empty @@ -129,7 +129,7 @@ svgedit.sanitize.sanitizeSvg = function (node) { // We only care about element nodes. // Automatically return for all non-element nodes, such as comments, etc. - if (node.nodeType != 1) { // 1 == ELEMENT_NODE + if (node.nodeType !== 1) { // 1 == ELEMENT_NODE return; } @@ -156,8 +156,8 @@ svgedit.sanitize.sanitizeSvg = function (node) { var attrNsURI = attr.namespaceURI; // Check that an attribute with the correct localName in the correct namespace is on // our whitelist or is a namespace declaration for one of our allowed namespaces - if (!(allowedAttrsNS.hasOwnProperty(attrLocalName) && attrNsURI == allowedAttrsNS[attrLocalName] && attrNsURI != NS.XMLNS) && - !(attrNsURI == NS.XMLNS && REVERSE_NS[attr.value])) { + if (!(allowedAttrsNS.hasOwnProperty(attrLocalName) && attrNsURI === allowedAttrsNS[attrLocalName] && attrNsURI !== NS.XMLNS) && + !(attrNsURI === NS.XMLNS && REVERSE_NS[attr.value])) { // TODO(codedread): Programmatically add the se: attributes to the NS-aware whitelist. // Bypassing the whitelist to allow se: prefixes. // Is there a more appropriate way to do this? @@ -180,7 +180,7 @@ svgedit.sanitize.sanitizeSvg = function (node) { } // For the style attribute, rewrite it in terms of XML presentational attributes - if (attrName == 'style') { + if (attrName === 'style') { var props = attr.value.split(';'), p = props.length; while (p--) { @@ -207,7 +207,7 @@ svgedit.sanitize.sanitizeSvg = function (node) { ['filter', 'linearGradient', 'pattern', 'radialGradient', 'textPath', 'use'].indexOf(node.nodeName) >= 0) { // TODO: we simply check if the first character is a #, is this bullet-proof? - if (href[0] != '#') { + if (href[0] !== '#') { // remove the attribute (but keep the element) svgedit.utilities.setHref(node, ''); node.removeAttributeNS(NS.XLINK, 'href'); @@ -215,7 +215,7 @@ svgedit.sanitize.sanitizeSvg = function (node) { } // Safari crashes on a without a xlink:href, so we just remove the node here - if (node.nodeName == 'use' && !svgedit.utilities.getHref(node)) { + if (node.nodeName === 'use' && !svgedit.utilities.getHref(node)) { parent.removeChild(node); return; } diff --git a/editor/select.js b/editor/select.js index 285ac362..661bd863 100644 --- a/editor/select.js +++ b/editor/select.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals $, svgedit */ /** * Package: svedit.select @@ -458,7 +458,7 @@ svgedit.select.SelectorManager.prototype.releaseSelector = function (elem) { console.log('WARNING! selector was released but was already unlocked'); } for (i = 0; i < N; ++i) { - if (this.selectors[i] && this.selectors[i] == sel) { + if (this.selectors[i] && this.selectors[i] === sel) { delete this.selectorMap[elem.id]; sel.locked = false; sel.selectedElement = null; diff --git a/editor/svgcanvas.js b/editor/svgcanvas.js index 91caf2f5..dcd9a246 100644 --- a/editor/svgcanvas.js +++ b/editor/svgcanvas.js @@ -1,5 +1,5 @@ -/* eslint-disable no-var */ -/* globals $, svgedit, svgCanvas, jsPDF */ +/* eslint-disable no-var, indent, no-redeclare */ +/* globals $, svgedit, svgCanvas, jsPDF, canvg */ /* * svgcanvas.js * @@ -28,18 +28,16 @@ // 14) recalculate.js (function () { - if (!window.console) { window.console = {}; - window.console.log = function(str) {}; - window.console.dir = function(str) {}; + window.console.log = function (str) {}; + window.console.dir = function (str) {}; } if (window.opera) { - window.console.log = function(str) { opera.postError(str); }; - window.console.dir = function(str) {}; + window.console.log = function (str) { opera.postError(str); }; + window.console.dir = function (str) {}; } - }()); // Class: SvgCanvas @@ -75,26 +73,28 @@ var svgdoc = container.ownerDocument; // This is a container for the document being edited, not the document itself. var svgroot = svgdoc.importNode(svgedit.utilities.text2xml( - '' + - '' + - '' + - ''+ - ''+ - ''+ - ''+ - ''+ - ''+ - ''+ - ''+ - '').documentElement, true); + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '').documentElement, + true +); container.appendChild(svgroot); // The actual element that represents the final output SVG element var svgcontent = svgdoc.createElementNS(NS.SVG, 'svg'); // This function resets the svgcontent element while keeping it in the DOM. -var clearSvgContentElement = canvas.clearSvgContentElement = function() { +var clearSvgContentElement = canvas.clearSvgContentElement = function () { while (svgcontent.firstChild) { svgcontent.removeChild(svgcontent.firstChild); } // TODO: Clear out all other attributes first? @@ -111,7 +111,7 @@ var clearSvgContentElement = canvas.clearSvgContentElement = function() { }).appendTo(svgroot); // TODO: make this string optional and set by the client - var comment = svgdoc.createComment(" Created with SVG-edit - https://github.com/SVG-Edit/svgedit"); + var comment = svgdoc.createComment(' Created with SVG-edit - https://github.com/SVG-Edit/svgedit'); svgcontent.appendChild(comment); }; clearSvgContentElement(); @@ -124,7 +124,7 @@ var idprefix = 'svg_'; // // Parameters: // p - String with the new prefix -canvas.setIdPrefix = function(p) { +canvas.setIdPrefix = function (p) { idprefix = p; }; @@ -135,20 +135,20 @@ canvas.current_drawing_ = new svgedit.draw.Drawing(svgcontent, idprefix); // Function: getCurrentDrawing // Returns the current Drawing. // @return {svgedit.draw.Drawing} -var getCurrentDrawing = canvas.getCurrentDrawing = function() { +var getCurrentDrawing = canvas.getCurrentDrawing = function () { return canvas.current_drawing_; }; // Float displaying the current zoom level (1 = 100%, .5 = 50%, etc) -var current_zoom = 1; +var currentZoom = 1; // pointer to current group (for in-group editing) -var current_group = null; +var currentGroup = null; // Object containing data for the currently selected styles -var all_properties = { +var allProperties = { shape: { - fill: (curConfig.initFill.color == 'none' ? '' : '#') + curConfig.initFill.color, + fill: (curConfig.initFill.color === 'none' ? '' : '#') + curConfig.initFill.color, fill_paint: null, fill_opacity: curConfig.initFill.opacity, stroke: '#' + curConfig.initStroke.color, @@ -162,8 +162,8 @@ var all_properties = { } }; -all_properties.text = $.extend(true, {}, all_properties.shape); -$.extend(all_properties.text, { +allProperties.text = $.extend(true, {}, allProperties.shape); +$.extend(allProperties.text, { fill: '#000000', stroke_width: curConfig.text.stroke_width, font_size: curConfig.text.font_size, @@ -171,35 +171,35 @@ $.extend(all_properties.text, { }); // Current shape style properties -var cur_shape = all_properties.shape; +var curShape = allProperties.shape; // Array with all the currently selected elements // default size of 1 until it needs to grow bigger var selectedElements = []; -var getJsonFromSvgElement = this.getJsonFromSvgElement = function(data) { +var getJsonFromSvgElement = this.getJsonFromSvgElement = function (data) { // Text node - if(data.nodeType == 3) return data.nodeValue; + if (data.nodeType === 3) return data.nodeValue; var retval = { element: data.tagName, - //namespace: nsMap[data.namespaceURI], + // namespace: nsMap[data.namespaceURI], attr: {}, - children: [], + children: [] }; // Iterate attributes - for(var i=0; i < data.attributes.length; i++) { + for (var i = 0; i < data.attributes.length; i++) { retval.attr[data.attributes[i].name] = data.attributes[i].value; }; // Iterate children - for(var i=0; i < data.childNodes.length; i++) { + for (var i = 0; i < data.childNodes.length; i++) { retval.children.push(getJsonFromSvgElement(data.childNodes[i])); } return retval; -} +}; // Function: addSvgElementFromJson // Create a new SVG element based on the given object keys/values and add it to the current layer @@ -213,33 +213,33 @@ var getJsonFromSvgElement = this.getJsonFromSvgElement = function(data) { // * children - Optional array with data objects to be added recursively as children // // Returns: The new element -var addSvgElementFromJson = this.addSvgElementFromJson = function(data) { - if (typeof(data) == 'string') return svgdoc.createTextNode(data); +var addSvgElementFromJson = this.addSvgElementFromJson = function (data) { + if (typeof data === 'string') return svgdoc.createTextNode(data); var shape = svgedit.utilities.getElem(data.attr.id); // if shape is a path but we need to create a rect/ellipse, then remove the path - var current_layer = getCurrentDrawing().getCurrentLayer(); - if (shape && data.element != shape.tagName) { - current_layer.removeChild(shape); + var currentLayer = getCurrentDrawing().getCurrentLayer(); + if (shape && data.element !== shape.tagName) { + currentLayer.removeChild(shape); shape = null; } if (!shape) { shape = svgdoc.createElementNS(NS.SVG, data.element); - if (current_layer) { - (current_group || current_layer).appendChild(shape); + if (currentLayer) { + (currentGroup || currentLayer).appendChild(shape); } } if (data.curStyles) { svgedit.utilities.assignAttributes(shape, { - 'fill': cur_shape.fill, - 'stroke': cur_shape.stroke, - 'stroke-width': cur_shape.stroke_width, - 'stroke-dasharray': cur_shape.stroke_dasharray, - 'stroke-linejoin': cur_shape.stroke_linejoin, - 'stroke-linecap': cur_shape.stroke_linecap, - 'stroke-opacity': cur_shape.stroke_opacity, - 'fill-opacity': cur_shape.fill_opacity, - 'opacity': cur_shape.opacity / 2, + 'fill': curShape.fill, + 'stroke': curShape.stroke, + 'stroke-width': curShape.stroke_width, + 'stroke-dasharray': curShape.stroke_dasharray, + 'stroke-linejoin': curShape.stroke_linejoin, + 'stroke-linecap': curShape.stroke_linecap, + 'stroke-opacity': curShape.stroke_opacity, + 'fill-opacity': curShape.fill_opacity, + 'opacity': curShape.opacity / 2, 'style': 'pointer-events:inherit' }, 100); } @@ -248,7 +248,7 @@ var addSvgElementFromJson = this.addSvgElementFromJson = function(data) { // Children if (data.children) { - data.children.forEach(function(child) { + data.children.forEach(function (child) { shape.appendChild(addSvgElementFromJson(child)); }); } @@ -257,63 +257,63 @@ var addSvgElementFromJson = this.addSvgElementFromJson = function(data) { }; // import svgtransformlist.js -var getTransformList = canvas.getTransformList = svgedit.transformlist.getTransformList; +/* var getTransformList = */ canvas.getTransformList = svgedit.transformlist.getTransformList; // import from math.js. var transformPoint = svgedit.math.transformPoint; var matrixMultiply = canvas.matrixMultiply = svgedit.math.matrixMultiply; var hasMatrixTransform = canvas.hasMatrixTransform = svgedit.math.hasMatrixTransform; var transformListToTransform = canvas.transformListToTransform = svgedit.math.transformListToTransform; -var snapToAngle = svgedit.math.snapToAngle; -var getMatrix = svgedit.math.getMatrix; +// var snapToAngle = svgedit.math.snapToAngle; +// var getMatrix = svgedit.math.getMatrix; // initialize from units.js // send in an object implementing the ElementContainer interface (see units.js) svgedit.units.init({ - getBaseUnit: function() { return curConfig.baseUnit; }, + getBaseUnit: function () { return curConfig.baseUnit; }, getElement: svgedit.utilities.getElem, - getHeight: function() { return svgcontent.getAttribute('height')/current_zoom; }, - getWidth: function() { return svgcontent.getAttribute('width')/current_zoom; }, - getRoundDigits: function() { return save_options.round_digits; } + getHeight: function () { return svgcontent.getAttribute('height') / currentZoom; }, + getWidth: function () { return svgcontent.getAttribute('width') / currentZoom; }, + getRoundDigits: function () { return saveOptions.round_digits; } }); // import from units.js -var convertToNum = canvas.convertToNum = svgedit.units.convertToNum; +/* var convertToNum = */ canvas.convertToNum = svgedit.units.convertToNum; // import from svgutils.js svgedit.utilities.init({ - getDOMDocument: function() { return svgdoc; }, - getDOMContainer: function() { return container; }, - getSVGRoot: function() { return svgroot; }, + getDOMDocument: function () { return svgdoc; }, + getDOMContainer: function () { return container; }, + getSVGRoot: function () { return svgroot; }, // TODO: replace this mostly with a way to get the current drawing. - getSelectedElements: function() { return selectedElements; }, - getSVGContent: function() { return svgcontent; }, - getBaseUnit: function() { return curConfig.baseUnit; }, - getSnappingStep: function() { return curConfig.snappingStep; } + getSelectedElements: function () { return selectedElements; }, + getSVGContent: function () { return svgcontent; }, + getBaseUnit: function () { return curConfig.baseUnit; }, + getSnappingStep: function () { return curConfig.snappingStep; } }); var findDefs = canvas.findDefs = svgedit.utilities.findDefs; var getUrlFromAttr = canvas.getUrlFromAttr = svgedit.utilities.getUrlFromAttr; var getHref = canvas.getHref = svgedit.utilities.getHref; var setHref = canvas.setHref = svgedit.utilities.setHref; var getPathBBox = svgedit.utilities.getPathBBox; -var getBBox = canvas.getBBox = svgedit.utilities.getBBox; -var getRotationAngle = canvas.getRotationAngle = svgedit.utilities.getRotationAngle; +/* var getBBox = */ canvas.getBBox = svgedit.utilities.getBBox; +/* var getRotationAngle = */ canvas.getRotationAngle = svgedit.utilities.getRotationAngle; var getElem = canvas.getElem = svgedit.utilities.getElem; -var getRefElem = canvas.getRefElem = svgedit.utilities.getRefElem; +/* var getRefElem = */ canvas.getRefElem = svgedit.utilities.getRefElem; var assignAttributes = canvas.assignAttributes = svgedit.utilities.assignAttributes; var cleanupElement = this.cleanupElement = svgedit.utilities.cleanupElement; // import from coords.js svgedit.coords.init({ - getDrawing: function() { return getCurrentDrawing(); }, - getGridSnapping: function() { return curConfig.gridSnapping; } + getDrawing: function () { return getCurrentDrawing(); }, + getGridSnapping: function () { return curConfig.gridSnapping; } }); var remapElement = this.remapElement = svgedit.coords.remapElement; // import from recalculate.js svgedit.recalculate.init({ - getSVGRoot: function() { return svgroot; }, - getStartTransform: function() { return startTransform; }, - setStartTransform: function(transform) { startTransform = transform; } + getSVGRoot: function () { return svgroot; }, + getStartTransform: function () { return startTransform; }, + setStartTransform: function (transform) { startTransform = transform; } }); var recalculateDimensions = this.recalculateDimensions = svgedit.recalculate.recalculateDimensions; @@ -330,38 +330,40 @@ var BatchCommand = svgedit.history.BatchCommand; var call; // Implement the svgedit.history.HistoryEventHandler interface. canvas.undoMgr = new svgedit.history.UndoManager({ - handleHistoryEvent: function(eventType, cmd) { + handleHistoryEvent: function (eventType, cmd) { var EventTypes = svgedit.history.HistoryEventTypes; // TODO: handle setBlurOffsets. - if (eventType == EventTypes.BEFORE_UNAPPLY || eventType == EventTypes.BEFORE_APPLY) { + if (eventType === EventTypes.BEFORE_UNAPPLY || eventType === EventTypes.BEFORE_APPLY) { canvas.clearSelection(); - } else if (eventType == EventTypes.AFTER_APPLY || eventType == EventTypes.AFTER_UNAPPLY) { + } else if (eventType === EventTypes.AFTER_APPLY || eventType === EventTypes.AFTER_UNAPPLY) { var elems = cmd.elements(); canvas.pathActions.clear(); call('changed', elems); var cmdType = cmd.type(); - var isApply = (eventType == EventTypes.AFTER_APPLY); - if (cmdType == MoveElementCommand.type()) { + var isApply = (eventType === EventTypes.AFTER_APPLY); + if (cmdType === MoveElementCommand.type()) { var parent = isApply ? cmd.newParent : cmd.oldParent; - if (parent == svgcontent) { + if (parent === svgcontent) { canvas.identifyLayers(); } - } else if (cmdType == InsertElementCommand.type() || - cmdType == RemoveElementCommand.type()) { - if (cmd.parent == svgcontent) { + } else if (cmdType === InsertElementCommand.type() || + cmdType === RemoveElementCommand.type()) { + if (cmd.parent === svgcontent) { canvas.identifyLayers(); } - if (cmdType == InsertElementCommand.type()) { - if (isApply) {restoreRefElems(cmd.elem);} + if (cmdType === InsertElementCommand.type()) { + if (isApply) { restoreRefElems(cmd.elem); } } else { - if (!isApply) {restoreRefElems(cmd.elem);} + if (!isApply) { restoreRefElems(cmd.elem); } } if (cmd.elem.tagName === 'use') { setUseData(cmd.elem); } - } else if (cmdType == ChangeElementCommand.type()) { + } else if (cmdType === ChangeElementCommand.type()) { // if we are changing layer names, re-identify all layers - if (cmd.elem.tagName == 'title' && cmd.elem.parentNode.parentNode == svgcontent) { + if (cmd.elem.tagName === 'title' && + cmd.elem.parentNode.parentNode === svgcontent + ) { canvas.identifyLayers(); } var values = isApply ? cmd.newValues : cmd.oldValues; @@ -373,7 +375,7 @@ canvas.undoMgr = new svgedit.history.UndoManager({ // have a featured detection for correct 'use' behavior? // —————————— // Remove & Re-add hack for Webkit (issue 775) - //if (cmd.elem.tagName === 'use' && svgedit.browser.isWebkit()) { + // if (cmd.elem.tagName === 'use' && svgedit.browser.isWebkit()) { // var elem = cmd.elem; // if (!elem.getAttribute('x') && !elem.getAttribute('y')) { // var parent = elem.parentNode; @@ -381,12 +383,12 @@ canvas.undoMgr = new svgedit.history.UndoManager({ // parent.removeChild(elem); // parent.insertBefore(elem, sib); // } - //} + // } } } } }); -var addCommandToHistory = function(cmd) { +var addCommandToHistory = function (cmd) { canvas.undoMgr.addCommandToHistory(cmd); }; @@ -395,54 +397,54 @@ var addCommandToHistory = function(cmd) { * @param {svgedit.history.HistoryRecordingService=} hrService - if exists, return it instead of creating a new service. * @returns {svgedit.history.HistoryRecordingService} */ -function historyRecordingService(hrService) { - return hrService ? hrService : new svgedit.history.HistoryRecordingService(canvas.undoMgr); +function historyRecordingService (hrService) { + return hrService || new svgedit.history.HistoryRecordingService(canvas.undoMgr); } // import from select.js svgedit.select.init(curConfig, { - createSVGElement: function(jsonMap) { return canvas.addSvgElementFromJson(jsonMap); }, - svgRoot: function() { return svgroot; }, - svgContent: function() { return svgcontent; }, - currentZoom: function() { return current_zoom; }, + createSVGElement: function (jsonMap) { return canvas.addSvgElementFromJson(jsonMap); }, + svgRoot: function () { return svgroot; }, + svgContent: function () { return svgcontent; }, + currentZoom: function () { return currentZoom; }, // TODO(codedread): Remove when getStrokedBBox() has been put into svgutils.js. - getStrokedBBox: function(elems) { return canvas.getStrokedBBox([elems]); } + getStrokedBBox: function (elems) { return canvas.getStrokedBBox([elems]); } }); // this object manages selectors for us var selectorManager = this.selectorManager = svgedit.select.getSelectorManager(); // Import from path.js svgedit.path.init({ - getCurrentZoom: function() { return current_zoom; }, - getSVGRoot: function() { return svgroot; } + getCurrentZoom: function () { return currentZoom; }, + getSVGRoot: function () { return svgroot; } }); // Interface strings, usually for title elements var uiStrings = { - exportNoBlur: "Blurred elements will appear as un-blurred", - exportNoforeignObject: "foreignObject elements will not appear", - exportNoDashArray: "Strokes will appear filled", - exportNoText: "Text may not appear as expected" + exportNoBlur: 'Blurred elements will appear as un-blurred', + exportNoforeignObject: 'foreignObject elements will not appear', + exportNoDashArray: 'Strokes will appear filled', + exportNoText: 'Text may not appear as expected' }; var visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use'; -var ref_attrs = ['clip-path', 'fill', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke']; +var refAttrs = ['clip-path', 'fill', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke']; var elData = $.data; // Animation element to change the opacity of any newly created element -var opac_ani = document.createElementNS(NS.SVG, 'animate'); -$(opac_ani).attr({ +var opacAni = document.createElementNS(NS.SVG, 'animate'); +$(opacAni).attr({ attributeName: 'opacity', begin: 'indefinite', dur: 1, fill: 'freeze' }).appendTo(svgroot); -var restoreRefElems = function(elem) { +var restoreRefElems = function (elem) { // Look for missing reference elements, restore any found var o, i, l, - attrs = $(elem).attr(ref_attrs); + attrs = $(elem).attr(refAttrs); for (o in attrs) { var val = attrs[o]; if (val && val.indexOf('url(') === 0) { @@ -464,7 +466,7 @@ var restoreRefElems = function(elem) { } }; -(function() { +(function () { // TODO For Issue 208: this is a start on a thumbnail // var svgthumb = svgdoc.createElementNS(NS.SVG, 'use'); // svgthumb.setAttribute('width', '100'); @@ -478,13 +480,13 @@ var restoreRefElems = function(elem) { var encodableImages = {}, // String with image URL of last loadable image - last_good_img_url = curConfig.imgPath + 'logo.png', + lastGoodImgUrl = curConfig.imgPath + 'logo.png', // Array with current disabled elements (for in-group editing) - disabled_elems = [], + disabledElems = [], // Object with save options - save_options = {round_digits: 5}, + saveOptions = {round_digits: 5}, // Boolean indicating whether or not a draw action has been started started = false, @@ -493,19 +495,19 @@ var encodableImages = {}, startTransform = null, // String indicating the current editor mode - current_mode = 'select', + currentMode = 'select', // String with the current direction in which an element is being resized - current_resize_mode = 'none', + currentResizeMode = 'none', // Object with IDs for imported files, to see if one was already added - import_ids = {}, + importIds = {}, // Current text style properties - cur_text = all_properties.text, + curText = allProperties.text, // Current general properties - cur_properties = cur_shape, + curProperties = curShape, // Array with selected elements' Bounding box object // selectedBBoxes = new Array(1), @@ -529,9 +531,9 @@ var encodableImages = {}, removedElements = {}; // Should this return an array by default, so extension results aren't overwritten? -var runExtensions = this.runExtensions = function(action, vars, returnArray) { +var runExtensions = this.runExtensions = function (action, vars, returnArray) { var result = returnArray ? [] : false; - $.each(extensions, function(name, opts) { + $.each(extensions, function (name, opts) { if (opts && action in opts) { if (returnArray) { result.push(opts[action](vars)); @@ -548,20 +550,20 @@ var runExtensions = this.runExtensions = function(action, vars, returnArray) { // // Parameters: // name - String with the ID of the extension -// ext_func - Function supplied by the extension with its data -this.addExtension = function(name, ext_func) { +// extFunc - Function supplied by the extension with its data +this.addExtension = function (name, extFunc) { var ext; if (!(name in extensions)) { // Provide private vars/funcs here. Is there a better way to do this? - if ($.isFunction(ext_func)) { - ext = ext_func($.extend(canvas.getPrivateMethods(), { + if ($.isFunction(extFunc)) { + ext = extFunc($.extend(canvas.getPrivateMethods(), { svgroot: svgroot, svgcontent: svgcontent, nonce: getCurrentDrawing().getNonce(), selectorManager: selectorManager })); } else { - ext = ext_func; + ext = extFunc; } extensions[name] = ext; call('extension_added', ext); @@ -570,22 +572,22 @@ this.addExtension = function(name, ext_func) { } }; -// This method rounds the incoming value to the nearest value based on the current_zoom -var round = this.round = function(val) { - return parseInt(val*current_zoom, 10)/current_zoom; +// This method rounds the incoming value to the nearest value based on the currentZoom +var round = this.round = function (val) { + return parseInt(val * currentZoom, 10) / currentZoom; }; // This method sends back an array or a NodeList full of elements that -// intersect the multi-select rubber-band-box on the current_layer only. +// intersect the multi-select rubber-band-box on the currentLayer only. // // We brute-force getIntersectionList for browsers that do not support it (Firefox). // // Reference: // Firefox does not implement getIntersectionList(), see https://bugzilla.mozilla.org/show_bug.cgi?id=501421 -var getIntersectionList = this.getIntersectionList = function(rect) { +var getIntersectionList = this.getIntersectionList = function (rect) { if (rubberBox == null) { return null; } - var parent = current_group || getCurrentDrawing().getCurrentLayer(); + var parent = currentGroup || getCurrentDrawing().getCurrentLayer(); var rubberBBox; if (!rect) { @@ -593,7 +595,7 @@ var getIntersectionList = this.getIntersectionList = function(rect) { var o, bb = svgcontent.createSVGRect(); for (o in rubberBBox) { - bb[o] = rubberBBox[o] / current_zoom; + bb[o] = rubberBBox[o] / currentZoom; } rubberBBox = bb; } else { @@ -606,7 +608,7 @@ var getIntersectionList = this.getIntersectionList = function(rect) { var resultList = null; if (!svgedit.browser.isIE) { - if (typeof(svgroot.getIntersectionList) == 'function') { + if (typeof svgroot.getIntersectionList === 'function') { // Offset the bbox of the rubber box by the offset of the svgcontent element. rubberBBox.x += parseInt(svgcontent.getAttribute('x'), 10); rubberBBox.y += parseInt(svgcontent.getAttribute('y'), 10); @@ -615,7 +617,7 @@ var getIntersectionList = this.getIntersectionList = function(rect) { } } - if (resultList == null || typeof(resultList.item) != 'function') { + if (resultList == null || typeof resultList.item !== 'function') { resultList = []; if (!curBBoxes.length) { @@ -624,7 +626,7 @@ var getIntersectionList = this.getIntersectionList = function(rect) { } var i = curBBoxes.length; while (i--) { - if (!rubberBBox.width) {continue;} + if (!rubberBBox.width) { continue; } if (svgedit.math.rectsIntersect(rubberBBox, curBBoxes[i].bbox)) { resultList.push(curBBoxes[i].elem); } @@ -646,9 +648,9 @@ var getIntersectionList = this.getIntersectionList = function(rect) { // // Returns: // A single bounding box object -var getStrokedBBox = this.getStrokedBBox = function(elems) { - if (!elems) {elems = getVisibleElements();} - return svgedit.utilities.getStrokedBBox(elems, addSvgElementFromJson, pathActions) +var getStrokedBBox = this.getStrokedBBox = function (elems) { + if (!elems) { elems = getVisibleElements(); } + return svgedit.utilities.getStrokedBBox(elems, addSvgElementFromJson, pathActions); }; // Function: getVisibleElements @@ -661,13 +663,13 @@ var getStrokedBBox = this.getStrokedBBox = function(elems) { // // Returns: // An array with all "visible" elements. -var getVisibleElements = this.getVisibleElements = function(parent) { +var getVisibleElements = this.getVisibleElements = function (parent) { if (!parent) { parent = $(svgcontent).children(); // Prevent layers from being included } var contentElems = []; - $(parent).children().each(function(i, elem) { + $(parent).children().each(function (i, elem) { if (elem.getBBox) { contentElems.push(elem); } @@ -687,14 +689,14 @@ var getVisibleElements = this.getVisibleElements = function(parent) { // An array with objects that include: // * elem - The element // * bbox - The element's BBox as retrieved from getStrokedBBox -var getVisibleElementsAndBBoxes = this.getVisibleElementsAndBBoxes = function(parent) { +var getVisibleElementsAndBBoxes = this.getVisibleElementsAndBBoxes = function (parent) { if (!parent) { parent = $(svgcontent).children(); // Prevent layers from being included } var contentElems = []; - $(parent).children().each(function(i, elem) { + $(parent).children().each(function (i, elem) { if (elem.getBBox) { - contentElems.push({'elem':elem, 'bbox':getStrokedBBox([elem])}); + contentElems.push({elem: elem, bbox: getStrokedBBox([elem])}); } }); return contentElems.reverse(); @@ -705,24 +707,22 @@ var getVisibleElementsAndBBoxes = this.getVisibleElementsAndBBoxes = function(pa // // Parameters: // elem - SVG element to wrap -var groupSvgElem = this.groupSvgElem = function(elem) { +var groupSvgElem = this.groupSvgElem = function (elem) { var g = document.createElementNS(NS.SVG, 'g'); elem.parentNode.replaceChild(g, elem); $(g).append(elem).data('gsvg', elem)[0].id = getNextId(); }; - // Set scope for these functions var getId, getNextId; var textActions, pathActions; -(function(c) { - +(function (c) { // Object to contain editor event names and callback functions var events = {}; - getId = c.getId = function() { return getCurrentDrawing().getId(); }; - getNextId = c.getNextId = function() { return getCurrentDrawing().getNextId(); }; + getId = c.getId = function () { return getCurrentDrawing().getId(); }; + getNextId = c.getNextId = function () { return getCurrentDrawing().getNextId(); }; // Function: call // Run the callback function associated with the given event @@ -730,7 +730,7 @@ var textActions, pathActions; // Parameters: // event - String with the event name // arg - Argument to pass through to the callback function - call = c.call = function(event, arg) { + call = c.call = function (event, arg) { if (events[event]) { return events[event](this, arg); } @@ -745,12 +745,11 @@ var textActions, pathActions; // // Return: // The previous event - c.bind = function(event, f) { + c.bind = function (event, f) { var old = events[event]; events[event] = f; return old; }; - }(canvas)); // Function: canvas.prepareSvg @@ -758,7 +757,7 @@ var textActions, pathActions; // // Parameters: // newDoc - The SVG DOM document -this.prepareSvg = function(newDoc) { +this.prepareSvg = function (newDoc) { this.sanitizeSvg(newDoc.documentElement); // convert paths into absolute commands @@ -780,8 +779,8 @@ this.prepareSvg = function(newDoc) { // // Parameters: // elem - The (text) DOM element to clone -var ffClone = function(elem) { - if (!svgedit.browser.isGecko()) {return elem;} +var ffClone = function (elem) { + if (!svgedit.browser.isGecko()) { return elem; } var clone = elem.cloneNode(true); elem.parentNode.insertBefore(clone, elem); elem.parentNode.removeChild(elem); @@ -791,15 +790,13 @@ var ffClone = function(elem) { return clone; }; - // this.each is deprecated, if any extension used this it can be recreated by doing this: // $(canvas.getRootElem()).children().each(...) -// this.each = function(cb) { +// this.each = function (cb) { // $(svgroot).children().each(cb); // }; - // Function: setRotationAngle // Removes any old rotations if present, prepends a new rotation at the // transformed center @@ -807,33 +804,33 @@ var ffClone = function(elem) { // Parameters: // val - The new rotation angle in degrees // preventUndo - Boolean indicating whether the action should be undoable or not -this.setRotationAngle = function(val, preventUndo) { +this.setRotationAngle = function (val, preventUndo) { // ensure val is the proper type val = parseFloat(val); var elem = selectedElements[0]; var oldTransform = elem.getAttribute('transform'); var bbox = svgedit.utilities.getBBox(elem); - var cx = bbox.x+bbox.width/2, cy = bbox.y+bbox.height/2; + var cx = bbox.x + bbox.width / 2, cy = bbox.y + bbox.height / 2; var tlist = svgedit.transformlist.getTransformList(elem); // only remove the real rotational transform if present (i.e. at index=0) if (tlist.numberOfItems > 0) { var xform = tlist.getItem(0); - if (xform.type == 4) { + if (xform.type === 4) { tlist.removeItem(0); } } - // find R_nc and insert it - if (val != 0) { + // find Rnc and insert it + if (val !== 0) { var center = svgedit.math.transformPoint(cx, cy, svgedit.math.transformListToTransform(tlist).matrix); - var R_nc = svgroot.createSVGTransform(); - R_nc.setRotate(val, center.x, center.y); + var Rnc = svgroot.createSVGTransform(); + Rnc.setRotate(val, center.x, center.y); if (tlist.numberOfItems) { - tlist.insertItemBefore(R_nc, 0); + tlist.insertItemBefore(Rnc, 0); } else { - tlist.appendItem(R_nc); + tlist.appendItem(Rnc); } - } else if (tlist.numberOfItems == 0) { + } else if (tlist.numberOfItems === 0) { elem.removeAttribute('transform'); } @@ -845,10 +842,10 @@ this.setRotationAngle = function(val, preventUndo) { changeSelectedAttribute('transform', newTransform, selectedElements); call('changed', selectedElements); } - var pointGripContainer = svgedit.utilities.getElem('pathpointgrip_container'); -// if (elem.nodeName == 'path' && pointGripContainer) { -// pathActions.setPointContainerTransform(elem.getAttribute('transform')); -// } + // var pointGripContainer = svgedit.utilities.getElem('pathpointgrip_container'); + // if (elem.nodeName === 'path' && pointGripContainer) { + // pathActions.setPointContainerTransform(elem.getAttribute('transform')); + // } var selector = selectorManager.requestSelector(selectedElements[0]); selector.resize(); selector.updateGripCursors(val); @@ -857,14 +854,14 @@ this.setRotationAngle = function(val, preventUndo) { // Function: recalculateAllSelectedDimensions // Runs recalculateDimensions on the selected elements, // adding the changes to a single batch command -var recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = function() { - var text = (current_resize_mode == 'none' ? 'position' : 'size'); +var recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = function () { + var text = (currentResizeMode === 'none' ? 'position' : 'size'); var batchCmd = new svgedit.history.BatchCommand(text); var i = selectedElements.length; while (i--) { var elem = selectedElements[i]; -// if (svgedit.utilities.getRotationAngle(elem) && !svgedit.math.hasMatrixTransform(getTransformList(elem))) {continue;} +// if (svgedit.utilities.getRotationAngle(elem) && !svgedit.math.hasMatrixTransform(getTransformList(elem))) { continue; } var cmd = svgedit.recalculate.recalculateDimensions(elem); if (cmd) { batchCmd.addSubCommand(cmd); @@ -877,14 +874,13 @@ var recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = f } }; - // Debug tool to easily see the current matrix in the browser's console -var logMatrix = function(m) { +var logMatrix = function (m) { console.log([m.a, m.b, m.c, m.d, m.e, m.f]); }; // Root Current Transformation Matrix in user units -var root_sctm = null; +var rootSctm = null; // Group: Selection @@ -892,28 +888,27 @@ var root_sctm = null; // Clears the selection. The 'selected' handler is then called. // Parameters: // noCall - Optional boolean that when true does not call the "selected" handler -var clearSelection = this.clearSelection = function(noCall) { - selectedElements.map(function(elem){ - if(elem == null) return; +var clearSelection = this.clearSelection = function (noCall) { + selectedElements.map(function (elem) { + if (elem == null) return; selectorManager.releaseSelector(elem); }); selectedElements = []; - if (!noCall) {call('selected', selectedElements);} + if (!noCall) { call('selected', selectedElements); } }; // TODO: do we need to worry about selectedBBoxes here? - // Function: addToSelection // Adds a list of elements to the selection. The 'selected' handler is then called. // // Parameters: // elemsToAdd - an array of DOM elements to add to the selection // showGrips - a boolean flag indicating whether the resize grips should be shown -var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) { - if (elemsToAdd.length == 0) { return; } +var addToSelection = this.addToSelection = function (elemsToAdd, showGrips) { + if (elemsToAdd.length === 0) { return; } // find the first null in our selectedElements array var j = 0; @@ -928,9 +923,9 @@ var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) { var i = elemsToAdd.length; while (i--) { var elem = elemsToAdd[i]; - if (!elem) {continue;} + if (!elem) { continue; } var bbox = svgedit.utilities.getBBox(elem); - if (!bbox) {continue;} + if (!bbox) { continue; } if (elem.tagName === 'a' && elem.childNodes.length === 1) { // Make "a" element's child be the selected element @@ -938,12 +933,11 @@ var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) { } // if it's not already there, add it - if (selectedElements.indexOf(elem) == -1) { - + if (selectedElements.indexOf(elem) === -1) { selectedElements[j] = elem; // only the first selectedBBoxes element is ever used in the codebase these days -// if (j == 0) selectedBBoxes[0] = svgedit.utilities.getBBox(elem); +// if (j === 0) selectedBBoxes[0] = svgedit.utilities.getBBox(elem); j++; var sel = selectorManager.requestSelector(elem, bbox); @@ -954,17 +948,16 @@ var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) { } call('selected', selectedElements); - if (showGrips || selectedElements.length == 1) { + if (showGrips || selectedElements.length === 1) { selectorManager.requestSelector(selectedElements[0]).showGrips(true); - } - else { + } else { selectorManager.requestSelector(selectedElements[0]).showGrips(false); } // make sure the elements are in the correct order // See: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition - selectedElements.sort(function(a, b) { + selectedElements.sort(function (a, b) { if (a && b && a.compareDocumentPosition) { return 3 - (b.compareDocumentPosition(a) & 6); } @@ -984,7 +977,7 @@ var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) { // // Parameters: // elems - an array of DOM elements to be selected -var selectOnly = this.selectOnly = function(elems, showGrips) { +var selectOnly = this.selectOnly = function (elems, showGrips) { clearSelection(true); addToSelection(elems, showGrips); }; @@ -997,9 +990,9 @@ var selectOnly = this.selectOnly = function(elems, showGrips) { // // Parameters: // elemsToRemove - an array of elements to remove from selection -var removeFromSelection = this.removeFromSelection = function(elemsToRemove) { +/* var removeFromSelection = */ this.removeFromSelection = function (elemsToRemove) { if (selectedElements[0] == null) { return; } - if (elemsToRemove.length == 0) { return; } + if (elemsToRemove.length === 0) { return; } // find every element and remove it from our array copy var i, @@ -1011,7 +1004,7 @@ var removeFromSelection = this.removeFromSelection = function(elemsToRemove) { var elem = selectedElements[i]; if (elem) { // keep the item - if (elemsToRemove.indexOf(elem) == -1) { + if (elemsToRemove.indexOf(elem) === -1) { newSelectedItems[j] = elem; j++; } else { // remove the item and its selector @@ -1025,11 +1018,11 @@ var removeFromSelection = this.removeFromSelection = function(elemsToRemove) { // Function: selectAllInCurrentLayer // Clears the selection, then adds all elements in the current layer to the selection. -this.selectAllInCurrentLayer = function() { - var current_layer = getCurrentDrawing().getCurrentLayer(); - if (current_layer) { - current_mode = 'select'; - selectOnly($(current_group || current_layer).children()); +this.selectAllInCurrentLayer = function () { + var currentLayer = getCurrentDrawing().getCurrentLayer(); + if (currentLayer) { + currentMode = 'select'; + selectOnly($(currentGroup || currentLayer).children()); } }; @@ -1041,68 +1034,70 @@ this.selectAllInCurrentLayer = function() { // // Returns: // DOM element we want -var getMouseTarget = this.getMouseTarget = function(evt) { +var getMouseTarget = this.getMouseTarget = function (evt) { if (evt == null) { return null; } - var mouse_target = evt.target; + var mouseTarget = evt.target; // if it was a , Opera and WebKit return the SVGElementInstance - if (mouse_target.correspondingUseElement) {mouse_target = mouse_target.correspondingUseElement;} + if (mouseTarget.correspondingUseElement) { mouseTarget = mouseTarget.correspondingUseElement; } // for foreign content, go up until we find the foreignObject // WebKit browsers set the mouse target to the svgcanvas div - if ([NS.MATH, NS.HTML].indexOf(mouse_target.namespaceURI) >= 0 && - mouse_target.id != 'svgcanvas') - { - while (mouse_target.nodeName != 'foreignObject') { - mouse_target = mouse_target.parentNode; - if (!mouse_target) {return svgroot;} + if ([NS.MATH, NS.HTML].indexOf(mouseTarget.namespaceURI) >= 0 && + mouseTarget.id !== 'svgcanvas' + ) { + while (mouseTarget.nodeName !== 'foreignObject') { + mouseTarget = mouseTarget.parentNode; + if (!mouseTarget) { return svgroot; } } } - // Get the desired mouse_target with jQuery selector-fu + // Get the desired mouseTarget with jQuery selector-fu // If it's root-like, select the root - var current_layer = getCurrentDrawing().getCurrentLayer(); - if ([svgroot, container, svgcontent, current_layer].indexOf(mouse_target) >= 0) { + var currentLayer = getCurrentDrawing().getCurrentLayer(); + if ([svgroot, container, svgcontent, currentLayer].indexOf(mouseTarget) >= 0) { return svgroot; } - var $target = $(mouse_target); + var $target = $(mouseTarget); // If it's a selection grip, return the grip parent if ($target.closest('#selectorParentGroup').length) { - // While we could instead have just returned mouse_target, + // While we could instead have just returned mouseTarget, // this makes it easier to indentify as being a selector grip return selectorManager.selectorParentGroup; } - while (mouse_target.parentNode !== (current_group || current_layer)) { - mouse_target = mouse_target.parentNode; + while (mouseTarget.parentNode !== (currentGroup || currentLayer)) { + mouseTarget = mouseTarget.parentNode; } -// -// // go up until we hit a child of a layer -// while (mouse_target.parentNode.parentNode.tagName == 'g') { -// mouse_target = mouse_target.parentNode; -// } + // + // // go up until we hit a child of a layer + // while (mouseTarget.parentNode.parentNode.tagName == 'g') { + // mouseTarget = mouseTarget.parentNode; + // } // Webkit bubbles the mouse event all the way up to the div, so we - // set the mouse_target to the svgroot like the other browsers -// if (mouse_target.nodeName.toLowerCase() == 'div') { -// mouse_target = svgroot; -// } + // set the mouseTarget to the svgroot like the other browsers + // if (mouseTarget.nodeName.toLowerCase() == 'div') { + // mouseTarget = svgroot; + // } - return mouse_target; + return mouseTarget; }; +var drawnPath = null; + // Mouse events -(function() { - var d_attr = null, - start_x = null, - start_y = null, - r_start_x = null, - r_start_y = null, - init_bbox = {}, +(function () { + var dAttr = null, + startX = null, + startY = null, + rStartX = null, + rStartY = null, + initBbox = {}, freehand = { minx: null, miny: null, @@ -1110,19 +1105,19 @@ var getMouseTarget = this.getMouseTarget = function(evt) { maxy: null }, sumDistance = 0, - controllPoint2 = {x:0, y:0}, - controllPoint1 = {x:0, y:0}, - start = {x:0, y:0}, - end = {x:0, y:0}, + controllPoint2 = {x: 0, y: 0}, + controllPoint1 = {x: 0, y: 0}, + start = {x: 0, y: 0}, + end = {x: 0, y: 0}, parameter, nextParameter, - bSpline = {x:0, y:0}, - nextPos = {x:0, y:0}, + bSpline = {x: 0, y: 0}, + nextPos = {x: 0, y: 0}, THRESHOLD_DIST = 0.8, STEP_COUNT = 10; - var getBsplinePoint = function(t) { - var spline = {x:0, y:0}, + var getBsplinePoint = function (t) { + var spline = {x: 0, y: 0}, p0 = controllPoint2, p1 = controllPoint1, p2 = start, @@ -1139,122 +1134,121 @@ var getMouseTarget = this.getMouseTarget = function(evt) { ]; spline.x = S * ( - (p0.x * m[0][0] + p1.x * m[0][1] + p2.x * m[0][2] + p3.x * m[0][3] ) * t3 + - (p0.x * m[1][0] + p1.x * m[1][1] + p2.x * m[1][2] + p3.x * m[1][3] ) * t2 + - (p0.x * m[2][0] + p1.x * m[2][1] + p2.x * m[2][2] + p3.x * m[2][3] ) * t + - (p0.x * m[3][0] + p1.x * m[3][1] + p2.x * m[3][2] + p3.x * m[3][3] ) + (p0.x * m[0][0] + p1.x * m[0][1] + p2.x * m[0][2] + p3.x * m[0][3]) * t3 + + (p0.x * m[1][0] + p1.x * m[1][1] + p2.x * m[1][2] + p3.x * m[1][3]) * t2 + + (p0.x * m[2][0] + p1.x * m[2][1] + p2.x * m[2][2] + p3.x * m[2][3]) * t + + (p0.x * m[3][0] + p1.x * m[3][1] + p2.x * m[3][2] + p3.x * m[3][3]) ); spline.y = S * ( - (p0.y * m[0][0] + p1.y * m[0][1] + p2.y * m[0][2] + p3.y * m[0][3] ) * t3 + - (p0.y * m[1][0] + p1.y * m[1][1] + p2.y * m[1][2] + p3.y * m[1][3] ) * t2 + - (p0.y * m[2][0] + p1.y * m[2][1] + p2.y * m[2][2] + p3.y * m[2][3] ) * t + - (p0.y * m[3][0] + p1.y * m[3][1] + p2.y * m[3][2] + p3.y * m[3][3] ) + (p0.y * m[0][0] + p1.y * m[0][1] + p2.y * m[0][2] + p3.y * m[0][3]) * t3 + + (p0.y * m[1][0] + p1.y * m[1][1] + p2.y * m[1][2] + p3.y * m[1][3]) * t2 + + (p0.y * m[2][0] + p1.y * m[2][1] + p2.y * m[2][2] + p3.y * m[2][3]) * t + + (p0.y * m[3][0] + p1.y * m[3][1] + p2.y * m[3][2] + p3.y * m[3][3]) ); return { - x:spline.x, - y:spline.y + x: spline.x, + y: spline.y }; }; // - when we are in a create mode, the element is added to the canvas // but the action is not recorded until mousing up // - when we are in select mode, select the element, remember the position // and do nothing else - var mouseDown = function(evt) { - if (canvas.spaceKey || evt.button === 1) {return;} + var mouseDown = function (evt) { + if (canvas.spaceKey || evt.button === 1) { return; } - var right_click = evt.button === 2; + var rightClick = evt.button === 2; if (evt.altKey) { // duplicate when dragging svgCanvas.cloneSelectedElements(0, 0); } - root_sctm = $('#svgcontent g')[0].getScreenCTM().inverse(); + rootSctm = $('#svgcontent g')[0].getScreenCTM().inverse(); - var pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ), - mouse_x = pt.x * current_zoom, - mouse_y = pt.y * current_zoom; + var pt = svgedit.math.transformPoint(evt.pageX, evt.pageY, rootSctm), + mouseX = pt.x * currentZoom, + mouseY = pt.y * currentZoom; evt.preventDefault(); - if (right_click) { - current_mode = 'select'; + if (rightClick) { + currentMode = 'select'; lastClickPoint = pt; } // This would seem to be unnecessary... -// if (['select', 'resize'].indexOf(current_mode) == -1) { -// setGradient(); -// } + // if (['select', 'resize'].indexOf(currentMode) === -1) { + // setGradient(); + // } - var x = mouse_x / current_zoom, - y = mouse_y / current_zoom, - mouse_target = getMouseTarget(evt); + var x = mouseX / currentZoom, + y = mouseY / currentZoom, + mouseTarget = getMouseTarget(evt); - if (mouse_target.tagName === 'a' && mouse_target.childNodes.length === 1) { - mouse_target = mouse_target.firstChild; + if (mouseTarget.tagName === 'a' && mouseTarget.childNodes.length === 1) { + mouseTarget = mouseTarget.firstChild; } - // real_x/y ignores grid-snap value - var real_x = x; - r_start_x = start_x = x; - var real_y = y; - r_start_y = start_y = y; + // realX/y ignores grid-snap value + var realX = x; + rStartX = startX = x; + var realY = y; + rStartY = startY = y; - if (curConfig.gridSnapping){ + if (curConfig.gridSnapping) { x = svgedit.utilities.snapToGrid(x); y = svgedit.utilities.snapToGrid(y); - start_x = svgedit.utilities.snapToGrid(start_x); - start_y = svgedit.utilities.snapToGrid(start_y); + startX = svgedit.utilities.snapToGrid(startX); + startY = svgedit.utilities.snapToGrid(startY); } // if it is a selector grip, then it must be a single element selected, - // set the mouse_target to that and update the mode to rotate/resize + // set the mouseTarget to that and update the mode to rotate/resize - if (mouse_target == selectorManager.selectorParentGroup && selectedElements[0] != null) { + if (mouseTarget === selectorManager.selectorParentGroup && selectedElements[0] != null) { var grip = evt.target; var griptype = elData(grip, 'type'); // rotating - if (griptype == 'rotate') { - current_mode = 'rotate'; - } + if (griptype === 'rotate') { + currentMode = 'rotate'; // resizing - else if (griptype == 'resize') { - current_mode = 'resize'; - current_resize_mode = elData(grip, 'dir'); + } else if (griptype === 'resize') { + currentMode = 'resize'; + currentResizeMode = elData(grip, 'dir'); } - mouse_target = selectedElements[0]; + mouseTarget = selectedElements[0]; } - startTransform = mouse_target.getAttribute('transform'); - var i, stroke_w, - tlist = svgedit.transformlist.getTransformList(mouse_target); - switch (current_mode) { + startTransform = mouseTarget.getAttribute('transform'); + var i, strokeW, + tlist = svgedit.transformlist.getTransformList(mouseTarget); + switch (currentMode) { case 'select': started = true; - current_resize_mode = 'none'; - if (right_click) {started = false;} + currentResizeMode = 'none'; + if (rightClick) { started = false; } - if (mouse_target != svgroot) { + if (mouseTarget !== svgroot) { // if this element is not yet selected, clear selection and select it - if (selectedElements.indexOf(mouse_target) == -1) { + if (selectedElements.indexOf(mouseTarget) === -1) { // only clear selection if shift is not pressed (otherwise, add // element to selection) if (!evt.shiftKey) { // No need to do the call here as it will be done on addToSelection clearSelection(true); } - addToSelection([mouse_target]); - justSelected = mouse_target; + addToSelection([mouseTarget]); + justSelected = mouseTarget; pathActions.clear(); } // else if it's a path, go into pathedit mode in mouseup - if (!right_click) { + if (!rightClick) { // insert a dummy transform so if the element(s) are moved it will have // a transform to use for its translate for (i = 0; i < selectedElements.length; ++i) { - if (selectedElements[i] == null) {continue;} + if (selectedElements[i] == null) { continue; } var slist = svgedit.transformlist.getTransformList(selectedElements[i]); if (slist.numberOfItems) { slist.insertItemBefore(svgroot.createSVGTransform(), 0); @@ -1263,22 +1257,22 @@ var getMouseTarget = this.getMouseTarget = function(evt) { } } } - } else if (!right_click){ + } else if (!rightClick) { clearSelection(); - current_mode = 'multiselect'; + currentMode = 'multiselect'; if (rubberBox == null) { rubberBox = selectorManager.getRubberBandBox(); } - r_start_x *= current_zoom; - r_start_y *= current_zoom; -// console.log('p',[evt.pageX, evt.pageY]); -// console.log('c',[evt.clientX, evt.clientY]); -// console.log('o',[evt.offsetX, evt.offsetY]); -// console.log('s',[start_x, start_y]); + rStartX *= currentZoom; + rStartY *= currentZoom; + // console.log('p',[evt.pageX, evt.pageY]); + // console.log('c',[evt.clientX, evt.clientY]); + // console.log('o',[evt.offsetX, evt.offsetY]); + // console.log('s',[startX, startY]); svgedit.utilities.assignAttributes(rubberBox, { - 'x': r_start_x, - 'y': r_start_y, + 'x': rStartX, + 'y': rStartY, 'width': 0, 'height': 0, 'display': 'inline' @@ -1291,8 +1285,8 @@ var getMouseTarget = this.getMouseTarget = function(evt) { rubberBox = selectorManager.getRubberBandBox(); } svgedit.utilities.assignAttributes(rubberBox, { - 'x': real_x * current_zoom, - 'y': real_x * current_zoom, + 'x': realX * currentZoom, + 'y': realX * currentZoom, 'width': 0, 'height': 0, 'display': 'inline' @@ -1300,21 +1294,21 @@ var getMouseTarget = this.getMouseTarget = function(evt) { break; case 'resize': started = true; - start_x = x; - start_y = y; + startX = x; + startY = y; // Getting the BBox from the selection box, since we know we // want to orient around it - init_bbox = svgedit.utilities.getBBox($('#selectedBox0')[0]); + initBbox = svgedit.utilities.getBBox($('#selectedBox0')[0]); var bb = {}; - $.each(init_bbox, function(key, val) { - bb[key] = val/current_zoom; + $.each(initBbox, function (key, val) { + bb[key] = val / currentZoom; }); - init_bbox = bb; + initBbox = bb; // append three dummy transforms to the tlist so that // we can translate,scale,translate in mousemove - var pos = svgedit.utilities.getRotationAngle(mouse_target) ? 1 : 0; + var pos = svgedit.utilities.getRotationAngle(mouseTarget) ? 1 : 0; if (svgedit.math.hasMatrixTransform(tlist)) { tlist.insertItemBefore(svgroot.createSVGTransform(), pos); @@ -1333,21 +1327,21 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var isWebkit = svgedit.browser.isWebkit(); if (isWebkit) { - var delayedStroke = function(ele) { + var delayedStroke = function (ele) { var _stroke = ele.getAttributeNS(null, 'stroke'); ele.removeAttributeNS(null, 'stroke'); // Re-apply stroke after delay. Anything higher than 1 seems to cause flicker - if (_stroke !== null) setTimeout(function() { ele.setAttributeNS(null, 'stroke', _stroke); }, 0); + if (_stroke !== null) setTimeout(function () { ele.setAttributeNS(null, 'stroke', _stroke); }, 0); }; } - mouse_target.style.vectorEffect = 'non-scaling-stroke'; - if (isWebkit) {delayedStroke(mouse_target);} + mouseTarget.style.vectorEffect = 'non-scaling-stroke'; + if (isWebkit) { delayedStroke(mouseTarget); } - var all = mouse_target.getElementsByTagName('*'), + var all = mouseTarget.getElementsByTagName('*'), len = all.length; for (i = 0; i < len; i++) { all[i].style.vectorEffect = 'non-scaling-stroke'; - if (isWebkit) {delayedStroke(all[i]);} + if (isWebkit) { delayedStroke(all[i]); } } } } @@ -1355,27 +1349,27 @@ var getMouseTarget = this.getMouseTarget = function(evt) { case 'fhellipse': case 'fhrect': case 'fhpath': - start.x = real_x; - start.y = real_y; + start.x = realX; + start.y = realY; started = true; - d_attr = real_x + ',' + real_y + ' '; - stroke_w = cur_shape.stroke_width == 0 ? 1 : cur_shape.stroke_width; + dAttr = realX + ',' + realY + ' '; + strokeW = parseFloat(curShape.stroke_width) === 0 ? 1 : curShape.stroke_width; addSvgElementFromJson({ element: 'polyline', curStyles: true, attr: { - points: d_attr, + points: dAttr, id: getNextId(), fill: 'none', - opacity: cur_shape.opacity / 2, + opacity: curShape.opacity / 2, 'stroke-linecap': 'round', style: 'pointer-events:none' } }); - freehand.minx = real_x; - freehand.maxx = real_x; - freehand.miny = real_y; - freehand.maxy = real_y; + freehand.minx = realX; + freehand.maxx = realX; + freehand.miny = realY; + freehand.maxy = realY; break; case 'image': started = true; @@ -1387,20 +1381,21 @@ var getMouseTarget = this.getMouseTarget = function(evt) { width: 0, height: 0, id: getNextId(), - opacity: cur_shape.opacity / 2, + opacity: curShape.opacity / 2, style: 'pointer-events:inherit' } }); - setHref(newImage, last_good_img_url); + setHref(newImage, lastGoodImgUrl); svgedit.utilities.preventClickDefault(newImage); break; case 'square': // FIXME: once we create the rect, we lose information that this was a square // (for resizing purposes this could be important) + // Fallthrough case 'rect': started = true; - start_x = x; - start_y = y; + startX = x; + startY = y; addSvgElementFromJson({ element: 'rect', curStyles: true, @@ -1410,13 +1405,13 @@ var getMouseTarget = this.getMouseTarget = function(evt) { width: 0, height: 0, id: getNextId(), - opacity: cur_shape.opacity / 2 + opacity: curShape.opacity / 2 } }); break; case 'line': started = true; - stroke_w = cur_shape.stroke_width == 0 ? 1 : cur_shape.stroke_width; + strokeW = Number(curShape.stroke_width) === 0 ? 1 : curShape.stroke_width; addSvgElementFromJson({ element: 'line', curStyles: true, @@ -1426,14 +1421,14 @@ var getMouseTarget = this.getMouseTarget = function(evt) { x2: x, y2: y, id: getNextId(), - stroke: cur_shape.stroke, - 'stroke-width': stroke_w, - 'stroke-dasharray': cur_shape.stroke_dasharray, - 'stroke-linejoin': cur_shape.stroke_linejoin, - 'stroke-linecap': cur_shape.stroke_linecap, - 'stroke-opacity': cur_shape.stroke_opacity, + stroke: curShape.stroke, + 'stroke-width': strokeW, + 'stroke-dasharray': curShape.stroke_dasharray, + 'stroke-linejoin': curShape.stroke_linejoin, + 'stroke-linecap': curShape.stroke_linecap, + 'stroke-opacity': curShape.stroke_opacity, fill: 'none', - opacity: cur_shape.opacity / 2, + opacity: curShape.opacity / 2, style: 'pointer-events:none' } }); @@ -1448,7 +1443,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { cy: y, r: 0, id: getNextId(), - opacity: cur_shape.opacity / 2 + opacity: curShape.opacity / 2 } }); break; @@ -1463,42 +1458,42 @@ var getMouseTarget = this.getMouseTarget = function(evt) { rx: 0, ry: 0, id: getNextId(), - opacity: cur_shape.opacity / 2 + opacity: curShape.opacity / 2 } }); break; case 'text': started = true; - var newText = addSvgElementFromJson({ + /* var newText = */ addSvgElementFromJson({ element: 'text', curStyles: true, attr: { x: x, y: y, id: getNextId(), - fill: cur_text.fill, - 'stroke-width': cur_text.stroke_width, - 'font-size': cur_text.font_size, - 'font-family': cur_text.font_family, + fill: curText.fill, + 'stroke-width': curText.stroke_width, + 'font-size': curText.font_size, + 'font-family': curText.font_family, 'text-anchor': 'middle', 'xml:space': 'preserve', - opacity: cur_shape.opacity + opacity: curShape.opacity } }); -// newText.textContent = 'text'; + // newText.textContent = 'text'; break; case 'path': // Fall through case 'pathedit': - start_x *= current_zoom; - start_y *= current_zoom; - pathActions.mouseDown(evt, mouse_target, start_x, start_y); + startX *= currentZoom; + startY *= currentZoom; + pathActions.mouseDown(evt, mouseTarget, startX, startY); started = true; break; case 'textedit': - start_x *= current_zoom; - start_y *= current_zoom; - textActions.mouseDown(evt, mouse_target, start_x, start_y); + startX *= currentZoom; + startY *= currentZoom; + textActions.mouseDown(evt, mouseTarget, startX, startY); started = true; break; case 'rotate': @@ -1511,14 +1506,14 @@ var getMouseTarget = this.getMouseTarget = function(evt) { break; } - var ext_result = runExtensions('mouseDown', { + var extResult = runExtensions('mouseDown', { event: evt, - start_x: start_x, - start_y: start_y, + start_x: startX, + start_y: startY, selectedElements: selectedElements }, true); - $.each(ext_result, function(i, r) { + $.each(extResult, function (i, r) { if (r && r.started) { started = true; } @@ -1527,59 +1522,59 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // in this function we do not record any state changes yet (but we do update // any elements that are still being created, moved or resized on the canvas) - var mouseMove = function(evt) { - if (!started) {return;} - if (evt.button === 1 || canvas.spaceKey) {return;} + var mouseMove = function (evt) { + if (!started) { return; } + if (evt.button === 1 || canvas.spaceKey) { return; } var i, xya, c, cx, cy, dx, dy, len, angle, box, selected = selectedElements[0], - pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ), - mouse_x = pt.x * current_zoom, - mouse_y = pt.y * current_zoom, + pt = svgedit.math.transformPoint(evt.pageX, evt.pageY, rootSctm), + mouseX = pt.x * currentZoom, + mouseY = pt.y * currentZoom, shape = svgedit.utilities.getElem(getId()); - var real_x = mouse_x / current_zoom; - x = real_x; - var real_y = mouse_y / current_zoom; - y = real_y; + var realX = mouseX / currentZoom; + var x = realX; + var realY = mouseY / currentZoom; + var y = realY; - if (curConfig.gridSnapping){ + if (curConfig.gridSnapping) { x = svgedit.utilities.snapToGrid(x); y = svgedit.utilities.snapToGrid(y); } evt.preventDefault(); var tlist; - switch (current_mode) { + switch (currentMode) { case 'select': // we temporarily use a translate on the element(s) being dragged // this transform is removed upon mousing up and the element is // relocated to the new location if (selectedElements[0] !== null) { - dx = x - start_x; - dy = y - start_y; + dx = x - startX; + dy = y - startY; - if (curConfig.gridSnapping){ + if (curConfig.gridSnapping) { dx = svgedit.utilities.snapToGrid(dx); dy = svgedit.utilities.snapToGrid(dy); } if (evt.shiftKey) { - xya = svgedit.math.snapToAngle(start_x, start_y, x, y); + xya = svgedit.math.snapToAngle(startX, startY, x, y); x = xya.x; y = xya.y; } - if (dx != 0 || dy != 0) { + if (dx !== 0 || dy !== 0) { len = selectedElements.length; for (i = 0; i < len; ++i) { selected = selectedElements[i]; - if (selected == null) {break;} -// if (i==0) { -// var box = svgedit.utilities.getBBox(selected); -// selectedBBoxes[i].x = box.x + dx; -// selectedBBoxes[i].y = box.y + dy; -// } + if (selected == null) { break; } + // if (i === 0) { + // var box = svgedit.utilities.getBBox(selected); + // selectedBBoxes[i].x = box.x + dx; + // selectedBBoxes[i].y = box.y + dy; + // } // update the dummy transform in our transform list // to be a translate @@ -1605,13 +1600,13 @@ var getMouseTarget = this.getMouseTarget = function(evt) { } break; case 'multiselect': - real_x *= current_zoom; - real_y *= current_zoom; + realX *= currentZoom; + realY *= currentZoom; svgedit.utilities.assignAttributes(rubberBox, { - 'x': Math.min(r_start_x, real_x), - 'y': Math.min(r_start_y, real_y), - 'width': Math.abs(real_x - r_start_x), - 'height': Math.abs(real_y - r_start_y) + 'x': Math.min(rStartX, realX), + 'y': Math.min(rStartY, realY), + 'width': Math.abs(realX - rStartX), + 'height': Math.abs(realY - rStartY) }, 100); // for each selected: @@ -1626,13 +1621,13 @@ var getMouseTarget = this.getMouseTarget = function(evt) { for (i = 0; i < len; ++i) { var intElem = newList[i]; // Found an element that was not selected before, so we should add it. - if (selectedElements.indexOf(intElem) == -1) { + if (selectedElements.indexOf(intElem) === -1) { elemsToAdd.push(intElem); } // Found an element that was already selected, so we shouldn't remove it. var foundInd = elemsToRemove.indexOf(intElem); - if (foundInd != -1) { - elemsToRemove.splice(foundInd, 1) + if (foundInd !== -1) { + elemsToRemove.splice(foundInd, 1); } } @@ -1651,11 +1646,11 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // the shape's coordinates tlist = svgedit.transformlist.getTransformList(selected); var hasMatrix = svgedit.math.hasMatrixTransform(tlist); - box = hasMatrix ? init_bbox : svgedit.utilities.getBBox(selected); + box = hasMatrix ? initBbox : svgedit.utilities.getBBox(selected); var left = box.x, top = box.y, width = box.width, height = box.height; - dx = (x-start_x); - dy = (y-start_y); + dx = (x - startX); + dy = (y - startY); if (curConfig.gridSnapping) { dx = svgedit.utilities.snapToGrid(dx); @@ -1667,7 +1662,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // if rotated, adjust the dx,dy values angle = svgedit.utilities.getRotationAngle(selected); if (angle) { - var r = Math.sqrt( dx*dx + dy*dy ), + var r = Math.sqrt(dx * dx + dy * dy), theta = Math.atan2(dy, dx) - angle * Math.PI / 180.0; dx = r * Math.cos(theta); dy = r * Math.sin(theta); @@ -1675,26 +1670,26 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // if not stretching in y direction, set dy to 0 // if not stretching in x direction, set dx to 0 - if (current_resize_mode.indexOf('n')==-1 && current_resize_mode.indexOf('s')==-1) { + if (currentResizeMode.indexOf('n') === -1 && currentResizeMode.indexOf('s') === -1) { dy = 0; } - if (current_resize_mode.indexOf('e')==-1 && current_resize_mode.indexOf('w')==-1) { + if (currentResizeMode.indexOf('e') === -1 && currentResizeMode.indexOf('w') === -1) { dx = 0; } - var ts = null, + var // ts = null, tx = 0, ty = 0, - sy = height ? (height+dy)/height : 1, - sx = width ? (width+dx)/width : 1; + sy = height ? (height + dy) / height : 1, + sx = width ? (width + dx) / width : 1; // if we are dragging on the north side, then adjust the scale factor and ty - if (current_resize_mode.indexOf('n') >= 0) { - sy = height ? (height-dy)/height : 1; + if (currentResizeMode.indexOf('n') >= 0) { + sy = height ? (height - dy) / height : 1; ty = height; } // if we dragging on the east side, then adjust the scale factor and tx - if (current_resize_mode.indexOf('w') >= 0) { - sx = width ? (width-dx)/width : 1; + if (currentResizeMode.indexOf('w') >= 0) { + sx = width ? (width - dx) / width : 1; tx = width; } @@ -1710,24 +1705,25 @@ var getMouseTarget = this.getMouseTarget = function(evt) { ty = svgedit.utilities.snapToGrid(ty); } - translateOrigin.setTranslate(-(left+tx), -(top+ty)); + translateOrigin.setTranslate(-(left + tx), -(top + ty)); if (evt.shiftKey) { - if (sx == 1) {sx = sy;} - else {sy = sx;} + if (sx === 1) { + sx = sy; + } else { sy = sx; } } scale.setScale(sx, sy); - translateBack.setTranslate(left+tx, top+ty); + translateBack.setTranslate(left + tx, top + ty); if (hasMatrix) { var diff = angle ? 1 : 0; - tlist.replaceItem(translateOrigin, 2+diff); - tlist.replaceItem(scale, 1+diff); + tlist.replaceItem(translateOrigin, 2 + diff); + tlist.replaceItem(scale, 1 + diff); tlist.replaceItem(translateBack, Number(diff)); } else { var N = tlist.numberOfItems; - tlist.replaceItem(translateBack, N-3); - tlist.replaceItem(scale, N-2); - tlist.replaceItem(translateOrigin, N-1); + tlist.replaceItem(translateBack, N - 3); + tlist.replaceItem(scale, N - 2); + tlist.replaceItem(translateOrigin, N - 1); } selectorManager.requestSelector(selected).resize(); @@ -1736,17 +1732,17 @@ var getMouseTarget = this.getMouseTarget = function(evt) { break; case 'zoom': - real_x *= current_zoom; - real_y *= current_zoom; + realX *= currentZoom; + realY *= currentZoom; svgedit.utilities.assignAttributes(rubberBox, { - 'x': Math.min(r_start_x*current_zoom, real_x), - 'y': Math.min(r_start_y*current_zoom, real_y), - 'width': Math.abs(real_x - r_start_x*current_zoom), - 'height': Math.abs(real_y - r_start_y*current_zoom) + 'x': Math.min(rStartX * currentZoom, realX), + 'y': Math.min(rStartY * currentZoom, realY), + 'width': Math.abs(realX - rStartX * currentZoom), + 'height': Math.abs(realY - rStartY * currentZoom) }, 100); break; case 'text': - svgedit.utilities.assignAttributes(shape,{ + svgedit.utilities.assignAttributes(shape, { 'x': x, 'y': y }, 1000); @@ -1761,7 +1757,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var y2 = y; if (evt.shiftKey) { - xya = svgedit.math.snapToAngle(start_x, start_y, x2, y2); + xya = svgedit.math.snapToAngle(startX, startY, x2, y2); x2 = xya.x; y2 = xya.y; } @@ -1776,39 +1772,39 @@ var getMouseTarget = this.getMouseTarget = function(evt) { case 'rect': // fall through case 'image': - var square = (current_mode == 'square') || evt.shiftKey, - w = Math.abs(x - start_x), - h = Math.abs(y - start_y), - new_x, new_y; + var square = (currentMode === 'square') || evt.shiftKey, + w = Math.abs(x - startX), + h = Math.abs(y - startY), + newX, newY; if (square) { w = h = Math.max(w, h); - new_x = start_x < x ? start_x : start_x - w; - new_y = start_y < y ? start_y : start_y - h; + newX = startX < x ? startX : startX - w; + newY = startY < y ? startY : startY - h; } else { - new_x = Math.min(start_x, x); - new_y = Math.min(start_y, y); + newX = Math.min(startX, x); + newY = Math.min(startY, y); } if (curConfig.gridSnapping) { w = svgedit.utilities.snapToGrid(w); h = svgedit.utilities.snapToGrid(h); - new_x = svgedit.utilities.snapToGrid(new_x); - new_y = svgedit.utilities.snapToGrid(new_y); + newX = svgedit.utilities.snapToGrid(newX); + newY = svgedit.utilities.snapToGrid(newY); } - svgedit.utilities.assignAttributes(shape,{ + svgedit.utilities.assignAttributes(shape, { 'width': w, 'height': h, - 'x': new_x, - 'y': new_y - },1000); + 'x': newX, + 'y': newY + }, 1000); break; case 'circle': c = $(shape).attr(['cx', 'cy']); cx = c.cx; cy = c.cy; - var rad = Math.sqrt( (x-cx)*(x-cx) + (y-cy)*(y-cy) ); + var rad = Math.sqrt((x - cx) * (x - cx) + (y - cy) * (y - cy)); if (curConfig.gridSnapping) { rad = svgedit.utilities.snapToGrid(rad); } @@ -1824,21 +1820,21 @@ var getMouseTarget = this.getMouseTarget = function(evt) { y = svgedit.utilities.snapToGrid(y); cy = svgedit.utilities.snapToGrid(cy); } - shape.setAttributeNS(null, 'rx', Math.abs(x - cx) ); - var ry = Math.abs(evt.shiftKey?(x - cx):(y - cy)); - shape.setAttributeNS(null, 'ry', ry ); + shape.setAttributeNS(null, 'rx', Math.abs(x - cx)); + var ry = Math.abs(evt.shiftKey ? (x - cx) : (y - cy)); + shape.setAttributeNS(null, 'ry', ry); break; case 'fhellipse': case 'fhrect': - freehand.minx = Math.min(real_x, freehand.minx); - freehand.maxx = Math.max(real_x, freehand.maxx); - freehand.miny = Math.min(real_y, freehand.miny); - freehand.maxy = Math.max(real_y, freehand.maxy); - // break; missing on purpose + freehand.minx = Math.min(realX, freehand.minx); + freehand.maxx = Math.max(realX, freehand.maxx); + freehand.miny = Math.min(realY, freehand.miny); + freehand.maxy = Math.max(realY, freehand.maxy); + // Fallthrough case 'fhpath': -// d_attr += + real_x + ',' + real_y + ' '; -// shape.setAttributeNS(null, 'points', d_attr); - end.x = real_x; end.y = real_y; + // dAttr += + realX + ',' + realY + ' '; + // shape.setAttributeNS(null, 'points', dAttr); + end.x = realX; end.y = realY; if (controllPoint2.x && controllPoint2.y) { for (i = 0; i < STEP_COUNT - 1; i++) { parameter = i / STEP_COUNT; @@ -1848,38 +1844,38 @@ var getMouseTarget = this.getMouseTarget = function(evt) { bSpline = getBsplinePoint(parameter); sumDistance += Math.sqrt((nextPos.x - bSpline.x) * (nextPos.x - bSpline.x) + (nextPos.y - bSpline.y) * (nextPos.y - bSpline.y)); if (sumDistance > THRESHOLD_DIST) { - d_attr += + bSpline.x + ',' + bSpline.y + ' '; - shape.setAttributeNS(null, 'points', d_attr); + dAttr += +bSpline.x + ',' + bSpline.y + ' '; + shape.setAttributeNS(null, 'points', dAttr); sumDistance -= THRESHOLD_DIST; } } } - controllPoint2 = {x:controllPoint1.x, y:controllPoint1.y}; - controllPoint1 = {x:start.x, y:start.y}; - start = {x:end.x, y:end.y}; + controllPoint2 = {x: controllPoint1.x, y: controllPoint1.y}; + controllPoint1 = {x: start.x, y: start.y}; + start = {x: end.x, y: end.y}; break; // update path stretch line coordinates case 'path': // fall through case 'pathedit': - x *= current_zoom; - y *= current_zoom; + x *= currentZoom; + y *= currentZoom; if (curConfig.gridSnapping) { x = svgedit.utilities.snapToGrid(x); y = svgedit.utilities.snapToGrid(y); - start_x = svgedit.utilities.snapToGrid(start_x); - start_y = svgedit.utilities.snapToGrid(start_y); + startX = svgedit.utilities.snapToGrid(startX); + startY = svgedit.utilities.snapToGrid(startY); } if (evt.shiftKey) { var path = svgedit.path.path; var x1, y1; if (path) { - x1 = path.dragging?path.dragging[0]:start_x; - y1 = path.dragging?path.dragging[1]:start_y; + x1 = path.dragging ? path.dragging[0] : startX; + y1 = path.dragging ? path.dragging[1] : startY; } else { - x1 = start_x; - y1 = start_y; + x1 = startX; + y1 = startY; } xya = svgedit.math.snapToAngle(x1, y1, x, y); x = xya.x; @@ -1887,51 +1883,51 @@ var getMouseTarget = this.getMouseTarget = function(evt) { } if (rubberBox && rubberBox.getAttribute('display') !== 'none') { - real_x *= current_zoom; - real_y *= current_zoom; + realX *= currentZoom; + realY *= currentZoom; svgedit.utilities.assignAttributes(rubberBox, { - 'x': Math.min(r_start_x*current_zoom, real_x), - 'y': Math.min(r_start_y*current_zoom, real_y), - 'width': Math.abs(real_x - r_start_x*current_zoom), - 'height': Math.abs(real_y - r_start_y*current_zoom) - },100); + 'x': Math.min(rStartX * currentZoom, realX), + 'y': Math.min(rStartY * currentZoom, realY), + 'width': Math.abs(realX - rStartX * currentZoom), + 'height': Math.abs(realY - rStartY * currentZoom) + }, 100); } pathActions.mouseMove(x, y); break; case 'textedit': - x *= current_zoom; - y *= current_zoom; -// if (rubberBox && rubberBox.getAttribute('display') != 'none') { -// svgedit.utilities.assignAttributes(rubberBox, { -// 'x': Math.min(start_x,x), -// 'y': Math.min(start_y,y), -// 'width': Math.abs(x-start_x), -// 'height': Math.abs(y-start_y) -// },100); -// } + x *= currentZoom; + y *= currentZoom; + // if (rubberBox && rubberBox.getAttribute('display') !== 'none') { + // svgedit.utilities.assignAttributes(rubberBox, { + // 'x': Math.min(startX, x), + // 'y': Math.min(startY, y), + // 'width': Math.abs(x - startX), + // 'height': Math.abs(y - startY) + // }, 100); + // } - textActions.mouseMove(mouse_x, mouse_y); + textActions.mouseMove(mouseX, mouseY); break; case 'rotate': box = svgedit.utilities.getBBox(selected); - cx = box.x + box.width/2; - cy = box.y + box.height/2; + cx = box.x + box.width / 2; + cy = box.y + box.height / 2; var m = svgedit.math.getMatrix(selected), center = svgedit.math.transformPoint(cx, cy, m); cx = center.x; cy = center.y; - angle = ((Math.atan2(cy-y, cx-x) * (180/Math.PI))-90) % 360; + angle = ((Math.atan2(cy - y, cx - x) * (180 / Math.PI)) - 90) % 360; if (curConfig.gridSnapping) { angle = svgedit.utilities.snapToGrid(angle); } if (evt.shiftKey) { // restrict rotations to nice angles (WRS) var snap = 45; - angle= Math.round(angle/snap)*snap; + angle = Math.round(angle / snap) * snap; } - canvas.setRotationAngle(angle<-180?(360+angle):angle, true); + canvas.setRotationAngle(angle < -180 ? (360 + angle) : angle, true); call('transition', selectedElements); break; default: @@ -1940,11 +1936,10 @@ var getMouseTarget = this.getMouseTarget = function(evt) { runExtensions('mouseMove', { event: evt, - mouse_x: mouse_x, - mouse_y: mouse_y, + mouse_x: mouseX, + mouse_y: mouseY, selected: selected }); - }; // mouseMove() // - in create mode, the element's opacity is set properly, we create an InsertElementCommand @@ -1952,27 +1947,27 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // - in move/resize mode, the element's attributes which were affected by the move/resize are // identified, a ChangeElementCommand is created and stored on the stack for those attrs // this is done in when we recalculate the selected dimensions() - var mouseUp = function(evt) { - if (evt.button === 2) {return;} + var mouseUp = function (evt) { + if (evt.button === 2) { return; } var tempJustSelected = justSelected; justSelected = null; - if (!started) {return;} - var pt = svgedit.math.transformPoint(evt.pageX, evt.pageY, root_sctm), - mouse_x = pt.x * current_zoom, - mouse_y = pt.y * current_zoom, - x = mouse_x / current_zoom, - y = mouse_y / current_zoom, + if (!started) { return; } + var pt = svgedit.math.transformPoint(evt.pageX, evt.pageY, rootSctm), + mouseX = pt.x * currentZoom, + mouseY = pt.y * currentZoom, + x = mouseX / currentZoom, + y = mouseY / currentZoom, element = svgedit.utilities.getElem(getId()), keep = false; - var real_x = x; - var real_y = y; + var realX = x; + var realY = y; // TODO: Make true when in multi-unit mode var useUnit = false; // (curConfig.baseUnit !== 'px'); started = false; var attrs, t; - switch (current_mode) { + switch (currentMode) { // intentionally fall-through to select here case 'resize': case 'multiselect': @@ -1980,33 +1975,34 @@ var getMouseTarget = this.getMouseTarget = function(evt) { rubberBox.setAttribute('display', 'none'); curBBoxes = []; } - current_mode = 'select'; + currentMode = 'select'; + // Fallthrough case 'select': if (selectedElements[0] != null) { // if we only have one selected element if (selectedElements[1] == null) { // set our current stroke/fill properties to the element's var selected = selectedElements[0]; - switch ( selected.tagName ) { + switch (selected.tagName) { case 'g': case 'use': case 'image': case 'foreignObject': break; default: - cur_properties.fill = selected.getAttribute('fill'); - cur_properties.fill_opacity = selected.getAttribute('fill-opacity'); - cur_properties.stroke = selected.getAttribute('stroke'); - cur_properties.stroke_opacity = selected.getAttribute('stroke-opacity'); - cur_properties.stroke_width = selected.getAttribute('stroke-width'); - cur_properties.stroke_dasharray = selected.getAttribute('stroke-dasharray'); - cur_properties.stroke_linejoin = selected.getAttribute('stroke-linejoin'); - cur_properties.stroke_linecap = selected.getAttribute('stroke-linecap'); + curProperties.fill = selected.getAttribute('fill'); + curProperties.fill_opacity = selected.getAttribute('fill-opacity'); + curProperties.stroke = selected.getAttribute('stroke'); + curProperties.stroke_opacity = selected.getAttribute('stroke-opacity'); + curProperties.stroke_width = selected.getAttribute('stroke-width'); + curProperties.stroke_dasharray = selected.getAttribute('stroke-dasharray'); + curProperties.stroke_linejoin = selected.getAttribute('stroke-linejoin'); + curProperties.stroke_linecap = selected.getAttribute('stroke-linecap'); } - if (selected.tagName == 'text') { - cur_text.font_size = selected.getAttribute('font-size'); - cur_text.font_family = selected.getAttribute('font-family'); + if (selected.tagName === 'text') { + curText.font_size = selected.getAttribute('font-size'); + curText.font_family = selected.getAttribute('font-family'); } selectorManager.requestSelector(selected).showGrips(true); @@ -2016,25 +2012,24 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // always recalculate dimensions to strip off stray identity transforms recalculateAllSelectedDimensions(); // if it was being dragged/resized - if (real_x != r_start_x || real_y != r_start_y) { + if (realX !== rStartX || realY !== rStartY) { var i, len = selectedElements.length; for (i = 0; i < len; ++i) { - if (selectedElements[i] == null) {break;} + if (selectedElements[i] == null) { break; } if (!selectedElements[i].firstChild) { // Not needed for groups (incorrectly resizes elems), possibly not needed at all? selectorManager.requestSelector(selectedElements[i]).resize(); } } - } // no change in position/size, so maybe we should move to pathedit - else { + } else { t = evt.target; if (selectedElements[0].nodeName === 'path' && selectedElements[1] == null) { pathActions.select(selectedElements[0]); - } // if it was a path + // if it was a path // else, if it was selected and this is a shift-click, remove it from selection - else if (evt.shiftKey) { - if (tempJustSelected != t) { + } else if (evt.shiftKey) { + if (tempJustSelected !== t) { canvas.removeFromSelection([t]); } } @@ -2045,12 +2040,11 @@ var getMouseTarget = this.getMouseTarget = function(evt) { var elem = selectedElements[0]; if (elem) { elem.removeAttribute('style'); - svgedit.utilities.walkTree(elem, function(elem) { + svgedit.utilities.walkTree(elem, function (elem) { elem.removeAttribute('style'); }); } } - } return; case 'zoom': @@ -2059,10 +2053,10 @@ var getMouseTarget = this.getMouseTarget = function(evt) { } var factor = evt.shiftKey ? 0.5 : 2; call('zoomed', { - 'x': Math.min(r_start_x, real_x), - 'y': Math.min(r_start_y, real_y), - 'width': Math.abs(real_x - r_start_x), - 'height': Math.abs(real_y - r_start_y), + 'x': Math.min(rStartX, realX), + 'y': Math.min(rStartY, realY), + 'width': Math.abs(realX - rStartX), + 'height': Math.abs(realY - rStartY), 'factor': factor }); return; @@ -2072,16 +2066,16 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // Webkit ignores how we set the points attribute with commas and uses space // to separate all coordinates, see https://bugs.webkit.org/show_bug.cgi?id=29870 sumDistance = 0; - controllPoint2 = {x:0, y:0}; - controllPoint1 = {x:0, y:0}; - start = {x:0, y:0}; - end = {x:0, y:0}; + controllPoint2 = {x: 0, y: 0}; + controllPoint1 = {x: 0, y: 0}; + start = {x: 0, y: 0}; + end = {x: 0, y: 0}; var coords = element.getAttribute('points'); var commaIndex = coords.indexOf(','); if (commaIndex >= 0) { - keep = coords.indexOf(',', commaIndex+1) >= 0; + keep = coords.indexOf(',', commaIndex + 1) >= 0; } else { - keep = coords.indexOf(' ', coords.indexOf(' ')+1) >= 0; + keep = coords.indexOf(' ', coords.indexOf(' ') + 1) >= 0; } if (keep) { element = pathActions.smoothPolylineIntoPath(element); @@ -2089,7 +2083,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { break; case 'line': attrs = $(element).attr(['x1', 'x2', 'y1', 'y2']); - keep = (attrs.x1 != attrs.x2 || attrs.y1 != attrs.y2); + keep = (attrs.x1 !== attrs.x2 || attrs.y1 !== attrs.y2); break; case 'foreignObject': case 'square': @@ -2097,10 +2091,10 @@ var getMouseTarget = this.getMouseTarget = function(evt) { case 'image': attrs = $(element).attr(['width', 'height']); // Image should be kept regardless of size (use inherit dimensions later) - keep = (attrs.width != 0 || attrs.height != 0) || current_mode === 'image'; + keep = (attrs.width !== '0' || attrs.height !== '0') || currentMode === 'image'; break; case 'circle': - keep = (element.getAttribute('r') != 0); + keep = (element.getAttribute('r') !== '0'); break; case 'ellipse': attrs = $(element).attr(['rx', 'ry']); @@ -2120,7 +2114,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { id: getId() } }); - call('changed',[element]); + call('changed', [element]); keep = true; } break; @@ -2138,7 +2132,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { id: getId() } }); - call('changed',[element]); + call('changed', [element]); keep = true; } break; @@ -2153,7 +2147,7 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // continue to be set to true so that mouseMove happens started = true; - var res = pathActions.mouseUp(evt, element, mouse_x, mouse_y); + var res = pathActions.mouseUp(evt, element, mouseX, mouseY); element = res.element; keep = res.keep; break; @@ -2165,12 +2159,12 @@ var getMouseTarget = this.getMouseTarget = function(evt) { case 'textedit': keep = false; element = null; - textActions.mouseUp(evt, mouse_x, mouse_y); + textActions.mouseUp(evt, mouseX, mouseY); break; case 'rotate': keep = true; element = null; - current_mode = 'select'; + currentMode = 'select'; var batchCmd = canvas.undoMgr.finishUndoableChange(); if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); @@ -2184,13 +2178,13 @@ var getMouseTarget = this.getMouseTarget = function(evt) { break; } - var ext_result = runExtensions('mouseUp', { + var extResult = runExtensions('mouseUp', { event: evt, - mouse_x: mouse_x, - mouse_y: mouse_y + mouse_x: mouseX, + mouse_y: mouseY }, true); - $.each(ext_result, function(i, r) { + $.each(extResult, function (i, r) { if (r) { keep = r.keep || keep; element = r.element; @@ -2208,48 +2202,47 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // if this element is in a group, go up until we reach the top-level group // just below the layer groups // TODO: once we implement links, we also would have to check for elements - while (t.parentNode.parentNode.tagName == 'g') { + while (t.parentNode.parentNode.tagName === 'g') { t = t.parentNode; } // if we are not in the middle of creating a path, and we've clicked on some shape, // then go to Select mode. // WebKit returns
when the canvas is clicked, Firefox/Opera return - if ( (current_mode != 'path' || !drawn_path) && - t.parentNode.id != 'selectorParentGroup' && - t.id != 'svgcanvas' && t.id != 'svgroot') - { + if ((currentMode !== 'path' || !drawnPath) && + t.parentNode.id !== 'selectorParentGroup' && + t.id !== 'svgcanvas' && t.id !== 'svgroot' + ) { // switch into "select" mode if we've clicked on an element canvas.setMode('select'); selectOnly([t], true); } - } else if (element != null) { canvas.addedNew = true; - if (useUnit) {svgedit.units.convertAttrs(element);} + if (useUnit) { svgedit.units.convertAttrs(element); } - var ani_dur = 0.2, c_ani; - if (opac_ani.beginElement && element.getAttribute('opacity') != cur_shape.opacity) { - c_ani = $(opac_ani).clone().attr({ - to: cur_shape.opacity, - dur: ani_dur + var aniDur = 0.2, cAni; + if (opacAni.beginElement && parseFloat(element.getAttribute('opacity')) !== curShape.opacity) { + cAni = $(opacAni).clone().attr({ + to: curShape.opacity, + dur: aniDur }).appendTo(element); try { // Fails in FF4 on foreignObject - c_ani[0].beginElement(); - } catch(e){} + cAni[0].beginElement(); + } catch (e) {} } else { - ani_dur = 0; + aniDur = 0; } // Ideally this would be done on the endEvent of the animation, // but that doesn't seem to be supported in Webkit - setTimeout(function() { - if (c_ani) {c_ani.remove();} - element.setAttribute('opacity', cur_shape.opacity); + setTimeout(function () { + if (cAni) { cAni.remove(); } + element.setAttribute('opacity', curShape.opacity); element.setAttribute('style', 'pointer-events:inherit'); cleanupElement(element); - if (current_mode === 'path') { + if (currentMode === 'path') { pathActions.toEditMode(element); } else if (curConfig.selectNew) { selectOnly([element], true); @@ -2258,54 +2251,56 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // undo means to call cmd.unapply(), redo means to call cmd.apply() addCommandToHistory(new svgedit.history.InsertElementCommand(element)); - call('changed',[element]); - }, ani_dur * 1000); + call('changed', [element]); + }, aniDur * 1000); } startTransform = null; }; - var dblClick = function(evt) { - var evt_target = evt.target; - var parent = evt_target.parentNode; + var dblClick = function (evt) { + var evtTarget = evt.target; + var parent = evtTarget.parentNode; // Do nothing if already in current group - if (parent === current_group) {return;} + if (parent === currentGroup) { return; } - var mouse_target = getMouseTarget(evt); - var tagName = mouse_target.tagName; + var mouseTarget = getMouseTarget(evt); + var tagName = mouseTarget.tagName; - if (tagName === 'text' && current_mode !== 'textedit') { - var pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ); - textActions.select(mouse_target, pt.x, pt.y); + if (tagName === 'text' && currentMode !== 'textedit') { + var pt = svgedit.math.transformPoint(evt.pageX, evt.pageY, rootSctm); + textActions.select(mouseTarget, pt.x, pt.y); } - if ((tagName === 'g' || tagName === 'a') && svgedit.utilities.getRotationAngle(mouse_target)) { + if ((tagName === 'g' || tagName === 'a') && + svgedit.utilities.getRotationAngle(mouseTarget) + ) { // TODO: Allow method of in-group editing without having to do // this (similar to editing rotated paths) // Ungroup and regroup - pushGroupProperties(mouse_target); - mouse_target = selectedElements[0]; + pushGroupProperties(mouseTarget); + mouseTarget = selectedElements[0]; clearSelection(true); } // Reset context - if (current_group) { + if (currentGroup) { leaveContext(); } if ((parent.tagName !== 'g' && parent.tagName !== 'a') || parent === getCurrentDrawing().getCurrentLayer() || - mouse_target === selectorManager.selectorParentGroup) - { + mouseTarget === selectorManager.selectorParentGroup + ) { // Escape from in-group edit return; } - setContext(mouse_target); + setContext(mouseTarget); }; // prevent links from being followed in the canvas - var handleLinkInCanvas = function(e) { + var handleLinkInCanvas = function (e) { e.preventDefault(); return false; }; @@ -2313,16 +2308,16 @@ var getMouseTarget = this.getMouseTarget = function(evt) { // Added mouseup to the container here. // TODO(codedread): Figure out why after the Closure compiler, the window mouseup is ignored. $(container).mousedown(mouseDown).mousemove(mouseMove).click(handleLinkInCanvas).dblclick(dblClick).mouseup(mouseUp); -// $(window).mouseup(mouseUp); + // $(window).mouseup(mouseUp); - //TODO(rafaelcastrocouto): User preference for shift key and zoom factor - $(container).bind('mousewheel DOMMouseScroll', function(e){ - //if (!e.shiftKey) {return;} + // TODO(rafaelcastrocouto): User preference for shift key and zoom factor + $(container).bind('mousewheel DOMMouseScroll', function (e) { + // if (!e.shiftKey) { return; } e.preventDefault(); var evt = e.originalEvent; - root_sctm = $('#svgcontent g')[0].getScreenCTM().inverse(); - var pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ); + rootSctm = $('#svgcontent g')[0].getScreenCTM().inverse(); + var pt = svgedit.math.transformPoint(evt.pageX, evt.pageY, rootSctm); var bbox = { 'x': pt.x, @@ -2332,31 +2327,29 @@ var getMouseTarget = this.getMouseTarget = function(evt) { }; var delta = (evt.wheelDelta) ? evt.wheelDelta : (evt.detail) ? -evt.detail : 0; - if (!delta) {return;} + if (!delta) { return; } - bbox.factor = Math.max(3/4, Math.min(4/3, (delta))); + bbox.factor = Math.max(3 / 4, Math.min(4 / 3, (delta))); call('zoomed', bbox); }); - }()); - // Group: Text edit functions // Functions relating to editing text elements -textActions = canvas.textActions = (function() { +textActions = canvas.textActions = (function () { var curtext; var textinput; var cursor; var selblock; var blinker; var chardata = []; - var textbb, transbb; + var textbb; // , transbb; var matrix; - var last_x, last_y; - var allow_dbl; + var lastX, lastY; + var allowDbl; - function setCursor(index) { + function setCursor (index) { var empty = (textinput.value === ''); $(textinput).focus(); @@ -2364,7 +2357,7 @@ textActions = canvas.textActions = (function() { if (empty) { index = 0; } else { - if (textinput.selectionEnd !== textinput.selectionStart) {return;} + if (textinput.selectionEnd !== textinput.selectionStart) { return; } index = textinput.selectionEnd; } } @@ -2386,28 +2379,28 @@ textActions = canvas.textActions = (function() { } if (!blinker) { - blinker = setInterval(function() { + blinker = setInterval(function () { var show = (cursor.getAttribute('display') === 'none'); - cursor.setAttribute('display', show?'inline':'none'); + cursor.setAttribute('display', show ? 'inline' : 'none'); }, 600); } - var start_pt = ptToScreen(charbb.x, textbb.y); - var end_pt = ptToScreen(charbb.x, (textbb.y + textbb.height)); + var startPt = ptToScreen(charbb.x, textbb.y); + var endPt = ptToScreen(charbb.x, (textbb.y + textbb.height)); svgedit.utilities.assignAttributes(cursor, { - x1: start_pt.x, - y1: start_pt.y, - x2: end_pt.x, - y2: end_pt.y, + x1: startPt.x, + y1: startPt.y, + x2: endPt.x, + y2: endPt.y, visibility: 'visible', display: 'inline' }); - if (selblock) {selblock.setAttribute('d', '');} + if (selblock) { selblock.setAttribute('d', ''); } } - function setSelection(start, end, skipInput) { + function setSelection (start, end, skipInput) { if (start === end) { setCursor(end); return; @@ -2419,7 +2412,6 @@ textActions = canvas.textActions = (function() { selblock = svgedit.utilities.getElem('text_selectblock'); if (!selblock) { - selblock = document.createElementNS(NS.SVG, 'path'); svgedit.utilities.assignAttributes(selblock, { id: 'text_selectblock', @@ -2440,10 +2432,10 @@ textActions = canvas.textActions = (function() { bl = ptToScreen(startbb.x, textbb.y + textbb.height), br = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y + textbb.height); - var dstr = 'M' + tl.x + ',' + tl.y - + ' L' + tr.x + ',' + tr.y - + ' ' + br.x + ',' + br.y - + ' ' + bl.x + ',' + bl.y + 'z'; + var dstr = 'M' + tl.x + ',' + tl.y + + ' L' + tr.x + ',' + tr.y + + ' ' + br.x + ',' + br.y + + ' ' + bl.x + ',' + bl.y + 'z'; svgedit.utilities.assignAttributes(selblock, { d: dstr, @@ -2451,38 +2443,38 @@ textActions = canvas.textActions = (function() { }); } - function getIndexFromPoint(mouse_x, mouse_y) { + function getIndexFromPoint (mouseX, mouseY) { // Position cursor here var pt = svgroot.createSVGPoint(); - pt.x = mouse_x; - pt.y = mouse_y; + pt.x = mouseX; + pt.y = mouseY; // No content, so return 0 - if (chardata.length == 1) {return 0;} + if (chardata.length === 1) { return 0; } // Determine if cursor should be on left or right of character var charpos = curtext.getCharNumAtPosition(pt); if (charpos < 0) { // Out of text range, look at mouse coords charpos = chardata.length - 2; - if (mouse_x <= chardata[0].x) { + if (mouseX <= chardata[0].x) { charpos = 0; } } else if (charpos >= chardata.length - 2) { charpos = chardata.length - 2; } var charbb = chardata[charpos]; - var mid = charbb.x + (charbb.width/2); - if (mouse_x > mid) { + var mid = charbb.x + (charbb.width / 2); + if (mouseX > mid) { charpos++; } return charpos; } - function setCursorFromPoint(mouse_x, mouse_y) { - setCursor(getIndexFromPoint(mouse_x, mouse_y)); + function setCursorFromPoint (mouseX, mouseY) { + setCursor(getIndexFromPoint(mouseX, mouseY)); } - function setEndSelectionFromPoint(x, y, apply) { + function setEndSelectionFromPoint (x, y, apply) { var i1 = textinput.selectionStart; var i2 = getIndexFromPoint(x, y); @@ -2491,14 +2483,14 @@ textActions = canvas.textActions = (function() { setSelection(start, end, !apply); } - function screenToPt(x_in, y_in) { + function screenToPt (xIn, yIn) { var out = { - x: x_in, - y: y_in + x: xIn, + y: yIn }; - out.x /= current_zoom; - out.y /= current_zoom; + out.x /= currentZoom; + out.y /= currentZoom; if (matrix) { var pt = svgedit.math.transformPoint(out.x, out.y, matrix.inverse()); @@ -2509,10 +2501,10 @@ textActions = canvas.textActions = (function() { return out; } - function ptToScreen(x_in, y_in) { + function ptToScreen (xIn, yIn) { var out = { - x: x_in, - y: y_in + x: xIn, + y: yIn }; if (matrix) { @@ -2521,107 +2513,109 @@ textActions = canvas.textActions = (function() { out.y = pt.y; } - out.x *= current_zoom; - out.y *= current_zoom; + out.x *= currentZoom; + out.y *= currentZoom; return out; } - function hideCursor() { + /* + // Not currently in use + function hideCursor () { if (cursor) { cursor.setAttribute('visibility', 'hidden'); } } + */ - function selectAll(evt) { + function selectAll (evt) { setSelection(0, curtext.textContent.length); $(this).unbind(evt); } - function selectWord(evt) { - if (!allow_dbl || !curtext) {return;} + function selectWord (evt) { + if (!allowDbl || !curtext) { return; } - var ept = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ), - mouse_x = ept.x * current_zoom, - mouse_y = ept.y * current_zoom; - var pt = screenToPt(mouse_x, mouse_y); + var ept = svgedit.math.transformPoint(evt.pageX, evt.pageY, rootSctm), + mouseX = ept.x * currentZoom, + mouseY = ept.y * currentZoom; + var pt = screenToPt(mouseX, mouseY); var index = getIndexFromPoint(pt.x, pt.y); var str = curtext.textContent; var first = str.substr(0, index).replace(/[a-z0-9]+$/i, '').length; var m = str.substr(index).match(/^[a-z0-9]+/i); - var last = (m?m[0].length:0) + index; + var last = (m ? m[0].length : 0) + index; setSelection(first, last); // Set tripleclick $(evt.target).click(selectAll); - setTimeout(function() { + setTimeout(function () { $(evt.target).unbind('click', selectAll); }, 300); - } return { - select: function(target, x, y) { + select: function (target, x, y) { curtext = target; textActions.toEditMode(x, y); }, - start: function(elem) { + start: function (elem) { curtext = elem; textActions.toEditMode(); }, - mouseDown: function(evt, mouse_target, start_x, start_y) { - var pt = screenToPt(start_x, start_y); + mouseDown: function (evt, mouseTarget, startX, startY) { + var pt = screenToPt(startX, startY); textinput.focus(); setCursorFromPoint(pt.x, pt.y); - last_x = start_x; - last_y = start_y; + lastX = startX; + lastY = startY; // TODO: Find way to block native selection }, - mouseMove: function(mouse_x, mouse_y) { - var pt = screenToPt(mouse_x, mouse_y); + mouseMove: function (mouseX, mouseY) { + var pt = screenToPt(mouseX, mouseY); setEndSelectionFromPoint(pt.x, pt.y); }, - mouseUp: function(evt, mouse_x, mouse_y) { - var pt = screenToPt(mouse_x, mouse_y); + mouseUp: function (evt, mouseX, mouseY) { + var pt = screenToPt(mouseX, mouseY); setEndSelectionFromPoint(pt.x, pt.y, true); // TODO: Find a way to make this work: Use transformed BBox instead of evt.target -// if (last_x === mouse_x && last_y === mouse_y -// && !svgedit.math.rectsIntersect(transbb, {x: pt.x, y: pt.y, width:0, height:0})) { -// textActions.toSelectMode(true); -// } + // if (lastX === mouseX && lastY === mouseY + // && !svgedit.math.rectsIntersect(transbb, {x: pt.x, y: pt.y, width: 0, height: 0})) { + // textActions.toSelectMode(true); + // } if ( - evt.target !== curtext - && mouse_x < last_x + 2 - && mouse_x > last_x - 2 - && mouse_y < last_y + 2 - && mouse_y > last_y - 2) { - + evt.target !== curtext && + mouseX < lastX + 2 && + mouseX > lastX - 2 && + mouseY < lastY + 2 && + mouseY > lastY - 2 + ) { textActions.toSelectMode(true); } - }, setCursor: setCursor, - toEditMode: function(x, y) { - allow_dbl = false; - current_mode = 'textedit'; + toEditMode: function (x, y) { + allowDbl = false; + currentMode = 'textedit'; selectorManager.requestSelector(curtext).showGrips(false); // Make selector group accept clicks - var sel = selectorManager.requestSelector(curtext).selectorRect; + /* var selector = */ selectorManager.requestSelector(curtext); // Do we need this? Has side effect of setting lock, so keeping for now, but next line wasn't being used + // var sel = selector.selectorRect; textActions.init(); $(curtext).css('cursor', 'text'); -// if (svgedit.browser.supportsEditableText()) { -// curtext.setAttribute('editable', 'simple'); -// return; -// } + // if (svgedit.browser.supportsEditableText()) { + // curtext.setAttribute('editable', 'simple'); + // return; + // } if (!arguments.length) { setCursor(); @@ -2630,16 +2624,16 @@ textActions = canvas.textActions = (function() { setCursorFromPoint(pt.x, pt.y); } - setTimeout(function() { - allow_dbl = true; + setTimeout(function () { + allowDbl = true; }, 300); }, - toSelectMode: function(selectElem) { - current_mode = 'select'; + toSelectMode: function (selectElem) { + currentMode = 'select'; clearInterval(blinker); blinker = null; - if (selblock) {$(selblock).attr('display', 'none');} - if (cursor) {$(cursor).attr('visibility', 'hidden');} + if (selblock) { $(selblock).attr('display', 'none'); } + if (cursor) { $(cursor).attr('visibility', 'hidden'); } $(curtext).css('cursor', 'move'); if (selectElem) { @@ -2658,26 +2652,26 @@ textActions = canvas.textActions = (function() { curtext = false; -// if (svgedit.browser.supportsEditableText()) { -// curtext.removeAttribute('editable'); -// } + // if (svgedit.browser.supportsEditableText()) { + // curtext.removeAttribute('editable'); + // } }, - setInputElem: function(elem) { + setInputElem: function (elem) { textinput = elem; -// $(textinput).blur(hideCursor); + // $(textinput).blur(hideCursor); }, - clear: function() { - if (current_mode == 'textedit') { + clear: function () { + if (currentMode === 'textedit') { textActions.toSelectMode(); } }, - init: function(inputElem) { - if (!curtext) {return;} + init: function (inputElem) { + if (!curtext) { return; } var i, end; -// if (svgedit.browser.supportsEditableText()) { -// curtext.select(); -// return; -// } + // if (svgedit.browser.supportsEditableText()) { + // curtext.select(); + // return; + // } if (!curtext.parentNode) { // Result of the ffClone, need to get correct element @@ -2701,20 +2695,20 @@ textActions = canvas.textActions = (function() { $(curtext).unbind('dblclick', selectWord).dblclick(selectWord); if (!len) { - end = {x: textbb.x + (textbb.width/2), width: 0}; + end = {x: textbb.x + (textbb.width / 2), width: 0}; } - for (i=0; i= 0) { + if (this.selected_pts.indexOf(index) === -1 && index >= 0) { this.selected_pts.push(index); } } @@ -2791,14 +2784,14 @@ pathActions = canvas.pathActions = function() { call('selected', grips); }; - current_path = null; - var drawn_path = null, - hasMoved = false; + currentPath = null; + drawnPath = null; + var hasMoved = false; // This function converts a polyline (created by the fh_path tool) into // a path element and coverts every three line segments into a single bezier // curve in an attempt to smooth out the free-hand - var smoothPolylineIntoPath = function(element) { + var smoothPolylineIntoPath = function (element) { var i, points = element.points; var N = points.numberOfItems; if (N >= 4) { @@ -2818,20 +2811,20 @@ pathActions = canvas.pathActions = function() { var curpos = points.getItem(0), prevCtlPt = null; var d = []; d.push(['M', curpos.x, ',', curpos.y, ' C'].join('')); - for (i = 1; i <= (N-4); i += 3) { + for (i = 1; i <= (N - 4); i += 3) { var ct1 = points.getItem(i); - var ct2 = points.getItem(i+1); - var end = points.getItem(i+2); + var ct2 = points.getItem(i + 1); + var end = points.getItem(i + 2); // if the previous segment had a control point, we want to smooth out // the control points on both sides if (prevCtlPt) { - var newpts = svgedit.path.smoothControlPoints( prevCtlPt, ct1, curpos ); - if (newpts && newpts.length == 2) { - var prevArr = d[d.length-1].split(','); + var newpts = svgedit.path.smoothControlPoints(prevCtlPt, ct1, curpos); + if (newpts && newpts.length === 2) { + var prevArr = d[d.length - 1].split(','); prevArr[2] = newpts[0].x; prevArr[3] = newpts[0].y; - d[d.length-1] = prevArr.join(','); + d[d.length - 1] = prevArr.join(','); ct1 = newpts[1]; } } @@ -2866,22 +2859,22 @@ pathActions = canvas.pathActions = function() { }; return { - mouseDown: function(evt, mouse_target, start_x, start_y) { + mouseDown: function (evt, mouseTarget, startX, startY) { var id; - if (current_mode === 'path') { - mouse_x = start_x; - mouse_y = start_y; + if (currentMode === 'path') { + var mouseX = startX; // Was this meant to work with the other `mouseX`? (was defined globally so adding `var` to at least avoid a global) + var mouseY = startY; // Was this meant to work with the other `mouseY`? (was defined globally so adding `var` to at least avoid a global) - var x = mouse_x/current_zoom, - y = mouse_y/current_zoom, + var x = mouseX / currentZoom, + y = mouseY / currentZoom, stretchy = svgedit.utilities.getElem('path_stretch_line'); newPoint = [x, y]; - if (curConfig.gridSnapping){ + if (curConfig.gridSnapping) { x = svgedit.utilities.snapToGrid(x); y = svgedit.utilities.snapToGrid(y); - mouse_x = svgedit.utilities.snapToGrid(mouse_x); - mouse_y = svgedit.utilities.snapToGrid(mouse_y); + mouseX = svgedit.utilities.snapToGrid(mouseX); + mouseY = svgedit.utilities.snapToGrid(mouseY); } if (!stretchy) { @@ -2899,33 +2892,35 @@ pathActions = canvas.pathActions = function() { var keep = null; var index; // if pts array is empty, create path element with M at current point - if (!drawn_path) { - d_attr = 'M' + x + ',' + y + ' '; - drawn_path = addSvgElementFromJson({ + if (!drawnPath) { + var dAttr = 'M' + x + ',' + y + ' '; // Was this meant to work with the other `dAttr`? (was defined globally so adding `var` to at least avoid a global) + drawnPath = addSvgElementFromJson({ element: 'path', curStyles: true, attr: { - d: d_attr, + d: dAttr, id: getNextId(), - opacity: cur_shape.opacity / 2 + opacity: curShape.opacity / 2 } }); // set stretchy line to first point - stretchy.setAttribute('d', ['M', mouse_x, mouse_y, mouse_x, mouse_y].join(' ')); + stretchy.setAttribute('d', ['M', mouseX, mouseY, mouseX, mouseY].join(' ')); index = subpath ? svgedit.path.path.segs.length : 0; - svgedit.path.addPointGrip(index, mouse_x, mouse_y); + svgedit.path.addPointGrip(index, mouseX, mouseY); } else { // determine if we clicked on an existing point - var seglist = drawn_path.pathSegList; + var seglist = drawnPath.pathSegList; var i = seglist.numberOfItems; - var FUZZ = 6/current_zoom; + var FUZZ = 6 / currentZoom; var clickOnPoint = false; while (i) { - i --; + i--; var item = seglist.getItem(i); var px = item.x, py = item.y; // found a matching point - if ( x >= (px-FUZZ) && x <= (px+FUZZ) && y >= (py-FUZZ) && y <= (py+FUZZ) ) { + if (x >= (px - FUZZ) && x <= (px + FUZZ) && + y >= (py - FUZZ) && y <= (py + FUZZ) + ) { clickOnPoint = true; break; } @@ -2939,7 +2934,7 @@ pathActions = canvas.pathActions = function() { var newpath = svgedit.utilities.getElem(id); var newseg; - var s_seg; + var sSeg; var len = seglist.numberOfItems; // if we clicked on an existing point, then we are done this path, commit it // (i, i+1) are the x,y that were clicked on @@ -2950,25 +2945,24 @@ pathActions = canvas.pathActions = function() { // otherwise, close the path if (i <= 1 && len >= 2) { // Create end segment - var abs_x = seglist.getItem(0).x; - var abs_y = seglist.getItem(0).y; + var absX = seglist.getItem(0).x; + var absY = seglist.getItem(0).y; - - s_seg = stretchy.pathSegList.getItem(1); - if (s_seg.pathSegType === 4) { - newseg = drawn_path.createSVGPathSegLinetoAbs(abs_x, abs_y); + sSeg = stretchy.pathSegList.getItem(1); + if (sSeg.pathSegType === 4) { + newseg = drawnPath.createSVGPathSegLinetoAbs(absX, absY); } else { - newseg = drawn_path.createSVGPathSegCurvetoCubicAbs( - abs_x, - abs_y, - s_seg.x1 / current_zoom, - s_seg.y1 / current_zoom, - abs_x, - abs_y + newseg = drawnPath.createSVGPathSegCurvetoCubicAbs( + absX, + absY, + sSeg.x1 / currentZoom, + sSeg.y1 / currentZoom, + absX, + absY ); } - var endseg = drawn_path.createSVGPathSegClosePath(); + var endseg = drawnPath.createSVGPathSegClosePath(); seglist.appendItem(newseg); seglist.appendItem(endseg); } else if (len < 3) { @@ -2978,8 +2972,8 @@ pathActions = canvas.pathActions = function() { $(stretchy).remove(); // This will signal to commit the path - element = newpath; - drawn_path = null; + // var element = newpath; // Other event handlers define own `element`, so this was probably not meant to interact with them or one which shares state (as there were none); I therefore adding a missing `var` to avoid a global + drawnPath = null; started = false; if (subpath) { @@ -2987,9 +2981,9 @@ pathActions = canvas.pathActions = function() { svgedit.coords.remapElement(newpath, {}, svgedit.path.path.matrix.inverse()); } - var new_d = newpath.getAttribute('d'); - var orig_d = $(svgedit.path.path.elem).attr('d'); - $(svgedit.path.path.elem).attr('d', orig_d + new_d); + var newD = newpath.getAttribute('d'); + var origD = $(svgedit.path.path.elem).attr('d'); + $(svgedit.path.path.elem).attr('d', origD + newD); $(newpath).remove(); if (svgedit.path.path.matrix) { svgedit.path.recalcRotatedPath(); @@ -2999,9 +2993,8 @@ pathActions = canvas.pathActions = function() { svgedit.path.path.selectPt(); return false; } - } // else, create a new point, update path element - else { + } else { // Checks if current target or parents are #svgcontent if (!$.contains(container, getMouseTarget(evt))) { // Clicked outside canvas, so don't make point @@ -3009,8 +3002,8 @@ pathActions = canvas.pathActions = function() { return false; } - var num = drawn_path.pathSegList.numberOfItems; - var last = drawn_path.pathSegList.getItem(num -1); + var num = drawnPath.pathSegList.numberOfItems; + var last = drawnPath.pathSegList.getItem(num - 1); var lastx = last.x, lasty = last.y; if (evt.shiftKey) { @@ -3020,29 +3013,29 @@ pathActions = canvas.pathActions = function() { } // Use the segment defined by stretchy - s_seg = stretchy.pathSegList.getItem(1); - if (s_seg.pathSegType === 4) { - newseg = drawn_path.createSVGPathSegLinetoAbs(round(x), round(y)); + sSeg = stretchy.pathSegList.getItem(1); + if (sSeg.pathSegType === 4) { + newseg = drawnPath.createSVGPathSegLinetoAbs(round(x), round(y)); } else { - newseg = drawn_path.createSVGPathSegCurvetoCubicAbs( + newseg = drawnPath.createSVGPathSegCurvetoCubicAbs( round(x), round(y), - s_seg.x1 / current_zoom, - s_seg.y1 / current_zoom, - s_seg.x2 / current_zoom, - s_seg.y2 / current_zoom + sSeg.x1 / currentZoom, + sSeg.y1 / currentZoom, + sSeg.x2 / currentZoom, + sSeg.y2 / currentZoom ); } - drawn_path.pathSegList.appendItem(newseg); + drawnPath.pathSegList.appendItem(newseg); - x *= current_zoom; - y *= current_zoom; + x *= currentZoom; + y *= currentZoom; // set stretchy line to latest point stretchy.setAttribute('d', ['M', x, y, x, y].join(' ')); index = num; - if (subpath) {index += svgedit.path.path.segs.length;} + if (subpath) { index += svgedit.path.path.segs.length; } svgedit.path.addPointGrip(index, x, y); } // keep = true; @@ -3051,18 +3044,18 @@ pathActions = canvas.pathActions = function() { return; } - // TODO: Make sure current_path isn't null at this point - if (!svgedit.path.path) {return;} + // TODO: Make sure currentPath isn't null at this point + if (!svgedit.path.path) { return; } svgedit.path.path.storeD(); id = evt.target.id; - var cur_pt; - if (id.substr(0,14) == 'pathpointgrip_') { + var curPt; + if (id.substr(0, 14) === 'pathpointgrip_') { // Select this point - cur_pt = svgedit.path.path.cur_pt = parseInt(id.substr(14)); - svgedit.path.path.dragging = [start_x, start_y]; - var seg = svgedit.path.path.segs[cur_pt]; + curPt = svgedit.path.path.cur_pt = parseInt(id.substr(14)); + svgedit.path.path.dragging = [startX, startY]; + var seg = svgedit.path.path.segs[curPt]; // only clear selection if shift is not pressed (otherwise, add // node to selection) @@ -3070,19 +3063,19 @@ pathActions = canvas.pathActions = function() { if (svgedit.path.path.selected_pts.length <= 1 || !seg.selected) { svgedit.path.path.clearSelection(); } - svgedit.path.path.addPtsToSelection(cur_pt); + svgedit.path.path.addPtsToSelection(curPt); } else if (seg.selected) { - svgedit.path.path.removePtFromSelection(cur_pt); + svgedit.path.path.removePtFromSelection(curPt); } else { - svgedit.path.path.addPtsToSelection(cur_pt); + svgedit.path.path.addPtsToSelection(curPt); } - } else if (id.indexOf('ctrlpointgrip_') == 0) { - svgedit.path.path.dragging = [start_x, start_y]; + } else if (id.indexOf('ctrlpointgrip_') === 0) { + svgedit.path.path.dragging = [startX, startY]; var parts = id.split('_')[1].split('c'); - cur_pt = Number(parts[0]); - var ctrl_num = Number(parts[1]); - svgedit.path.path.selectPt(cur_pt, ctrl_num); + curPt = Number(parts[0]); + var ctrlNum = Number(parts[1]); + svgedit.path.path.selectPt(curPt, ctrlNum); } // Start selection box @@ -3091,85 +3084,85 @@ pathActions = canvas.pathActions = function() { rubberBox = selectorManager.getRubberBandBox(); } svgedit.utilities.assignAttributes(rubberBox, { - 'x': start_x * current_zoom, - 'y': start_y * current_zoom, - 'width': 0, - 'height': 0, - 'display': 'inline' + 'x': startX * currentZoom, + 'y': startY * currentZoom, + 'width': 0, + 'height': 0, + 'display': 'inline' }, 100); } }, - mouseMove: function(mouse_x, mouse_y) { + mouseMove: function (mouseX, mouseY) { hasMoved = true; - if (current_mode === 'path') { - if (!drawn_path) {return;} - var seglist = drawn_path.pathSegList; + if (currentMode === 'path') { + if (!drawnPath) { return; } + var seglist = drawnPath.pathSegList; var index = seglist.numberOfItems - 1; if (newPoint) { // First point -// if (!index) {return;} + // if (!index) { return; } // Set control points var pointGrip1 = svgedit.path.addCtrlGrip('1c1'); var pointGrip2 = svgedit.path.addCtrlGrip('0c2'); // dragging pointGrip1 - pointGrip1.setAttribute('cx', mouse_x); - pointGrip1.setAttribute('cy', mouse_y); + pointGrip1.setAttribute('cx', mouseX); + pointGrip1.setAttribute('cy', mouseY); pointGrip1.setAttribute('display', 'inline'); - var pt_x = newPoint[0]; - var pt_y = newPoint[1]; + var ptX = newPoint[0]; + var ptY = newPoint[1]; // set curve - var seg = seglist.getItem(index); - var cur_x = mouse_x / current_zoom; - var cur_y = mouse_y / current_zoom; - var alt_x = (pt_x + (pt_x - cur_x)); - var alt_y = (pt_y + (pt_y - cur_y)); + // var seg = seglist.getItem(index); + var curX = mouseX / currentZoom; + var curY = mouseY / currentZoom; + var altX = (ptX + (ptX - curX)); + var altY = (ptY + (ptY - curY)); - pointGrip2.setAttribute('cx', alt_x * current_zoom); - pointGrip2.setAttribute('cy', alt_y * current_zoom); + pointGrip2.setAttribute('cx', altX * currentZoom); + pointGrip2.setAttribute('cy', altY * currentZoom); pointGrip2.setAttribute('display', 'inline'); var ctrlLine = svgedit.path.getCtrlLine(1); svgedit.utilities.assignAttributes(ctrlLine, { - x1: mouse_x, - y1: mouse_y, - x2: alt_x * current_zoom, - y2: alt_y * current_zoom, + x1: mouseX, + y1: mouseY, + x2: altX * currentZoom, + y2: altY * currentZoom, display: 'inline' }); if (index === 0) { - firstCtrl = [mouse_x, mouse_y]; + firstCtrl = [mouseX, mouseY]; } else { var last = seglist.getItem(index - 1); - var last_x = last.x; - var last_y = last.y; + var lastX = last.x; + var lastY = last.y; if (last.pathSegType === 6) { - last_x += (last_x - last.x2); - last_y += (last_y - last.y2); + lastX += (lastX - last.x2); + lastY += (lastY - last.y2); } else if (firstCtrl) { - last_x = firstCtrl[0]/current_zoom; - last_y = firstCtrl[1]/current_zoom; + lastX = firstCtrl[0] / currentZoom; + lastY = firstCtrl[1] / currentZoom; } - svgedit.path.replacePathSeg(6, index, [pt_x, pt_y, last_x, last_y, alt_x, alt_y], drawn_path); + svgedit.path.replacePathSeg(6, index, [ptX, ptY, lastX, lastY, altX, altY], drawnPath); } } else { var stretchy = svgedit.utilities.getElem('path_stretch_line'); if (stretchy) { var prev = seglist.getItem(index); if (prev.pathSegType === 6) { - var prev_x = prev.x + (prev.x - prev.x2); - var prev_y = prev.y + (prev.y - prev.y2); - svgedit.path.replacePathSeg(6, 1, [mouse_x, mouse_y, prev_x * current_zoom, prev_y * current_zoom, mouse_x, mouse_y], stretchy); + var prevX = prev.x + (prev.x - prev.x2); + var prevY = prev.y + (prev.y - prev.y2); + svgedit.path.replacePathSeg(6, 1, [mouseX, mouseY, prevX * currentZoom, prevY * currentZoom, mouseX, mouseY], stretchy); } else if (firstCtrl) { - svgedit.path.replacePathSeg(6, 1, [mouse_x, mouse_y, firstCtrl[0], firstCtrl[1], mouse_x, mouse_y], stretchy); + svgedit.path.replacePathSeg(6, 1, [mouseX, mouseY, firstCtrl[0], firstCtrl[1], mouseX, mouseY], stretchy); } else { - svgedit.path.replacePathSeg(4, 1, [mouse_x, mouse_y], stretchy); + svgedit.path.replacePathSeg(4, 1, [mouseX, mouseY], stretchy); } } } @@ -3182,50 +3175,48 @@ pathActions = canvas.pathActions = function() { y: svgedit.path.path.dragging[1] }, svgedit.path.path); var mpt = svgedit.path.getPointFromGrip({ - x: mouse_x, - y: mouse_y + x: mouseX, + y: mouseY }, svgedit.path.path); - var diff_x = mpt.x - pt.x; - var diff_y = mpt.y - pt.y; - svgedit.path.path.dragging = [mouse_x, mouse_y]; + var diffX = mpt.x - pt.x; + var diffY = mpt.y - pt.y; + svgedit.path.path.dragging = [mouseX, mouseY]; if (svgedit.path.path.dragctrl) { - svgedit.path.path.moveCtrl(diff_x, diff_y); + svgedit.path.path.moveCtrl(diffX, diffY); } else { - svgedit.path.path.movePts(diff_x, diff_y); + svgedit.path.path.movePts(diffX, diffY); } } else { svgedit.path.path.selected_pts = []; - svgedit.path.path.eachSeg(function(i) { + svgedit.path.path.eachSeg(function (i) { var seg = this; - if (!seg.next && !seg.prev) {return;} + if (!seg.next && !seg.prev) { return; } - var item = seg.item; + // var item = seg.item; var rbb = rubberBox.getBBox(); var pt = svgedit.path.getGripPt(seg); - var pt_bb = { + var ptBb = { x: pt.x, y: pt.y, width: 0, height: 0 }; - var sel = svgedit.math.rectsIntersect(rbb, pt_bb); + var sel = svgedit.math.rectsIntersect(rbb, ptBb); this.select(sel); - //Note that addPtsToSelection is not being run - if (sel) {svgedit.path.path.selected_pts.push(seg.index);} + // Note that addPtsToSelection is not being run + if (sel) { svgedit.path.path.selected_pts.push(seg.index); } }); - } }, - mouseUp: function(evt, element, mouse_x, mouse_y) { - + mouseUp: function (evt, element, mouseX, mouseY) { // Create mode - if (current_mode === 'path') { + if (currentMode === 'path') { newPoint = null; - if (!drawn_path) { + if (!drawnPath) { element = svgedit.utilities.getElem(getId()); started = false; firstCtrl = null; @@ -3240,7 +3231,7 @@ pathActions = canvas.pathActions = function() { // Edit mode if (svgedit.path.path.dragging) { - var last_pt = svgedit.path.path.cur_pt; + var lastPt = svgedit.path.path.cur_pt; svgedit.path.path.dragging = false; svgedit.path.path.dragctrl = false; @@ -3251,9 +3242,9 @@ pathActions = canvas.pathActions = function() { } if (!evt.shiftKey && !hasMoved) { - svgedit.path.path.selectPt(last_pt); + svgedit.path.path.selectPt(lastPt); } - } else if (rubberBox && rubberBox.getAttribute('display') != 'none') { + } else if (rubberBox && rubberBox.getAttribute('display') !== 'none') { // Done with multi-node-select rubberBox.setAttribute('display', 'none'); @@ -3267,19 +3258,19 @@ pathActions = canvas.pathActions = function() { } hasMoved = false; }, - toEditMode: function(element) { + toEditMode: function (element) { svgedit.path.path = svgedit.path.getPath_(element); - current_mode = 'pathedit'; + currentMode = 'pathedit'; clearSelection(); svgedit.path.path.show(true).update(); svgedit.path.path.oldbbox = svgedit.utilities.getBBox(svgedit.path.path.elem); subpath = false; }, - toSelectMode: function(elem) { - var selPath = (elem == svgedit.path.path.elem); - current_mode = 'select'; + toSelectMode: function (elem) { + var selPath = (elem === svgedit.path.path.elem); + currentMode = 'select'; svgedit.path.path.show(false); - current_path = false; + currentPath = false; clearSelection(); if (svgedit.path.path.matrix) { @@ -3292,31 +3283,31 @@ pathActions = canvas.pathActions = function() { addToSelection([elem], true); } }, - addSubPath: function(on) { + addSubPath: function (on) { if (on) { // Internally we go into "path" mode, but in the UI it will // still appear as if in "pathedit" mode. - current_mode = 'path'; + currentMode = 'path'; subpath = true; } else { pathActions.clear(true); pathActions.toEditMode(svgedit.path.path.elem); } }, - select: function(target) { - if (current_path === target) { + select: function (target) { + if (currentPath === target) { pathActions.toEditMode(target); - current_mode = 'pathedit'; - } // going into pathedit mode - else { - current_path = target; + currentMode = 'pathedit'; + // going into pathedit mode + } else { + currentPath = target; } }, - reorient: function() { + reorient: function () { var elem = selectedElements[0]; - if (!elem) {return;} + if (!elem) { return; } var angle = svgedit.utilities.getRotationAngle(elem); - if (angle == 0) {return;} + if (angle === 0) { return; } var batchCmd = new svgedit.history.BatchCommand('Reorient path'); var changes = { @@ -3338,22 +3329,22 @@ pathActions = canvas.pathActions = function() { call('changed', selectedElements); }, - clear: function(remove) { - current_path = null; - if (drawn_path) { + clear: function (remove) { + currentPath = null; + if (drawnPath) { var elem = svgedit.utilities.getElem(getId()); $(svgedit.utilities.getElem('path_stretch_line')).remove(); $(elem).remove(); $(svgedit.utilities.getElem('pathpointgrip_container')).find('*').attr('display', 'none'); - drawn_path = firstCtrl = null; + drawnPath = firstCtrl = null; started = false; - } else if (current_mode == 'pathedit') { + } else if (currentMode === 'pathedit') { this.toSelectMode(); } - if (svgedit.path.path) {svgedit.path.path.init().show(false);} + if (svgedit.path.path) { svgedit.path.path.init().show(false); } }, - resetOrientation: function(path) { - if (path == null || path.nodeName != 'path') {return false;} + resetOrientation: function (path) { + if (path == null || path.nodeName !== 'path') { return false; } var tlist = svgedit.transformlist.getTransformList(path); var m = svgedit.math.transformListToTransform(tlist).matrix; tlist.clear(); @@ -3364,23 +3355,22 @@ pathActions = canvas.pathActions = function() { // TODO: Find out why! // Presumed fixed in Opera 10.5, so commented out for now -// try { + // try { var len = segList.numberOfItems; -// } catch(err) { -// var fixed_d = pathActions.convertPath(path); -// path.setAttribute('d', fixed_d); -// segList = path.pathSegList; -// var len = segList.numberOfItems; -// } - var i, last_x, last_y; - + // } catch(err) { + // var fixed_d = pathActions.convertPath(path); + // path.setAttribute('d', fixed_d); + // segList = path.pathSegList; + // var len = segList.numberOfItems; + // } + var i; // , lastX, lastY; for (i = 0; i < len; ++i) { var seg = segList.getItem(i); var type = seg.pathSegType; - if (type == 1) {continue;} + if (type === 1) { continue; } var pts = []; - $.each(['',1,2], function(j, n) { - var x = seg['x'+n], y = seg['y'+n]; + $.each(['', 1, 2], function (j, n) { + var x = seg['x' + n], y = seg['y' + n]; if (x !== undefined && y !== undefined) { var pt = svgedit.math.transformPoint(x, y, m); pts.splice(pts.length, 0, pt.x, pt.y); @@ -3391,35 +3381,35 @@ pathActions = canvas.pathActions = function() { reorientGrads(path, m); }, - zoomChange: function() { - if (current_mode == 'pathedit') { + zoomChange: function () { + if (currentMode === 'pathedit') { svgedit.path.path.update(); } }, - getNodePoint: function() { - var sel_pt = svgedit.path.path.selected_pts.length ? svgedit.path.path.selected_pts[0] : 1; + getNodePoint: function () { + var selPt = svgedit.path.path.selected_pts.length ? svgedit.path.path.selected_pts[0] : 1; - var seg = svgedit.path.path.segs[sel_pt]; + var seg = svgedit.path.path.segs[selPt]; return { x: seg.item.x, y: seg.item.y, type: seg.type }; }, - linkControlPoints: function(linkPoints) { + linkControlPoints: function (linkPoints) { svgedit.path.setLinkControlPoints(linkPoints); }, - clonePathNode: function() { + clonePathNode: function () { svgedit.path.path.storeD(); - var sel_pts = svgedit.path.path.selected_pts; - var segs = svgedit.path.path.segs; + var selPts = svgedit.path.path.selected_pts; + // var segs = svgedit.path.path.segs; - var i = sel_pts.length; + var i = selPts.length; var nums = []; while (i--) { - var pt = sel_pts[i]; + var pt = selPts[i]; svgedit.path.path.addSeg(pt); nums.push(pt + i); @@ -3429,60 +3419,60 @@ pathActions = canvas.pathActions = function() { svgedit.path.path.endChanges('Clone path node(s)'); }, - opencloseSubPath: function() { - var sel_pts = svgedit.path.path.selected_pts; + opencloseSubPath: function () { + var selPts = svgedit.path.path.selected_pts; // Only allow one selected node for now - if (sel_pts.length !== 1) {return;} + if (selPts.length !== 1) { return; } var elem = svgedit.path.path.elem; var list = elem.pathSegList; - var len = list.numberOfItems; + // var len = list.numberOfItems; - var index = sel_pts[0]; + var index = selPts[0]; - var open_pt = null; - var start_item = null; + var openPt = null; + var startItem = null; // Check if subpath is already open - svgedit.path.path.eachSeg(function(i) { + svgedit.path.path.eachSeg(function (i) { if (this.type === 2 && i <= index) { - start_item = this.item; + startItem = this.item; } - if (i <= index) {return true;} + if (i <= index) { return true; } if (this.type === 2) { // Found M first, so open - open_pt = i; + openPt = i; return false; } if (this.type === 1) { // Found Z first, so closed - open_pt = false; + openPt = false; return false; } }); - if (open_pt == null) { + if (openPt == null) { // Single path, so close last seg - open_pt = svgedit.path.path.segs.length - 1; + openPt = svgedit.path.path.segs.length - 1; } - if (open_pt !== false) { + if (openPt !== false) { // Close this path // Create a line going to the previous "M" - var newseg = elem.createSVGPathSegLinetoAbs(start_item.x, start_item.y); + var newseg = elem.createSVGPathSegLinetoAbs(startItem.x, startItem.y); var closer = elem.createSVGPathSegClosePath(); - if (open_pt == svgedit.path.path.segs.length - 1) { + if (openPt === svgedit.path.path.segs.length - 1) { list.appendItem(newseg); list.appendItem(closer); } else { - svgedit.path.insertItemBefore(elem, closer, open_pt); - svgedit.path.insertItemBefore(elem, newseg, open_pt); + svgedit.path.insertItemBefore(elem, closer, openPt); + svgedit.path.insertItemBefore(elem, newseg, openPt); } - svgedit.path.path.init().selectPt(open_pt+1); + svgedit.path.path.init().selectPt(openPt + 1); return; } @@ -3501,92 +3491,91 @@ pathActions = canvas.pathActions = function() { return; } - var i, last_m, z_seg; + var i, lastM, zSeg; // Find this sub-path's closing point and remove - for (i = 0; i 0) { - var prev_type = segList.getItem(len-1).pathSegType; + var prevType = segList.getItem(len - 1).pathSegType; // Path has M M - if (prev_type === 2) { - remItems(len-1, 1); + if (prevType === 2) { + remItems(len - 1, 1); cleanup(); break; // Entire path ends with Z M - } else if (prev_type === 1 && segList.numberOfItems-1 === len) { + } else if (prevType === 1 && segList.numberOfItems - 1 === len) { remItems(len, 1); cleanup(); break; @@ -3610,7 +3599,7 @@ pathActions = canvas.pathActions = function() { svgedit.path.path.clearSelection(); // TODO: Find right way to select point now - // path.selectPt(sel_pt); + // path.selectPt(selPt); if (window.opera) { // Opera repaints incorrectly var cp = $(svgedit.path.path.elem); cp.attr('d', cp.attr('d')); @@ -3618,55 +3607,54 @@ pathActions = canvas.pathActions = function() { svgedit.path.path.endChanges('Delete path node(s)'); }, smoothPolylineIntoPath: smoothPolylineIntoPath, - setSegType: function(v) { + setSegType: function (v) { svgedit.path.path.setSegType(v); }, - moveNode: function(attr, newValue) { - var sel_pts = svgedit.path.path.selected_pts; - if (!sel_pts.length) {return;} + moveNode: function (attr, newValue) { + var selPts = svgedit.path.path.selected_pts; + if (!selPts.length) { return; } svgedit.path.path.storeD(); // Get first selected point - var seg = svgedit.path.path.segs[sel_pts[0]]; - var diff = {x:0, y:0}; + var seg = svgedit.path.path.segs[selPts[0]]; + var diff = {x: 0, y: 0}; diff[attr] = newValue - seg.item[attr]; seg.move(diff.x, diff.y); svgedit.path.path.endChanges('Move path point'); }, - fixEnd: function(elem) { + fixEnd: function (elem) { // Adds an extra segment if the last seg before a Z doesn't end // at its M point // M0,0 L0,100 L100,100 z var segList = elem.pathSegList; var len = segList.numberOfItems; - var i, last_m; + var i, lastM; for (i = 0; i < len; ++i) { var item = segList.getItem(i); if (item.pathSegType === 2) { - last_m = item; + lastM = item; } if (item.pathSegType === 1) { - var prev = segList.getItem(i-1); - if (prev.x != last_m.x || prev.y != last_m.y) { + var prev = segList.getItem(i - 1); + if (prev.x !== lastM.x || prev.y !== lastM.y) { // Add an L segment here - var newseg = elem.createSVGPathSegLinetoAbs(last_m.x, last_m.y); + var newseg = elem.createSVGPathSegLinetoAbs(lastM.x, lastM.y); svgedit.path.insertItemBefore(elem, newseg, i); // Can this be done better? pathActions.fixEnd(elem); break; } - } } - if (svgedit.browser.isWebkit()) {resetD(elem);} + if (svgedit.browser.isWebkit()) { resetD(elem); } }, // Convert a path to one with only absolute or relative values convertPath: svgedit.utilities.convertPath }; -}(); +})(); // end pathActions // Group: Serialization @@ -3677,34 +3665,34 @@ pathActions = canvas.pathActions = function() { // // Returns: // The amount of elements that were removed -var removeUnusedDefElems = this.removeUnusedDefElems = function() { +var removeUnusedDefElems = this.removeUnusedDefElems = function () { var defs = svgcontent.getElementsByTagNameNS(NS.SVG, 'defs'); - if (!defs || !defs.length) {return 0;} + if (!defs || !defs.length) { return 0; } -// if (!defs.firstChild) {return;} + // if (!defs.firstChild) { return; } - var defelem_uses = [], + var defelemUses = [], numRemoved = 0; var attrs = ['fill', 'stroke', 'filter', 'marker-start', 'marker-mid', 'marker-end']; var alen = attrs.length; - var all_els = svgcontent.getElementsByTagNameNS(NS.SVG, '*'); - var all_len = all_els.length; + var allEls = svgcontent.getElementsByTagNameNS(NS.SVG, '*'); + var allLen = allEls.length; var i, j; - for (i = 0; i < all_len; i++) { - var el = all_els[i]; + for (i = 0; i < allLen; i++) { + var el = allEls[i]; for (j = 0; j < alen; j++) { var ref = svgedit.utilities.getUrlFromAttr(el.getAttribute(attrs[j])); if (ref) { - defelem_uses.push(ref.substr(1)); + defelemUses.push(ref.substr(1)); } } // gradients can refer to other gradients var href = getHref(el); if (href && href.indexOf('#') === 0) { - defelem_uses.push(href.substr(1)); + defelemUses.push(href.substr(1)); } } @@ -3713,7 +3701,7 @@ var removeUnusedDefElems = this.removeUnusedDefElems = function() { while (i--) { var defelem = defelems[i]; var id = defelem.id; - if (defelem_uses.indexOf(id) < 0) { + if (defelemUses.indexOf(id) < 0) { // Not found, so remove (but remember) removedElements[id] = defelem; defelem.parentNode.removeChild(defelem); @@ -3729,49 +3717,49 @@ var removeUnusedDefElems = this.removeUnusedDefElems = function() { // // Returns: // String containing the SVG image for output -this.svgCanvasToString = function() { +this.svgCanvasToString = function () { // keep calling it until there are none to remove while (removeUnusedDefElems() > 0) {} pathActions.clear(true); // Keep SVG-Edit comment on top - $.each(svgcontent.childNodes, function(i, node) { + $.each(svgcontent.childNodes, function (i, node) { if (i && node.nodeType === 8 && node.data.indexOf('Created with') >= 0) { svgcontent.insertBefore(node, svgcontent.firstChild); } }); // Move out of in-group editing mode - if (current_group) { + if (currentGroup) { leaveContext(); - selectOnly([current_group]); + selectOnly([currentGroup]); } - var naked_svgs = []; + var nakedSvgs = []; // Unwrap gsvg if it has no special attributes (only id and style) - $(svgcontent).find('g:data(gsvg)').each(function() { + $(svgcontent).find('g:data(gsvg)').each(function () { var attrs = this.attributes; var len = attrs.length; var i; for (i = 0; i < len; i++) { - if (attrs[i].nodeName == 'id' || attrs[i].nodeName == 'style') { + if (attrs[i].nodeName === 'id' || attrs[i].nodeName === 'style') { len--; } } // No significant attributes, so ungroup if (len <= 0) { var svg = this.firstChild; - naked_svgs.push(svg); + nakedSvgs.push(svg); $(this).replaceWith(svg); } }); var output = this.svgToString(svgcontent, 0); // Rewrap gsvg - if (naked_svgs.length) { - $(naked_svgs).each(function() { + if (nakedSvgs.length) { + $(nakedSvgs).each(function () { groupSvgElem(this); }); } @@ -3788,11 +3776,11 @@ this.svgCanvasToString = function() { // // Returns: // String with the given element as an SVG tag -this.svgToString = function(elem, indent) { +this.svgToString = function (elem, indent) { var out = [], toXml = svgedit.utilities.toXml; var unit = curConfig.baseUnit; - var unit_re = new RegExp('^-?[\\d\\.]+' + unit + '$'); + var unitRe = new RegExp('^-?[\\d\\.]+' + unit + '$'); if (elem) { cleanupElement(elem); @@ -3801,7 +3789,7 @@ this.svgToString = function(elem, indent) { i, childs = elem.childNodes; - for (i = 0; i < indent; i++) {out.push(' ');} + for (i = 0; i < indent; i++) { out.push(' '); } out.push('<'); out.push(elem.nodeName); if (elem.id === 'svgcontent') { // Process root element separately @@ -3825,41 +3813,40 @@ this.svgToString = function(elem, indent) { res.h = svgedit.units.convertUnit(res.h, unit) + unit; } - out.push(' width="' + res.w + '" height="' + res.h + '"' + vb + ' xmlns="'+NS.SVG+'"'); + out.push(' width="' + res.w + '" height="' + res.h + '"' + vb + ' xmlns="' + NS.SVG + '"'); var nsuris = {}; // Check elements for namespaces, add if found - $(elem).find('*').andSelf().each(function() { - var el = this; + $(elem).find('*').andSelf().each(function () { + // var el = this; // for some elements have no attribute var uri = this.namespaceURI; - if (uri && !nsuris[uri] && nsMap[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml' ) { + if (uri && !nsuris[uri] && nsMap[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml') { nsuris[uri] = true; - out.push(' xmlns:' + nsMap[uri] + '="' + uri +'"'); + out.push(' xmlns:' + nsMap[uri] + '="' + uri + '"'); } - $.each(this.attributes, function(i, attr) { + $.each(this.attributes, function (i, attr) { var uri = attr.namespaceURI; - if (uri && !nsuris[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml' ) { + if (uri && !nsuris[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml') { nsuris[uri] = true; - out.push(' xmlns:' + nsMap[uri] + '="' + uri +'"'); + out.push(' xmlns:' + nsMap[uri] + '="' + uri + '"'); } }); }); i = attrs.length; - var attr_names = ['width', 'height', 'xmlns', 'x', 'y', 'viewBox', 'id', 'overflow']; + var attrNames = ['width', 'height', 'xmlns', 'x', 'y', 'viewBox', 'id', 'overflow']; while (i--) { attr = attrs.item(i); var attrVal = toXml(attr.value); // Namespaces have already been dealt with, so skip - if (attr.nodeName.indexOf('xmlns:') === 0) {continue;} + if (attr.nodeName.indexOf('xmlns:') === 0) { continue; } // only serialize attributes we don't use internally - if (attrVal != '' && attr_names.indexOf(attr.localName) == -1) { - + if (attrVal !== '' && attrNames.indexOf(attr.localName) === -1) { if (!attr.namespaceURI || nsMap[attr.namespaceURI]) { out.push(' '); out.push(attr.nodeName); out.push('="'); @@ -3869,39 +3856,39 @@ this.svgToString = function(elem, indent) { } } else { // Skip empty defs - if (elem.nodeName === 'defs' && !elem.firstChild) {return;} + if (elem.nodeName === 'defs' && !elem.firstChild) { return; } - var moz_attrs = ['-moz-math-font-style', '_moz-math-font-style']; + var mozAttrs = ['-moz-math-font-style', '_moz-math-font-style']; for (i = attrs.length - 1; i >= 0; i--) { attr = attrs.item(i); var attrVal = toXml(attr.value); - //remove bogus attributes added by Gecko - if (moz_attrs.indexOf(attr.localName) >= 0) {continue;} - if (attrVal != '') { - if (attrVal.indexOf('pointer-events') === 0) {continue;} - if (attr.localName === 'class' && attrVal.indexOf('se_') === 0) {continue;} + // remove bogus attributes added by Gecko + if (mozAttrs.indexOf(attr.localName) >= 0) { continue; } + if (attrVal !== '') { + if (attrVal.indexOf('pointer-events') === 0) { continue; } + if (attr.localName === 'class' && attrVal.indexOf('se_') === 0) { continue; } out.push(' '); - if (attr.localName === 'd') {attrVal = pathActions.convertPath(elem, true);} + if (attr.localName === 'd') { attrVal = pathActions.convertPath(elem, true); } if (!isNaN(attrVal)) { attrVal = svgedit.units.shortFloat(attrVal); - } else if (unit_re.test(attrVal)) { + } else if (unitRe.test(attrVal)) { attrVal = svgedit.units.shortFloat(attrVal) + unit; } // Embed images when saving - if (save_options.apply - && elem.nodeName === 'image' - && attr.localName === 'href' - && save_options.images - && save_options.images === 'embed') - { + if (saveOptions.apply && + elem.nodeName === 'image' && + attr.localName === 'href' && + saveOptions.images && + saveOptions.images === 'embed' + ) { var img = encodableImages[attrVal]; - if (img) {attrVal = img;} + if (img) { attrVal = img; } } // map various namespaces to our fixed namespace prefixes // (the default xmlns attribute itself does not get a prefix) - if (!attr.namespaceURI || attr.namespaceURI == NS.SVG || nsMap[attr.namespaceURI]) { + if (!attr.namespaceURI || attr.namespaceURI === NS.SVG || nsMap[attr.namespaceURI]) { out.push(attr.nodeName); out.push('="'); out.push(attrVal); out.push('"'); } @@ -3916,28 +3903,28 @@ this.svgToString = function(elem, indent) { for (i = 0; i < childs.length; i++) { var child = childs.item(i); - switch(child.nodeType) { + switch (child.nodeType) { case 1: // element node out.push('\n'); out.push(this.svgToString(childs.item(i), indent)); break; case 3: // text node var str = child.nodeValue.replace(/^\s+|\s+$/g, ''); - if (str != '') { + if (str !== '') { bOneLine = true; out.push(String(toXml(str))); } break; case 4: // cdata node out.push('\n'); - out.push(new Array(indent+1).join(' ')); + out.push(new Array(indent + 1).join(' ')); out.push(''); out.push(child.nodeValue); out.push(''); break; case 8: // comment out.push('\n'); - out.push(new Array(indent+1).join(' ')); + out.push(new Array(indent + 1).join(' ')); out.push(''); @@ -3947,7 +3934,7 @@ this.svgToString = function(elem, indent) { indent--; if (!bOneLine) { out.push('\n'); - for (i = 0; i < indent; i++) {out.push(' ');} + for (i = 0; i < indent; i++) { out.push(' '); } } out.push(''); } else { @@ -3964,9 +3951,9 @@ this.svgToString = function(elem, indent) { // val - String with the path/URL of the image // callback - Optional function to run when image data is found, supplies the // result (data URL or false) as first parameter. -this.embedImage = function(val, callback) { +this.embedImage = function (val, callback) { // load in the image and once it's loaded, get the dimensions - $(new Image()).load(function() { + $(new Image()).load(function () { // create a canvas the same size as the raster image var canvas = document.createElement('canvas'); canvas.width = this.width; @@ -3976,23 +3963,23 @@ this.embedImage = function(val, callback) { // retrieve the data: URL try { var urldata = ';svgedit_url=' + encodeURIComponent(val); - urldata = canvas.toDataURL().replace(';base64', urldata+';base64'); + urldata = canvas.toDataURL().replace(';base64', urldata + ';base64'); encodableImages[val] = urldata; - } catch(e) { + } catch (e) { encodableImages[val] = false; } - last_good_img_url = val; - if (callback) {callback(encodableImages[val]);} + lastGoodImgUrl = val; + if (callback) { callback(encodableImages[val]); } }).attr('src', val); }; // Function: setGoodImage // Sets a given URL to be a "last good image" URL -this.setGoodImage = function(val) { - last_good_img_url = val; +this.setGoodImage = function (val) { + lastGoodImgUrl = val; }; -this.open = function() { +this.open = function () { // Nothing by default, handled by optional widget/extension }; @@ -4003,12 +3990,12 @@ this.open = function() { // // Returns: // Nothing -this.save = function(opts) { +this.save = function (opts) { // remove the selected outline before serializing clearSelection(); // Update save options if provided - if (opts) {$.extend(save_options, opts);} - save_options.apply = true; + if (opts) { $.extend(saveOptions, opts); } + saveOptions.apply = true; // no need for doctype, see http://jwatt.org/svg/authoring/#doctype-declaration var str = this.svgCanvasToString(); @@ -4023,7 +4010,7 @@ function getIssues () { var issues = []; // Selector and notice - var issue_list = { + var issueList = { 'feGaussianBlur': uiStrings.exportNoBlur, 'foreignObject': uiStrings.exportNoforeignObject, '[stroke-dasharray]': uiStrings.exportNoDashArray @@ -4032,10 +4019,10 @@ function getIssues () { // Add font/text check if Canvas Text API is not implemented if (!('font' in $('')[0].getContext('2d'))) { - issue_list.text = uiStrings.exportNoText; + issueList.text = uiStrings.exportNoText; } - $.each(issue_list, function(sel, descr) { + $.each(issueList, function (sel, descr) { if (content.find(sel).length) { issues.push(descr); } @@ -4046,7 +4033,7 @@ function getIssues () { // Function: rasterExport // Generates a Data URL based on the current image, then calls "exported" // with an object including the string, image information, and any issues found -this.rasterExport = function(imgType, quality, exportWindowName) { +this.rasterExport = function (imgType, quality, exportWindowName) { var mimeType = 'image/' + imgType.toLowerCase(); var issues = getIssues(); var str = this.svgCanvasToString(); @@ -4060,7 +4047,7 @@ this.rasterExport = function(imgType, quality, exportWindowName) { c.width = svgCanvas.contentW; c.height = svgCanvas.contentH; - canvg(c, str, {renderCallback: function() { + canvg(c, str, {renderCallback: function () { var dataURLType = (type === 'ICO' ? 'BMP' : type).toLowerCase(); var datauri = quality ? c.toDataURL('image/' + dataURLType, quality) : c.toDataURL('image/' + dataURLType); if (c.toBlob) { @@ -4090,11 +4077,11 @@ this.exportPDF = function (exportWindowName, outputType) { }); // Todo: Give options to use predefined jsPDF formats like "a4", etc. from pull-down (with option to keep customizable) var docTitle = getDocumentTitle(); doc.setProperties({ - title: docTitle/*, + title: docTitle /* , subject: '', author: '', keywords: '', - creator: ''*/ + creator: '' */ }); var issues = getIssues(); var str = that.svgCanvasToString(); @@ -4116,8 +4103,8 @@ this.exportPDF = function (exportWindowName, outputType) { // // Returns: // The current drawing as raw SVG XML text. -this.getSvgString = function() { - save_options.apply = false; +this.getSvgString = function () { + saveOptions.apply = false; return this.svgCanvasToString(); }; @@ -4132,8 +4119,8 @@ this.getSvgString = function() { // if you're controlling SVG-Edit externally, and want randomized IDs, call // this BEFORE calling svgCanvas.setSvgString // -this.randomizeIds = function(enableRandomization) { - if (arguments.length > 0 && enableRandomization == false) { +this.randomizeIds = function (enableRandomization) { + if (arguments.length > 0 && enableRandomization === false) { svgedit.draw.randomizeIds(false, getCurrentDrawing()); } else { svgedit.draw.randomizeIds(true, getCurrentDrawing()); @@ -4145,7 +4132,7 @@ this.randomizeIds = function(enableRandomization) { // // Parameters: // g - The parent element of the tree to give unique IDs -var uniquifyElems = this.uniquifyElems = function(g) { +var uniquifyElems = this.uniquifyElems = function (g) { var ids = {}; // TODO: Handle markers and connectors. These are not yet re-identified properly // as their referring elements do not get remapped. @@ -4155,24 +4142,24 @@ var uniquifyElems = this.uniquifyElems = function(g) { // // Problem #1: if svg_1 gets renamed, we do not update the polyline's se:connector attribute // Problem #2: if the polyline svg_7 gets renamed, we do not update the marker id nor the polyline's marker-end attribute - var ref_elems = ['filter', 'linearGradient', 'pattern', 'radialGradient', 'symbol', 'textPath', 'use']; + var refElems = ['filter', 'linearGradient', 'pattern', 'radialGradient', 'symbol', 'textPath', 'use']; - svgedit.utilities.walkTree(g, function(n) { + svgedit.utilities.walkTree(g, function (n) { // if it's an element node - if (n.nodeType == 1) { + if (n.nodeType === 1) { // and the element has an ID if (n.id) { // and we haven't tracked this ID yet if (!(n.id in ids)) { // add this id to our map - ids[n.id] = {elem:null, attrs:[], hrefs:[]}; + ids[n.id] = {elem: null, attrs: [], hrefs: []}; } ids[n.id].elem = n; } // now search for all attributes on this element that might refer // to other elements - $.each(ref_attrs, function(i, attr) { + $.each(refAttrs, function (i, attr) { var attrnode = n.getAttributeNode(attr); if (attrnode) { // the incoming file has been sanitized, so we should be able to safely just strip off the leading # @@ -4181,7 +4168,7 @@ var uniquifyElems = this.uniquifyElems = function(g) { if (refid) { if (!(refid in ids)) { // add this id to our map - ids[refid] = {elem:null, attrs:[], hrefs:[]}; + ids[refid] = {elem: null, attrs: [], hrefs: []}; } ids[refid].attrs.push(attrnode); } @@ -4191,12 +4178,12 @@ var uniquifyElems = this.uniquifyElems = function(g) { // check xlink:href now var href = svgedit.utilities.getHref(n); // TODO: what if an or element refers to an element internally? - if (href && ref_elems.indexOf(n.nodeName) >= 0) { + if (href && refElems.indexOf(n.nodeName) >= 0) { var refid = href.substr(1); if (refid) { if (!(refid in ids)) { // add this id to our map - ids[refid] = {elem:null, attrs:[], hrefs:[]}; + ids[refid] = {elem: null, attrs: [], hrefs: []}; } ids[refid].hrefs.push(n); } @@ -4207,7 +4194,7 @@ var uniquifyElems = this.uniquifyElems = function(g) { // in ids, we now have a map of ids, elements and attributes, let's re-identify var oldid; for (oldid in ids) { - if (!oldid) {continue;} + if (!oldid) { continue; } var elem = ids[oldid].elem; if (elem) { var newid = getNextId(); @@ -4236,93 +4223,93 @@ var uniquifyElems = this.uniquifyElems = function(g) { // Function setUseData // Assigns reference data for each use element -var setUseData = this.setUseData = function(parent) { +var setUseData = this.setUseData = function (parent) { var elems = $(parent); if (parent.tagName !== 'use') { elems = elems.find('use'); } - elems.each(function() { + elems.each(function () { var id = getHref(this).substr(1); - var ref_elem = svgedit.utilities.getElem(id); - if (!ref_elem) {return;} - $(this).data('ref', ref_elem); - if (ref_elem.tagName == 'symbol' || ref_elem.tagName == 'svg') { - $(this).data('symbol', ref_elem).data('ref', ref_elem); + var refElem = svgedit.utilities.getElem(id); + if (!refElem) { return; } + $(this).data('ref', refElem); + if (refElem.tagName === 'symbol' || refElem.tagName === 'svg') { + $(this).data('symbol', refElem).data('ref', refElem); } }); }; // Function convertGradients // Converts gradients from userSpaceOnUse to objectBoundingBox -var convertGradients = this.convertGradients = function(elem) { +var convertGradients = this.convertGradients = function (elem) { var elems = $(elem).find('linearGradient, radialGradient'); if (!elems.length && svgedit.browser.isWebkit()) { // Bug in webkit prevents regular *Gradient selector search - elems = $(elem).find('*').filter(function() { + elems = $(elem).find('*').filter(function () { return (this.tagName.indexOf('Gradient') >= 0); }); } - elems.each(function() { + elems.each(function () { var grad = this; if ($(grad).attr('gradientUnits') === 'userSpaceOnUse') { // TODO: Support more than one element with this ref by duplicating parent grad var elems = $(svgcontent).find('[fill="url(#' + grad.id + ')"],[stroke="url(#' + grad.id + ')"]'); - if (!elems.length) {return;} + if (!elems.length) { return; } // get object's bounding box var bb = svgedit.utilities.getBBox(elems[0]); // This will occur if the element is inside a or a , // in which we shouldn't need to convert anyway. - if (!bb) {return;} + if (!bb) { return; } if (grad.tagName === 'linearGradient') { - var g_coords = $(grad).attr(['x1', 'y1', 'x2', 'y2']); + var gCoords = $(grad).attr(['x1', 'y1', 'x2', 'y2']); // If has transform, convert var tlist = grad.gradientTransform.baseVal; if (tlist && tlist.numberOfItems > 0) { var m = svgedit.math.transformListToTransform(tlist).matrix; - var pt1 = svgedit.math.transformPoint(g_coords.x1, g_coords.y1, m); - var pt2 = svgedit.math.transformPoint(g_coords.x2, g_coords.y2, m); + var pt1 = svgedit.math.transformPoint(gCoords.x1, gCoords.y1, m); + var pt2 = svgedit.math.transformPoint(gCoords.x2, gCoords.y2, m); - g_coords.x1 = pt1.x; - g_coords.y1 = pt1.y; - g_coords.x2 = pt2.x; - g_coords.y2 = pt2.y; + gCoords.x1 = pt1.x; + gCoords.y1 = pt1.y; + gCoords.x2 = pt2.x; + gCoords.y2 = pt2.y; grad.removeAttribute('gradientTransform'); } $(grad).attr({ - x1: (g_coords.x1 - bb.x) / bb.width, - y1: (g_coords.y1 - bb.y) / bb.height, - x2: (g_coords.x2 - bb.x) / bb.width, - y2: (g_coords.y2 - bb.y) / bb.height + x1: (gCoords.x1 - bb.x) / bb.width, + y1: (gCoords.y1 - bb.y) / bb.height, + x2: (gCoords.x2 - bb.x) / bb.width, + y2: (gCoords.y2 - bb.y) / bb.height }); grad.removeAttribute('gradientUnits'); } // else { - // Note: radialGradient elements cannot be easily converted - // because userSpaceOnUse will keep circular gradients, while - // objectBoundingBox will x/y scale the gradient according to - // its bbox. - - // For now we'll do nothing, though we should probably have - // the gradient be updated as the element is moved, as - // inkscape/illustrator do. - -// var g_coords = $(grad).attr(['cx', 'cy', 'r']); -// -// $(grad).attr({ -// cx: (g_coords.cx - bb.x) / bb.width, -// cy: (g_coords.cy - bb.y) / bb.height, -// r: g_coords.r -// }); -// -// grad.removeAttribute('gradientUnits'); + // Note: radialGradient elements cannot be easily converted + // because userSpaceOnUse will keep circular gradients, while + // objectBoundingBox will x/y scale the gradient according to + // its bbox. + // + // For now we'll do nothing, though we should probably have + // the gradient be updated as the element is moved, as + // inkscape/illustrator do. + // + // var gCoords = $(grad).attr(['cx', 'cy', 'r']); + // + // $(grad).attr({ + // cx: (gCoords.cx - bb.x) / bb.width, + // cy: (gCoords.cy - bb.y) / bb.height, + // r: gCoords.r + // }); + // + // grad.removeAttribute('gradientUnits'); // } } }); @@ -4330,7 +4317,7 @@ var convertGradients = this.convertGradients = function(elem) { // Function: convertToGroup // Converts selected/given or child SVG element to a group -var convertToGroup = this.convertToGroup = function(elem) { +var convertToGroup = this.convertToGroup = function (elem) { if (!elem) { elem = selectedElements[0]; } @@ -4376,7 +4363,7 @@ var convertToGroup = this.convertToGroup = function(elem) { $elem.remove(); // See if other elements reference this symbol - var has_more = $(svgcontent).find('use:data(symbol)').length; + var hasMore = $(svgcontent).find('use:data(symbol)').length; var g = svgdoc.createElementNS(NS.SVG, 'g'); var childs = elem.childNodes; @@ -4402,7 +4389,7 @@ var convertToGroup = this.convertToGroup = function(elem) { // Put the dupe gradients back into (after uniquifying them) if (svgedit.browser.isGecko()) { - $(findDefs()).append( $(g).find('linearGradient,radialGradient,pattern') ); + $(findDefs()).append($(g).find('linearGradient,radialGradient,pattern')); } // now give the g itself a new id @@ -4411,7 +4398,7 @@ var convertToGroup = this.convertToGroup = function(elem) { prev.after(g); if (parent) { - if (!has_more) { + if (!hasMore) { // remove symbol/svg element var nextSibling = elem.nextSibling; parent.removeChild(elem); @@ -4430,17 +4417,17 @@ var convertToGroup = this.convertToGroup = function(elem) { // recalculate dimensions on the top-level children so that unnecessary transforms // are removed - svgedit.utilities.walkTreePost(g, function(n){ + svgedit.utilities.walkTreePost(g, function (n) { try { svgedit.recalculate.recalculateDimensions(n); - } catch(e) { + } catch (e) { console.log(e); } }); // Give ID for any visible element missing one - $(g).find(visElems).each(function() { - if (!this.id) {this.id = getNextId();} + $(g).find(visElems).each(function () { + if (!this.id) { this.id = getNextId(); } }); selectOnly([g]); @@ -4451,7 +4438,6 @@ var convertToGroup = this.convertToGroup = function(elem) { } addCommandToHistory(batchCmd); - } else { console.log('Unexpected element to ungroup:', elem); } @@ -4469,7 +4455,7 @@ var convertToGroup = this.convertToGroup = function(elem) { // // Returns: // This function returns false if the set was unsuccessful, true otherwise. -this.setSvgString = function(xmlString, preventUndo) { +this.setSvgString = function (xmlString, preventUndo) { try { // convert string into XML document var newDoc = svgedit.utilities.text2xml(xmlString); @@ -4487,8 +4473,7 @@ this.setSvgString = function(xmlString, preventUndo) { // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode() if (svgdoc.adoptNode) { svgcontent = svgdoc.adoptNode(newDoc.documentElement); - } - else { + } else { svgcontent = svgdoc.importNode(newDoc.documentElement, true); } @@ -4506,7 +4491,7 @@ this.setSvgString = function(xmlString, preventUndo) { } // change image href vals if possible - content.find('image').each(function() { + content.find('image').each(function () { var image = this; svgedit.utilities.preventClickDefault(image); var val = getHref(this); @@ -4527,9 +4512,9 @@ this.setSvgString = function(xmlString, preventUndo) { }); // Wrap child SVGs in group elements - content.find('svg').each(function() { + content.find('svg').each(function () { // Skip if it's in a - if ($(this).closest('defs').length) {return;} + if ($(this).closest('defs').length) { return; } uniquifyElems(this); @@ -4567,14 +4552,13 @@ this.setSvgString = function(xmlString, preventUndo) { var vb = content.attr('viewBox').split(' '); attrs.width = vb[2]; attrs.height = vb[3]; - } // handle content that doesn't have a viewBox - else { - $.each(['width', 'height'], function(i, dim) { + } else { + $.each(['width', 'height'], function (i, dim) { // Set to 100 if not given var val = content.attr(dim); - if (!val) {val = '100%';} + if (!val) { val = '100%'; } if (String(val).substr(-1) === '%') { // Use user units if percentage given @@ -4589,8 +4573,8 @@ this.setSvgString = function(xmlString, preventUndo) { identifyLayers(); // Give ID for any visible layer children missing one - content.children().find(visElems).each(function() { - if (!this.id) {this.id = getNextId();} + content.children().find(visElems).each(function () { + if (!this.id) { this.id = getNextId(); } }); // Percentage width/height, so let's base it on visible elements @@ -4602,8 +4586,8 @@ this.setSvgString = function(xmlString, preventUndo) { // Just in case negative numbers are given or // result from the percs calculation - if (attrs.width <= 0) {attrs.width = 100;} - if (attrs.height <= 0) {attrs.height = 100;} + if (attrs.width <= 0) { attrs.width = 100; } + if (attrs.height <= 0) { attrs.height = 100; } content.attr(attrs); this.contentW = attrs.width; @@ -4615,7 +4599,7 @@ this.setSvgString = function(xmlString, preventUndo) { batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(svgroot, changes)); // reset zoom - current_zoom = 1; + currentZoom = 1; // reset transform lists svgedit.transformlist.resetListMap(); @@ -4625,7 +4609,7 @@ this.setSvgString = function(xmlString, preventUndo) { if (!preventUndo) addCommandToHistory(batchCmd); call('changed', [svgcontent]); - } catch(e) { + } catch (e) { console.log(e); return false; } @@ -4649,17 +4633,17 @@ this.setSvgString = function(xmlString, preventUndo) { // arbitrary transform lists, but makes some assumptions about how the transform list // was obtained // * import should happen in top-left of current zoomed viewport -this.importSvgString = function(xmlString) { +this.importSvgString = function (xmlString) { var j, ts; try { // Get unique ID - var uid = svgedit.utilities.encode64(xmlString.length + xmlString).substr(0,32); + var uid = svgedit.utilities.encode64(xmlString.length + xmlString).substr(0, 32); var useExisting = false; // Look for symbol and make sure symbol exists in image - if (import_ids[uid]) { - if ( $(import_ids[uid].symbol).parents('#svgroot').length ) { + if (importIds[uid]) { + if ($(importIds[uid].symbol).parents('#svgroot').length) { useExisting = true; } } @@ -4667,8 +4651,8 @@ this.importSvgString = function(xmlString) { var batchCmd = new svgedit.history.BatchCommand('Import Image'); var symbol; if (useExisting) { - symbol = import_ids[uid].symbol; - ts = import_ids[uid].xform; + symbol = importIds[uid].symbol; + ts = importIds[uid].xform; } else { // convert string into XML document var newDoc = svgedit.utilities.text2xml(xmlString); @@ -4696,14 +4680,14 @@ this.importSvgString = function(xmlString) { } // TODO: properly handle preserveAspectRatio - var canvasw = +svgcontent.getAttribute('width'), + var // canvasw = +svgcontent.getAttribute('width'), canvash = +svgcontent.getAttribute('height'); // imported content should be 1/3 of the canvas on its largest dimension if (innerh > innerw) { - ts = 'scale(' + (canvash/3)/vb[3] + ')'; + ts = 'scale(' + (canvash / 3) / vb[3] + ')'; } else { - ts = 'scale(' + (canvash/3)/vb[2] + ')'; + ts = 'scale(' + (canvash / 3) / vb[2] + ')'; } // Hack to make recalculateDimensions understand how to scale @@ -4732,7 +4716,7 @@ this.importSvgString = function(xmlString) { symbol.id = getNextId(); // Store data - import_ids[uid] = { + importIds[uid] = { symbol: symbol, xform: ts }; @@ -4741,32 +4725,32 @@ this.importSvgString = function(xmlString) { batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(symbol)); } - var use_el = svgdoc.createElementNS(NS.SVG, 'use'); - use_el.id = getNextId(); - setHref(use_el, '#' + symbol.id); + var useEl = svgdoc.createElementNS(NS.SVG, 'use'); + useEl.id = getNextId(); + setHref(useEl, '#' + symbol.id); - (current_group || getCurrentDrawing().getCurrentLayer()).appendChild(use_el); - batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(use_el)); + (currentGroup || getCurrentDrawing().getCurrentLayer()).appendChild(useEl); + batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(useEl)); clearSelection(); - use_el.setAttribute('transform', ts); - svgedit.recalculate.recalculateDimensions(use_el); - $(use_el).data('symbol', symbol).data('ref', symbol); - addToSelection([use_el]); + useEl.setAttribute('transform', ts); + svgedit.recalculate.recalculateDimensions(useEl); + $(useEl).data('symbol', symbol).data('ref', symbol); + addToSelection([useEl]); // TODO: Find way to add this in a recalculateDimensions-parsable way -// if (vb[0] != 0 || vb[1] != 0) -// ts = 'translate(' + (-vb[0]) + ',' + (-vb[1]) + ') ' + ts; + // if (vb[0] != 0 || vb[1] != 0) { + // ts = 'translate(' + (-vb[0]) + ',' + (-vb[1]) + ') ' + ts; + // } addCommandToHistory(batchCmd); call('changed', [svgcontent]); - - } catch(e) { + } catch (e) { console.log(e); return null; } // we want to return the element so we can automatically select it - return use_el; + return useEl; }; // TODO(codedread): Move all layer/context functions in draw.js @@ -4776,7 +4760,7 @@ this.importSvgString = function(xmlString) { // Function: identifyLayers // Updates layer system -var identifyLayers = canvas.identifyLayers = function() { +var identifyLayers = canvas.identifyLayers = function () { leaveContext(); getCurrentDrawing().identifyLayers(); }; @@ -4788,10 +4772,10 @@ var identifyLayers = canvas.identifyLayers = function() { // // Parameters: // name - The given name -this.createLayer = function(name, hrService) { - var new_layer = getCurrentDrawing().createLayer(name, historyRecordingService(hrService)); +this.createLayer = function (name, hrService) { + var newLayer = getCurrentDrawing().createLayer(name, historyRecordingService(hrService)); clearSelection(); - call('changed', [new_layer]); + call('changed', [newLayer]); }; /** @@ -4801,27 +4785,27 @@ this.createLayer = function(name, hrService) { * @param {string} name - The given name. If the layer name exists, a new name will be generated. * @param {svgedit.history.HistoryRecordingService} hrService - History recording service */ -this.cloneLayer = function(name, hrService) { +this.cloneLayer = function (name, hrService) { // Clone the current layer and make the cloned layer the new current layer - var new_layer = getCurrentDrawing().cloneLayer(name, historyRecordingService(hrService)); + var newLayer = getCurrentDrawing().cloneLayer(name, historyRecordingService(hrService)); clearSelection(); leaveContext(); - call('changed', [new_layer]); + call('changed', [newLayer]); }; // Function: deleteCurrentLayer // Deletes the current layer from the drawing and then clears the selection. This function // then calls the 'changed' handler. This is an undoable action. -this.deleteCurrentLayer = function() { - var current_layer = getCurrentDrawing().getCurrentLayer(); - var nextSibling = current_layer.nextSibling; - var parent = current_layer.parentNode; - current_layer = getCurrentDrawing().deleteCurrentLayer(); - if (current_layer) { +this.deleteCurrentLayer = function () { + var currentLayer = getCurrentDrawing().getCurrentLayer(); + var nextSibling = currentLayer.nextSibling; + var parent = currentLayer.parentNode; + currentLayer = getCurrentDrawing().deleteCurrentLayer(); + if (currentLayer) { var batchCmd = new svgedit.history.BatchCommand('Delete Layer'); // store in our Undo History - batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(current_layer, nextSibling, parent)); + batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(currentLayer, nextSibling, parent)); addCommandToHistory(batchCmd); clearSelection(); call('changed', [parent]); @@ -4839,7 +4823,7 @@ this.deleteCurrentLayer = function() { // // Returns: // true if the current layer was switched, otherwise false -this.setCurrentLayer = function(name) { +this.setCurrentLayer = function (name) { var result = getCurrentDrawing().setCurrentLayer(svgedit.utilities.toXml(name)); if (result) { clearSelection(); @@ -4857,7 +4841,7 @@ this.setCurrentLayer = function(name) { // // Returns: // true if the rename succeeded, false otherwise. -this.renameCurrentLayer = function(newname) { +this.renameCurrentLayer = function (newname) { var drawing = getCurrentDrawing(); var layer = drawing.getCurrentLayer(); if (layer) { @@ -4881,8 +4865,8 @@ this.renameCurrentLayer = function(newname) { // // Returns: // true if the current layer position was changed, false otherwise. -this.setCurrentLayerPosition = function(newpos) { - var oldpos, drawing = getCurrentDrawing(); +this.setCurrentLayerPosition = function (newpos) { + var drawing = getCurrentDrawing(); var result = drawing.setCurrentLayerPosition(newpos); if (result) { addCommandToHistory(new svgedit.history.MoveElementCommand(result.currentGroup, result.oldNextSibling, svgcontent)); @@ -4901,22 +4885,22 @@ this.setCurrentLayerPosition = function(newpos) { // // Returns: // true if the layer's visibility was set, false otherwise -this.setLayerVisibility = function(layername, bVisible) { +this.setLayerVisibility = function (layername, bVisible) { var drawing = getCurrentDrawing(); var prevVisibility = drawing.getLayerVisibility(layername); var layer = drawing.setLayerVisibility(layername, bVisible); if (layer) { var oldDisplay = prevVisibility ? 'inline' : 'none'; - addCommandToHistory(new svgedit.history.ChangeElementCommand(layer, {'display':oldDisplay}, 'Layer Visibility')); + addCommandToHistory(new svgedit.history.ChangeElementCommand(layer, {'display': oldDisplay}, 'Layer Visibility')); } else { return false; } - if (layer == drawing.getCurrentLayer()) { + if (layer === drawing.getCurrentLayer()) { clearSelection(); pathActions.clear(); } -// call('changed', [selected]); + // call('changed', [selected]); return true; }; @@ -4929,12 +4913,12 @@ this.setLayerVisibility = function(layername, bVisible) { // // Returns: // true if the selected elements were moved to the layer, false otherwise. -this.moveSelectedToLayer = function(layername) { +this.moveSelectedToLayer = function (layername) { // find the layer var i; var drawing = getCurrentDrawing(); var layer = drawing.getLayerByName(layername); - if (!layer) {return false;} + if (!layer) { return false; } var batchCmd = new svgedit.history.BatchCommand('Move Elements to Layer'); @@ -4943,7 +4927,7 @@ this.moveSelectedToLayer = function(layername) { i = selElems.length; while (i--) { var elem = selElems[i]; - if (!elem) {continue;} + if (!elem) { continue; } var oldNextSibling = elem.nextSibling; // TODO: this is pretty brittle! var oldLayer = elem.parentNode; @@ -4956,15 +4940,14 @@ this.moveSelectedToLayer = function(layername) { return true; }; - -this.mergeLayer = function(hrService) { +this.mergeLayer = function (hrService) { getCurrentDrawing().mergeLayer(historyRecordingService(hrService)); clearSelection(); leaveContext(); call('changed', [svgcontent]); }; -this.mergeAllLayers = function(hrService) { +this.mergeAllLayers = function (hrService) { getCurrentDrawing().mergeAllLayers(historyRecordingService(hrService)); clearSelection(); leaveContext(); @@ -4974,11 +4957,11 @@ this.mergeAllLayers = function(hrService) { // Function: leaveContext // Return from a group context to the regular kind, make any previously // disabled elements enabled again -var leaveContext = this.leaveContext = function() { - var i, len = disabled_elems.length; +var leaveContext = this.leaveContext = function () { + var i, len = disabledElems.length; if (len) { for (i = 0; i < len; i++) { - var elem = disabled_elems[i]; + var elem = disabledElems[i]; var orig = elData(elem, 'orig_opac'); if (orig !== 1) { elem.setAttribute('opacity', orig); @@ -4987,43 +4970,43 @@ var leaveContext = this.leaveContext = function() { } elem.setAttribute('style', 'pointer-events: inherit'); } - disabled_elems = []; + disabledElems = []; clearSelection(true); call('contextset', null); } - current_group = null; + currentGroup = null; }; // Function: setContext // Set the current context (for in-group editing) -var setContext = this.setContext = function(elem) { +var setContext = this.setContext = function (elem) { leaveContext(); if (typeof elem === 'string') { elem = svgedit.utilities.getElem(elem); } // Edit inside this group - current_group = elem; + currentGroup = elem; // Disable other elements - $(elem).parentsUntil('#svgcontent').andSelf().siblings().each(function() { + $(elem).parentsUntil('#svgcontent').andSelf().siblings().each(function () { var opac = this.getAttribute('opacity') || 1; // Store the original's opacity elData(this, 'orig_opac', opac); this.setAttribute('opacity', opac * 0.33); this.setAttribute('style', 'pointer-events: none'); - disabled_elems.push(this); + disabledElems.push(this); }); clearSelection(); - call('contextset', current_group); + call('contextset', currentGroup); }; // Group: Document functions // Function: clear // Clears the current document. This is not an undoable action. -this.clear = function() { +this.clear = function () { pathActions.clear(); clearSelection(); @@ -5055,44 +5038,43 @@ this.linkControlPoints = pathActions.linkControlPoints; // Function: getContentElem // Returns the content DOM element -this.getContentElem = function() { return svgcontent; }; +this.getContentElem = function () { return svgcontent; }; // Function: getRootElem // Returns the root DOM element -this.getRootElem = function() { return svgroot; }; +this.getRootElem = function () { return svgroot; }; // Function: getSelectedElems // Returns the array with selected DOM elements -this.getSelectedElems = function() { return selectedElements; }; +this.getSelectedElems = function () { return selectedElements; }; // Function: getResolution // Returns the current dimensions and zoom level in an object -var getResolution = this.getResolution = function() { +var getResolution = this.getResolution = function () { // var vb = svgcontent.getAttribute('viewBox').split(' '); -// return {'w':vb[2], 'h':vb[3], 'zoom': current_zoom}; +// return {'w':vb[2], 'h':vb[3], 'zoom': currentZoom}; - var width = svgcontent.getAttribute('width')/current_zoom; - var height = svgcontent.getAttribute('height')/current_zoom; + var width = svgcontent.getAttribute('width') / currentZoom; + var height = svgcontent.getAttribute('height') / currentZoom; return { 'w': width, 'h': height, - 'zoom': current_zoom + 'zoom': currentZoom }; }; // Function: getZoom // Returns the current zoom level -this.getZoom = function(){return current_zoom;}; +this.getZoom = function () { return currentZoom; }; // Function: getSnapToGrid // Returns the current snap to grid setting -this.getSnapToGrid = function(){return curConfig.gridSnapping;}; - +this.getSnapToGrid = function () { return curConfig.gridSnapping; }; // Function: getVersion // Returns a string which describes the revision number of SvgCanvas. -this.getVersion = function() { +this.getVersion = function () { return 'svgcanvas.js ($Rev$)'; }; @@ -5101,7 +5083,7 @@ this.getVersion = function() { // // Parameters: // strs - Object with strings (see uiStrings for examples) -this.setUiStrings = function(strs) { +this.setUiStrings = function (strs) { $.extend(uiStrings, strs.notification); }; @@ -5110,20 +5092,20 @@ this.setUiStrings = function(strs) { // // Parameters: // opts - Object with options (see curConfig for examples) -this.setConfig = function(opts) { +this.setConfig = function (opts) { $.extend(curConfig, opts); }; // Function: getTitle // Returns the current group/SVG's title contents -this.getTitle = function(elem) { +this.getTitle = function (elem) { var i; elem = elem || selectedElements[0]; - if (!elem) {return;} + if (!elem) { return; } elem = $(elem).data('gsvg') || $(elem).data('symbol') || elem; var childs = elem.childNodes; for (i = 0; i < childs.length; i++) { - if (childs[i].nodeName == 'title') { + if (childs[i].nodeName === 'title') { return childs[i].textContent; } } @@ -5133,7 +5115,7 @@ this.getTitle = function(elem) { // Function: setGroupTitle // Sets the group/SVG's title content // TODO: Combine this with setDocumentTitle -this.setGroupTitle = function(val) { +this.setGroupTitle = function (val) { var elem = selectedElements[0]; elem = $(elem).data('gsvg') || elem; @@ -5164,7 +5146,7 @@ this.setGroupTitle = function(val) { // Function: getDocumentTitle // Returns the current document title or an empty string if not found -var getDocumentTitle = this.getDocumentTitle = function() { +var getDocumentTitle = this.getDocumentTitle = function () { return canvas.getTitle(svgcontent); }; @@ -5174,31 +5156,31 @@ var getDocumentTitle = this.getDocumentTitle = function() { // // Parameters: // newtitle - String with the new title -this.setDocumentTitle = function(newtitle) { +this.setDocumentTitle = function (newtitle) { var i; - var childs = svgcontent.childNodes, doc_title = false, old_title = ''; + var childs = svgcontent.childNodes, docTitle = false, oldTitle = ''; var batchCmd = new svgedit.history.BatchCommand('Change Image Title'); for (i = 0; i < childs.length; i++) { - if (childs[i].nodeName == 'title') { - doc_title = childs[i]; - old_title = doc_title.textContent; + if (childs[i].nodeName === 'title') { + docTitle = childs[i]; + oldTitle = docTitle.textContent; break; } } - if (!doc_title) { - doc_title = svgdoc.createElementNS(NS.SVG, 'title'); - svgcontent.insertBefore(doc_title, svgcontent.firstChild); + if (!docTitle) { + docTitle = svgdoc.createElementNS(NS.SVG, 'title'); + svgcontent.insertBefore(docTitle, svgcontent.firstChild); } if (newtitle.length) { - doc_title.textContent = newtitle; + docTitle.textContent = newtitle; } else { // No title given, so element is not necessary - doc_title.parentNode.removeChild(doc_title); + docTitle.parentNode.removeChild(docTitle); } - batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(doc_title, {'#text': old_title})); + batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(docTitle, {'#text': oldTitle})); addCommandToHistory(batchCmd); }; @@ -5207,7 +5189,7 @@ this.setDocumentTitle = function(newtitle) { // // Parameters: // add - Boolean to indicate whether or not to add the namespace value -this.getEditorNS = function(add) { +this.getEditorNS = function (add) { if (add) { svgcontent.setAttribute('xmlns:se', NS.SE); } @@ -5225,12 +5207,12 @@ this.getEditorNS = function(add) { // Returns: // Boolean to indicate if resolution change was succesful. // It will fail on "fit to content" option with no content to fit to. -this.setResolution = function(x, y) { +this.setResolution = function (x, y) { var res = getResolution(); var w = res.w, h = res.h; var batchCmd; - if (x == 'fit') { + if (x === 'fit') { // Get bounding box var bbox = getStrokedBBox(); @@ -5239,9 +5221,9 @@ this.setResolution = function(x, y) { var visEls = getVisibleElements(); addToSelection(visEls); var dx = [], dy = []; - $.each(visEls, function(i, item) { - dx.push(bbox.x*-1); - dy.push(bbox.y*-1); + $.each(visEls, function (i, item) { + dx.push(bbox.x * -1); + dy.push(bbox.y * -1); }); var cmd = canvas.moveSelectedElements(dx, dy, true); @@ -5254,7 +5236,7 @@ this.setResolution = function(x, y) { return false; } } - if (x != w || y != h) { + if (x !== w || y !== h) { if (!batchCmd) { batchCmd = new svgedit.history.BatchCommand('Change Image Dimensions'); } @@ -5267,9 +5249,9 @@ this.setResolution = function(x, y) { this.contentW = x; this.contentH = y; - batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(svgcontent, {'width':w, 'height':h})); + batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(svgcontent, {'width': w, 'height': h})); - svgcontent.setAttribute('viewBox', [0, 0, x/current_zoom, y/current_zoom].join(' ')); + svgcontent.setAttribute('viewBox', [0, 0, x / currentZoom, y / currentZoom].join(' ')); batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(svgcontent, {'viewBox': ['0 0', w, h].join(' ')})); addCommandToHistory(batchCmd); @@ -5281,7 +5263,7 @@ this.setResolution = function(x, y) { // Function: getOffset // Returns an object with x, y values indicating the svgcontent element's // position in the editor's canvas. -this.getOffset = function() { +this.getOffset = function () { return $(svgcontent).attr(['x', 'y']); }; @@ -5290,40 +5272,40 @@ this.getOffset = function() { // // Parameters: // val - Bounding box object to zoom to or string indicating zoom option -// editor_w - Integer with the editor's workarea box's width -// editor_h - Integer with the editor's workarea box's height -this.setBBoxZoom = function(val, editor_w, editor_h) { +// editorW - Integer with the editor's workarea box's width +// editorH - Integer with the editor's workarea box's height +this.setBBoxZoom = function (val, editorW, editorH) { var spacer = 0.85; var bb; - var calcZoom = function(bb) { - if (!bb) {return false;} - var w_zoom = Math.round((editor_w / bb.width)*100 * spacer)/100; - var h_zoom = Math.round((editor_h / bb.height)*100 * spacer)/100; - var zoomlevel = Math.min(w_zoom, h_zoom); + var calcZoom = function (bb) { + if (!bb) { return false; } + var wZoom = Math.round((editorW / bb.width) * 100 * spacer) / 100; + var hZoom = Math.round((editorH / bb.height) * 100 * spacer) / 100; + var zoomlevel = Math.min(wZoom, hZoom); canvas.setZoom(zoomlevel); return {'zoom': zoomlevel, 'bbox': bb}; }; - if (typeof val == 'object') { + if (typeof val === 'object') { bb = val; - if (bb.width == 0 || bb.height == 0) { - var newzoom = bb.zoom ? bb.zoom : current_zoom * bb.factor; + if (bb.width === 0 || bb.height === 0) { + var newzoom = bb.zoom ? bb.zoom : currentZoom * bb.factor; canvas.setZoom(newzoom); - return {'zoom': current_zoom, 'bbox': bb}; + return {'zoom': currentZoom, 'bbox': bb}; } return calcZoom(bb); } switch (val) { case 'selection': - if (!selectedElements[0]) {return;} - var sel_elems = $.map(selectedElements, function(n){ if (n) {return n;} }); - bb = getStrokedBBox(sel_elems); + if (!selectedElements[0]) { return; } + var selectedElems = $.map(selectedElements, function (n) { if (n) { return n; } }); + bb = getStrokedBBox(selectedElems); break; case 'canvas': var res = getResolution(); spacer = 0.95; - bb = {width:res.w, height:res.h , x:0, y:0}; + bb = {width: res.w, height: res.h, x: 0, y: 0}; break; case 'content': bb = getStrokedBBox(); @@ -5342,12 +5324,12 @@ this.setBBoxZoom = function(val, editor_w, editor_h) { // // Parameters: // zoomlevel - Float indicating the zoom level to change to -this.setZoom = function(zoomlevel) { +this.setZoom = function (zoomlevel) { var res = getResolution(); - svgcontent.setAttribute('viewBox', '0 0 ' + res.w/zoomlevel + ' ' + res.h/zoomlevel); - current_zoom = zoomlevel; - $.each(selectedElements, function(i, elem) { - if (!elem) {return;} + svgcontent.setAttribute('viewBox', '0 0 ' + res.w / zoomlevel + ' ' + res.h / zoomlevel); + currentZoom = zoomlevel; + $.each(selectedElements, function (i, elem) { + if (!elem) { return; } selectorManager.requestSelector(elem).resize(); }); pathActions.zoomChange(); @@ -5356,8 +5338,8 @@ this.setZoom = function(zoomlevel) { // Function: getMode // Returns the current editor mode string -this.getMode = function() { - return current_mode; +this.getMode = function () { + return currentMode; }; // Function: setMode @@ -5365,19 +5347,19 @@ this.getMode = function() { // // Parameters: // name - String with the new mode to change to -this.setMode = function(name) { +this.setMode = function (name) { pathActions.clear(true); textActions.clear(); - cur_properties = (selectedElements[0] && selectedElements[0].nodeName == 'text') ? cur_text : cur_shape; - current_mode = name; + curProperties = (selectedElements[0] && selectedElements[0].nodeName === 'text') ? curText : curShape; + currentMode = name; }; // Group: Element Styling // Function: getColor // Returns the current fill/stroke option -this.getColor = function(type) { - return cur_properties[type]; +this.getColor = function (type) { + return curProperties[type]; }; // Function: setColor @@ -5387,12 +5369,12 @@ this.getColor = function(type) { // type - String indicating fill or stroke // val - The value to set the stroke attribute to // preventUndo - Boolean indicating whether or not this should be and undoable option -this.setColor = function(type, val, preventUndo) { - cur_shape[type] = val; - cur_properties[type + '_paint'] = {type:'solidColor'}; +this.setColor = function (type, val, preventUndo) { + curShape[type] = val; + curProperties[type + '_paint'] = {type: 'solidColor'}; var elems = []; function addNonG (e) { - if (e.nodeName != 'g') { + if (e.nodeName !== 'g') { elems.push(e); } } @@ -5400,11 +5382,11 @@ this.setColor = function(type, val, preventUndo) { while (i--) { var elem = selectedElements[i]; if (elem) { - if (elem.tagName == 'g') { + if (elem.tagName === 'g') { svgedit.utilities.walkTree(elem, addNonG); } else { - if (type == 'fill') { - if (elem.tagName != 'polyline' && elem.tagName != 'line') { + if (type === 'fill') { + if (elem.tagName !== 'polyline' && elem.tagName !== 'line') { elems.push(elem); } } else { @@ -5428,20 +5410,20 @@ this.setColor = function(type, val, preventUndo) { // // Parameters // type - String indicating "fill" or "stroke" to apply to an element -var setGradient = this.setGradient = function(type) { - if (!cur_properties[type + '_paint'] || cur_properties[type + '_paint'].type == 'solidColor') {return;} +var setGradient = this.setGradient = function (type) { + if (!curProperties[type + '_paint'] || curProperties[type + '_paint'].type === 'solidColor') { return; } var grad = canvas[type + 'Grad']; // find out if there is a duplicate gradient already in the defs - var duplicate_grad = findDuplicateGradient(grad); + var duplicateGrad = findDuplicateGradient(grad); var defs = svgedit.utilities.findDefs(); // no duplicate found, so import gradient into defs - if (!duplicate_grad) { - var orig_grad = grad; - grad = defs.appendChild( svgdoc.importNode(grad, true) ); + if (!duplicateGrad) { + // var origGrad = grad; + grad = defs.appendChild(svgdoc.importNode(grad, true)); // get next id and set it on the grad grad.id = getNextId(); } else { // use existing gradient - grad = duplicate_grad; + grad = duplicateGrad; } canvas.setColor(type, 'url(#' + grad.id + ')'); }; @@ -5454,38 +5436,38 @@ var setGradient = this.setGradient = function(type) { // // Returns: // The existing gradient if found, null if not -var findDuplicateGradient = function(grad) { +var findDuplicateGradient = function (grad) { var defs = svgedit.utilities.findDefs(); - var existing_grads = $(defs).find('linearGradient, radialGradient'); - var i = existing_grads.length; - var rad_attrs = ['r', 'cx', 'cy', 'fx', 'fy']; + var existingGrads = $(defs).find('linearGradient, radialGradient'); + var i = existingGrads.length; + var radAttrs = ['r', 'cx', 'cy', 'fx', 'fy']; while (i--) { - var og = existing_grads[i]; - if (grad.tagName == 'linearGradient') { - if (grad.getAttribute('x1') != og.getAttribute('x1') || - grad.getAttribute('y1') != og.getAttribute('y1') || - grad.getAttribute('x2') != og.getAttribute('x2') || - grad.getAttribute('y2') != og.getAttribute('y2')) - { + var og = existingGrads[i]; + if (grad.tagName === 'linearGradient') { + if (grad.getAttribute('x1') !== og.getAttribute('x1') || + grad.getAttribute('y1') !== og.getAttribute('y1') || + grad.getAttribute('x2') !== og.getAttribute('x2') || + grad.getAttribute('y2') !== og.getAttribute('y2') + ) { continue; } } else { - var grad_attrs = $(grad).attr(rad_attrs); - var og_attrs = $(og).attr(rad_attrs); + var gradAttrs = $(grad).attr(radAttrs); + var ogAttrs = $(og).attr(radAttrs); var diff = false; - $.each(rad_attrs, function(i, attr) { - if (grad_attrs[attr] != og_attrs[attr]) {diff = true;} + $.each(radAttrs, function (i, attr) { + if (gradAttrs[attr] !== ogAttrs[attr]) { diff = true; } }); - if (diff) {continue;} + if (diff) { continue; } } // else could be a duplicate, iterate through stops var stops = grad.getElementsByTagNameNS(NS.SVG, 'stop'); var ostops = og.getElementsByTagNameNS(NS.SVG, 'stop'); - if (stops.length != ostops.length) { + if (stops.length !== ostops.length) { continue; } @@ -5494,15 +5476,14 @@ var findDuplicateGradient = function(grad) { var stop = stops[j]; var ostop = ostops[j]; - if (stop.getAttribute('offset') != ostop.getAttribute('offset') || - stop.getAttribute('stop-opacity') != ostop.getAttribute('stop-opacity') || - stop.getAttribute('stop-color') != ostop.getAttribute('stop-color')) - { + if (stop.getAttribute('offset') !== ostop.getAttribute('offset') || + stop.getAttribute('stop-opacity') !== ostop.getAttribute('stop-opacity') || + stop.getAttribute('stop-color') !== ostop.getAttribute('stop-color')) { break; } } - if (j == -1) { + if (j === -1) { return og; } } // for each gradient in defs @@ -5510,7 +5491,7 @@ var findDuplicateGradient = function(grad) { return null; }; -function reorientGrads(elem, m) { +function reorientGrads (elem, m) { var i; var bb = svgedit.utilities.getBBox(elem); for (i = 0; i < 2; i++) { @@ -5535,15 +5516,15 @@ function reorientGrads(elem, m) { var pt2 = svgedit.math.transformPoint(x2, y2, m); // Convert back to BB points - var g_coords = {}; + var gCoords = {}; - g_coords.x1 = (pt1.x - bb.x) / bb.width; - g_coords.y1 = (pt1.y - bb.y) / bb.height; - g_coords.x2 = (pt2.x - bb.x) / bb.width; - g_coords.y2 = (pt2.y - bb.y) / bb.height; + gCoords.x1 = (pt1.x - bb.x) / bb.width; + gCoords.y1 = (pt1.y - bb.y) / bb.height; + gCoords.x2 = (pt2.x - bb.x) / bb.width; + gCoords.y2 = (pt2.y - bb.y) / bb.height; var newgrad = grad.cloneNode(true); - $(newgrad).attr(g_coords); + $(newgrad).attr(gCoords); newgrad.id = getNextId(); svgedit.utilities.findDefs().appendChild(newgrad); @@ -5559,16 +5540,16 @@ function reorientGrads(elem, m) { // Parameters: // type - String with "fill" or "stroke" // paint - The jGraduate paint object to apply -this.setPaint = function(type, paint) { +this.setPaint = function (type, paint) { // make a copy var p = new $.jGraduate.Paint(paint); this.setPaintOpacity(type, p.alpha / 100, true); // now set the current paint object - cur_properties[type + '_paint'] = p; + curProperties[type + '_paint'] = p; switch (p.type) { case 'solidColor': - this.setColor(type, p.solidColor != 'none' ? '#' + p.solidColor : 'none'); + this.setColor(type, p.solidColor !== 'none' ? '#' + p.solidColor : 'none'); break; case 'linearGradient': case 'radialGradient': @@ -5579,18 +5560,18 @@ this.setPaint = function(type, paint) { }; // alias -this.setStrokePaint = function(paint) { +this.setStrokePaint = function (paint) { this.setPaint('stroke', paint); }; -this.setFillPaint = function(paint) { +this.setFillPaint = function (paint) { this.setPaint('fill', paint); }; // Function: getStrokeWidth // Returns the current stroke-width value -this.getStrokeWidth = function() { - return cur_properties.stroke_width; +this.getStrokeWidth = function () { + return curProperties.stroke_width; }; // Function: setStrokeWidth @@ -5599,16 +5580,16 @@ this.getStrokeWidth = function() { // // Parameters: // val - A Float indicating the new stroke width value -this.setStrokeWidth = function(val) { - if (val == 0 && ['line', 'path'].indexOf(current_mode) >= 0) { +this.setStrokeWidth = function (val) { + if (val === 0 && ['line', 'path'].indexOf(currentMode) >= 0) { canvas.setStrokeWidth(1); return; } - cur_properties.stroke_width = val; + curProperties.stroke_width = val; var elems = []; function addNonG (e) { - if (e.nodeName != 'g') { + if (e.nodeName !== 'g') { elems.push(e); } } @@ -5616,10 +5597,9 @@ this.setStrokeWidth = function(val) { while (i--) { var elem = selectedElements[i]; if (elem) { - if (elem.tagName == 'g') { + if (elem.tagName === 'g') { svgedit.utilities.walkTree(elem, addNonG); - } - else { + } else { elems.push(elem); } } @@ -5636,22 +5616,17 @@ this.setStrokeWidth = function(val) { // Parameters: // attr - String with the attribute name // val - String or number with the attribute value -this.setStrokeAttr = function(attr, val) { - cur_shape[attr.replace('-', '_')] = val; +this.setStrokeAttr = function (attr, val) { + curShape[attr.replace('-', '_')] = val; var elems = []; - function addNonG (e) { - if (e.nodeName != 'g') { - elems.push(e); - } - } + var i = selectedElements.length; while (i--) { var elem = selectedElements[i]; if (elem) { - if (elem.tagName == 'g') { - svgedit.utilities.walkTree(elem, function(e){if (e.nodeName!='g') {elems.push(e);}}); - } - else { + if (elem.tagName === 'g') { + svgedit.utilities.walkTree(elem, function (e) { if (e.nodeName !== 'g') { elems.push(e); } }); + } else { elems.push(elem); } } @@ -5664,33 +5639,33 @@ this.setStrokeAttr = function(attr, val) { // Function: getStyle // Returns current style options -this.getStyle = function() { - return cur_shape; +this.getStyle = function () { + return curShape; }; // Function: getOpacity // Returns the current opacity -this.getOpacity = function() { - return cur_shape.opacity; +this.getOpacity = function () { + return curShape.opacity; }; // Function: setOpacity // Sets the given opacity to the current selected elements -this.setOpacity = function(val) { - cur_shape.opacity = val; +this.setOpacity = function (val) { + curShape.opacity = val; changeSelectedAttribute('opacity', val); }; // Function: getOpacity // Returns the current fill opacity -this.getFillOpacity = function() { - return cur_shape.fill_opacity; +this.getFillOpacity = function () { + return curShape.fill_opacity; }; // Function: getStrokeOpacity // Returns the current stroke opacity -this.getStrokeOpacity = function() { - return cur_shape.stroke_opacity; +this.getStrokeOpacity = function () { + return curShape.stroke_opacity; }; // Function: setPaintOpacity @@ -5700,12 +5675,11 @@ this.getStrokeOpacity = function() { // type - String with "fill" or "stroke" // val - Float with the new opacity value // preventUndo - Boolean indicating whether or not this should be an undoable action -this.setPaintOpacity = function(type, val, preventUndo) { - cur_shape[type + '_opacity'] = val; +this.setPaintOpacity = function (type, val, preventUndo) { + curShape[type + '_opacity'] = val; if (!preventUndo) { changeSelectedAttribute(type + '-opacity', val); - } - else { + } else { changeSelectedAttributeNoUndo(type + '-opacity', val); } }; @@ -5715,7 +5689,7 @@ this.setPaintOpacity = function(type, val, preventUndo) { // // Parameters: // type - String with "fill" or "stroke" -this.getPaintOpacity = function(type) { +this.getPaintOpacity = function (type) { return type === 'fill' ? this.getFillOpacity() : this.getStrokeOpacity(); }; @@ -5724,13 +5698,13 @@ this.getPaintOpacity = function(type) { // // Parameters: // elem - The element to check the blur value for -this.getBlur = function(elem) { +this.getBlur = function (elem) { var val = 0; // var elem = selectedElements[0]; if (elem) { - var filter_url = elem.getAttribute('filter'); - if (filter_url) { + var filterUrl = elem.getAttribute('filter'); + if (filterUrl) { var blur = svgedit.utilities.getElem(elem.id + '_blur'); if (blur) { val = blur.firstChild.getAttribute('stdDeviation'); @@ -5740,8 +5714,8 @@ this.getBlur = function(elem) { return val; }; -(function() { - var cur_command = null; +(function () { + var curCommand = null; var filter = null; var filterHidden = false; @@ -5750,7 +5724,7 @@ this.getBlur = function(elem) { // // Parameters: // val - The new stdDeviation value - canvas.setBlurNoUndo = function(val) { + canvas.setBlurNoUndo = function (val) { if (!filter) { canvas.setBlur(val); return; @@ -5775,11 +5749,11 @@ this.getBlur = function(elem) { } }; - function finishChange() { + function finishChange () { var bCmd = canvas.undoMgr.finishUndoableChange(); - cur_command.addSubCommand(bCmd); - addCommandToHistory(cur_command); - cur_command = null; + curCommand.addSubCommand(bCmd); + addCommandToHistory(curCommand); + curCommand = null; filter = null; } @@ -5790,7 +5764,7 @@ this.getBlur = function(elem) { // Parameters: // filter - The filter DOM element to update // stdDev - The standard deviation value on which to base the offset size - canvas.setBlurOffsets = function(filter, stdDev) { + canvas.setBlurOffsets = function (filter, stdDev) { if (stdDev > 3) { // TODO: Create algorithm here where size is based on expected blur svgedit.utilities.assignAttributes(filter, { @@ -5816,16 +5790,16 @@ this.getBlur = function(elem) { // Parameters: // val - Float with the new stdDeviation blur value // complete - Boolean indicating whether or not the action should be completed (to add to the undo manager) - canvas.setBlur = function(val, complete) { - if (cur_command) { + canvas.setBlur = function (val, complete) { + if (curCommand) { finishChange(); return; } // Looks for associated blur, creates one if not found var elem = selectedElements[0]; - var elem_id = elem.id; - filter = svgedit.utilities.getElem(elem_id + '_blur'); + var elemId = elem.id; + filter = svgedit.utilities.getElem(elemId + '_blur'); val -= 0; @@ -5847,7 +5821,7 @@ this.getBlur = function(elem) { filter = addSvgElementFromJson({ 'element': 'filter', 'attr': { - 'id': elem_id + '_blur' + 'id': elemId + '_blur' } }); @@ -5865,12 +5839,12 @@ this.getBlur = function(elem) { return; } - changeSelectedAttribute('filter', 'url(#' + elem_id + '_blur)'); + changeSelectedAttribute('filter', 'url(#' + elemId + '_blur)'); batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(elem, changes)); canvas.setBlurOffsets(filter, val); - cur_command = batchCmd; - canvas.undoMgr.beginUndoableChange('stdDeviation', [filter?filter.firstChild:null]); + curCommand = batchCmd; + canvas.undoMgr.beginUndoableChange('stdDeviation', [filter ? filter.firstChild : null]); if (complete) { canvas.setBlurNoUndo(val); finishChange(); @@ -5883,13 +5857,12 @@ this.getBlur = function(elem) { // // Returns: // Boolean indicating whether or not element is bold -this.getBold = function() { +this.getBold = function () { // should only have one element selected var selected = selectedElements[0]; - if (selected != null && selected.tagName == 'text' && - selectedElements[1] == null) - { - return (selected.getAttribute('font-weight') == 'bold'); + if (selected != null && selected.tagName === 'text' && + selectedElements[1] == null) { + return (selected.getAttribute('font-weight') === 'bold'); } return false; }; @@ -5899,11 +5872,10 @@ this.getBold = function() { // // Parameters: // b - Boolean indicating bold (true) or normal (false) -this.setBold = function(b) { +this.setBold = function (b) { var selected = selectedElements[0]; - if (selected != null && selected.tagName == 'text' && - selectedElements[1] == null) - { + if (selected != null && selected.tagName === 'text' && + selectedElements[1] == null) { changeSelectedAttribute('font-weight', b ? 'bold' : 'normal'); } if (!selectedElements[0].textContent) { @@ -5916,12 +5888,11 @@ this.setBold = function(b) { // // Returns: // Boolean indicating whether or not element is italic -this.getItalic = function() { +this.getItalic = function () { var selected = selectedElements[0]; - if (selected != null && selected.tagName == 'text' && - selectedElements[1] == null) - { - return (selected.getAttribute('font-style') == 'italic'); + if (selected != null && selected.tagName === 'text' && + selectedElements[1] == null) { + return (selected.getAttribute('font-style') === 'italic'); } return false; }; @@ -5931,11 +5902,10 @@ this.getItalic = function() { // // Parameters: // b - Boolean indicating italic (true) or normal (false) -this.setItalic = function(i) { +this.setItalic = function (i) { var selected = selectedElements[0]; - if (selected != null && selected.tagName == 'text' && - selectedElements[1] == null) - { + if (selected != null && selected.tagName === 'text' && + selectedElements[1] == null) { changeSelectedAttribute('font-style', i ? 'italic' : 'normal'); } if (!selectedElements[0].textContent) { @@ -5945,8 +5915,8 @@ this.setItalic = function(i) { // Function: getFontFamily // Returns the current font family -this.getFontFamily = function() { - return cur_text.font_family; +this.getFontFamily = function () { + return curText.font_family; }; // Function: setFontFamily @@ -5954,35 +5924,34 @@ this.getFontFamily = function() { // // Parameters: // val - String with the new font family -this.setFontFamily = function(val) { - cur_text.font_family = val; +this.setFontFamily = function (val) { + curText.font_family = val; changeSelectedAttribute('font-family', val); if (selectedElements[0] && !selectedElements[0].textContent) { textActions.setCursor(); } }; - // Function: setFontColor // Set the new font color // // Parameters: // val - String with the new font color -this.setFontColor = function(val) { - cur_text.fill = val; +this.setFontColor = function (val) { + curText.fill = val; changeSelectedAttribute('fill', val); }; // Function: getFontColor // Returns the current font color -this.getFontColor = function() { - return cur_text.fill; +this.getFontColor = function () { + return curText.fill; }; // Function: getFontSize // Returns the current font size -this.getFontSize = function() { - return cur_text.font_size; +this.getFontSize = function () { + return curText.font_size; }; // Function: setFontSize @@ -5990,8 +5959,8 @@ this.getFontSize = function() { // // Parameters: // val - Float with the new font size -this.setFontSize = function(val) { - cur_text.font_size = val; +this.setFontSize = function (val) { + curText.font_size = val; changeSelectedAttribute('font-size', val); if (!selectedElements[0].textContent) { textActions.setCursor(); @@ -6000,7 +5969,7 @@ this.setFontSize = function(val) { // Function: getText // Returns the current text (textContent) of the selected element -this.getText = function() { +this.getText = function () { var selected = selectedElements[0]; if (selected == null) { return ''; } return selected.textContent; @@ -6011,7 +5980,7 @@ this.getText = function() { // // Parameters: // val - String with the new text -this.setTextContent = function(val) { +this.setTextContent = function (val) { changeSelectedAttribute('#text', val); textActions.init(val); textActions.setCursor(); @@ -6023,29 +5992,29 @@ this.setTextContent = function(val) { // // Parameters: // val - String with the image URL/path -this.setImageURL = function(val) { +this.setImageURL = function (val) { var elem = selectedElements[0]; - if (!elem) {return;} + if (!elem) { return; } var attrs = $(elem).attr(['width', 'height']); var setsize = (!attrs.width || !attrs.height); - var cur_href = getHref(elem); + var curHref = getHref(elem); // Do nothing if no URL change or size change - if (cur_href !== val) { + if (curHref !== val) { setsize = true; - } else if (!setsize) {return;} + } else if (!setsize) { return; } var batchCmd = new svgedit.history.BatchCommand('Change Image URL'); setHref(elem, val); batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(elem, { - '#href': cur_href + '#href': curHref })); if (setsize) { - $(new Image()).load(function() { + $(new Image()).load(function () { var changes = $(elem).attr(['width', 'height']); $(elem).attr({ @@ -6069,47 +6038,46 @@ this.setImageURL = function(val) { // // Parameters: // val - String with the link URL/path -this.setLinkURL = function(val) { +this.setLinkURL = function (val) { var elem = selectedElements[0]; - if (!elem) {return;} + if (!elem) { return; } if (elem.tagName !== 'a') { // See if parent is an anchor - var parents_a = $(elem).parents('a'); - if (parents_a.length) { - elem = parents_a[0]; + var parentsA = $(elem).parents('a'); + if (parentsA.length) { + elem = parentsA[0]; } else { return; } } - var cur_href = getHref(elem); + var curHref = getHref(elem); - if (cur_href === val) {return;} + if (curHref === val) { return; } var batchCmd = new svgedit.history.BatchCommand('Change Link URL'); setHref(elem, val); batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(elem, { - '#href': cur_href + '#href': curHref })); addCommandToHistory(batchCmd); }; - // Function: setRectRadius // Sets the rx & ry values to the selected rect element to change its corner radius // // Parameters: // val - The new radius -this.setRectRadius = function(val) { +this.setRectRadius = function (val) { var selected = selectedElements[0]; - if (selected != null && selected.tagName == 'rect') { + if (selected != null && selected.tagName === 'rect') { var r = selected.getAttribute('rx'); - if (r != val) { + if (r !== String(val)) { selected.setAttribute('rx', val); selected.setAttribute('ry', val); - addCommandToHistory(new svgedit.history.ChangeElementCommand(selected, {'rx':r, 'ry':r}, 'Radius')); + addCommandToHistory(new svgedit.history.ChangeElementCommand(selected, {'rx': r, 'ry': r}, 'Radius')); call('changed', [selected]); } } @@ -6117,16 +6085,15 @@ this.setRectRadius = function(val) { // Function: makeHyperlink // Wraps the selected element(s) in an anchor element or converts group to one -this.makeHyperlink = function(url) { +this.makeHyperlink = function (url) { canvas.groupSelectedElements('a', url); // TODO: If element is a single "g", convert to "a" // if (selectedElements.length > 1 && selectedElements[1]) { - }; // Function: removeHyperlink -this.removeHyperlink = function() { +this.removeHyperlink = function () { canvas.ungroupSelectedElement(); }; @@ -6138,8 +6105,8 @@ this.removeHyperlink = function() { // Parameters: // new_type - Integer with the new segment type // See http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSeg for list -this.setSegType = function(new_type) { - pathActions.setSegType(new_type); +this.setSegType = function (newType) { + pathActions.setSegType(newType); }; // TODO(codedread): Remove the getBBox argument and split this function into two. @@ -6153,36 +6120,35 @@ this.setSegType = function(new_type) { // Returns: // If the getBBox flag is true, the resulting path's bounding box object. // Otherwise the resulting path element is returned. -this.convertToPath = function(elem, getBBox) { +this.convertToPath = function (elem, getBBox) { if (elem == null) { var elems = selectedElements; - $.each(elems, function(i, elem) { - if (elem) {canvas.convertToPath(elem);} + $.each(elems, function (i, elem) { + if (elem) { canvas.convertToPath(elem); } }); return; } if (getBBox) { - return svgedit.utilities.getBBoxOfElementAsPath(elem, addSvgElementFromJson, pathActions) + return svgedit.utilities.getBBoxOfElementAsPath(elem, addSvgElementFromJson, pathActions); } else { - // TODO: Why is this applying attributes from cur_shape, then inside utilities.convertToPath it's pulling addition attributes from elem? - // TODO: If convertToPath is called with one elem, cur_shape and elem are probably the same; but calling with multiple is a bug or cool feature. + // TODO: Why is this applying attributes from curShape, then inside utilities.convertToPath it's pulling addition attributes from elem? + // TODO: If convertToPath is called with one elem, curShape and elem are probably the same; but calling with multiple is a bug or cool feature. var attrs = { - 'fill': cur_shape.fill, - 'fill-opacity': cur_shape.fill_opacity, - 'stroke': cur_shape.stroke, - 'stroke-width': cur_shape.stroke_width, - 'stroke-dasharray': cur_shape.stroke_dasharray, - 'stroke-linejoin': cur_shape.stroke_linejoin, - 'stroke-linecap': cur_shape.stroke_linecap, - 'stroke-opacity': cur_shape.stroke_opacity, - 'opacity': cur_shape.opacity, - 'visibility':'hidden' + 'fill': curShape.fill, + 'fill-opacity': curShape.fill_opacity, + 'stroke': curShape.stroke, + 'stroke-width': curShape.stroke_width, + 'stroke-dasharray': curShape.stroke_dasharray, + 'stroke-linejoin': curShape.stroke_linejoin, + 'stroke-linecap': curShape.stroke_linecap, + 'stroke-opacity': curShape.stroke_opacity, + 'opacity': curShape.opacity, + 'visibility': 'hidden' }; return svgedit.utilities.convertToPath(elem, attrs, addSvgElementFromJson, pathActions, clearSelection, addToSelection, svgedit.history, addCommandToHistory); } }; - // Function: changeSelectedAttributeNoUndo // This function makes the changes to the elements. It does not add the change // to the history stack. @@ -6191,78 +6157,76 @@ this.convertToPath = function(elem, getBBox) { // attr - String with the attribute name // newValue - String or number with the new attribute value // elems - The DOM elements to apply the change to -var changeSelectedAttributeNoUndo = function(attr, newValue, elems) { - if (current_mode == 'pathedit') { +var changeSelectedAttributeNoUndo = function (attr, newValue, elems) { + if (currentMode === 'pathedit') { // Editing node pathActions.moveNode(attr, newValue); } elems = elems || selectedElements; var i = elems.length; - var no_xy_elems = ['g', 'polyline', 'path']; - var good_g_attrs = ['transform', 'opacity', 'filter']; + var noXYElems = ['g', 'polyline', 'path']; + var goodGAttrs = ['transform', 'opacity', 'filter']; while (i--) { var elem = elems[i]; - if (elem == null) {continue;} + if (elem == null) { continue; } // Set x,y vals on elements that don't have them - if ((attr === 'x' || attr === 'y') && no_xy_elems.indexOf(elem.tagName) >= 0) { + if ((attr === 'x' || attr === 'y') && noXYElems.indexOf(elem.tagName) >= 0) { var bbox = getStrokedBBox([elem]); - var diff_x = attr === 'x' ? newValue - bbox.x : 0; - var diff_y = attr === 'y' ? newValue - bbox.y : 0; - canvas.moveSelectedElements(diff_x*current_zoom, diff_y*current_zoom, true); + var diffX = attr === 'x' ? newValue - bbox.x : 0; + var diffY = attr === 'y' ? newValue - bbox.y : 0; + canvas.moveSelectedElements(diffX * currentZoom, diffY * currentZoom, true); continue; } // only allow the transform/opacity/filter attribute to change on elements, slightly hacky // TODO: FIXME: This doesn't seem right. Where's the body of this if statement? - if (elem.tagName === 'g' && good_g_attrs.indexOf(attr) >= 0) {} + if (elem.tagName === 'g' && goodGAttrs.indexOf(attr) >= 0) {} var oldval = attr === '#text' ? elem.textContent : elem.getAttribute(attr); - if (oldval == null) {oldval = '';} + if (oldval == null) { oldval = ''; } if (oldval !== String(newValue)) { - if (attr == '#text') { - var old_w = svgedit.utilities.getBBox(elem).width; + if (attr === '#text') { + // var oldW = svgedit.utilities.getBBox(elem).width; elem.textContent = newValue; // FF bug occurs on on rotated elements - if (/rotate/.test(elem.getAttribute('transform'))) { + if ((/rotate/).test(elem.getAttribute('transform'))) { elem = ffClone(elem); } - // Hoped to solve the issue of moving text with text-anchor="start", // but this doesn't actually fix it. Hopefully on the right track, though. -Fyrd - -// var box=getBBox(elem), left=box.x, top=box.y, width=box.width, -// height=box.height, dx = width - old_w, dy=0; -// var angle = svgedit.utilities.getRotationAngle(elem, true); -// if (angle) { -// var r = Math.sqrt( dx*dx + dy*dy ); -// var theta = Math.atan2(dy,dx) - angle; -// dx = r * Math.cos(theta); -// dy = r * Math.sin(theta); -// -// elem.setAttribute('x', elem.getAttribute('x')-dx); -// elem.setAttribute('y', elem.getAttribute('y')-dy); -// } - - } else if (attr == '#href') { + // var box = getBBox(elem), left = box.x, top = box.y, width = box.width, + // height = box.height, dx = width - oldW, dy = 0; + // var angle = svgedit.utilities.getRotationAngle(elem, true); + // if (angle) { + // var r = Math.sqrt(dx * dx + dy * dy); + // var theta = Math.atan2(dy, dx) - angle; + // dx = r * Math.cos(theta); + // dy = r * Math.sin(theta); + // + // elem.setAttribute('x', elem.getAttribute('x') - dx); + // elem.setAttribute('y', elem.getAttribute('y') - dy); + // } + } else if (attr === '#href') { setHref(elem, newValue); - } - else {elem.setAttribute(attr, newValue);} + } else { elem.setAttribute(attr, newValue); } // Go into "select" mode for text changes // NOTE: Important that this happens AFTER elem.setAttribute() or else attributes like // font-size can get reset to their old value, ultimately by svgEditor.updateContextPanel(), // after calling textActions.toSelectMode() below - if (current_mode === 'textedit' && attr !== '#text' && elem.textContent.length) { + if (currentMode === 'textedit' && attr !== '#text' && elem.textContent.length) { textActions.toSelectMode(elem); } -// if (i==0) -// selectedBBoxes[0] = svgedit.utilities.getBBox(elem); + // if (i === 0) { + // selectedBBoxes[0] = svgedit.utilities.getBBox(elem); + // } + // Use the Firefox ffClone hack for text elements with gradients or // where other text attributes are changed. - if (svgedit.browser.isGecko() && elem.nodeName === 'text' && /rotate/.test(elem.getAttribute('transform'))) { + if (svgedit.browser.isGecko() && elem.nodeName === 'text' && (/rotate/).test(elem.getAttribute('transform'))) { if (String(newValue).indexOf('url') === 0 || (['font-size', 'font-family', 'x', 'y'].indexOf(attr) >= 0 && elem.textContent)) { elem = ffClone(elem); } @@ -6272,27 +6236,27 @@ var changeSelectedAttributeNoUndo = function(attr, newValue, elems) { // that are not in the selectedElements array, we need to only request a // selector if the element is in that array if (selectedElements.indexOf(elem) >= 0) { - setTimeout(function() { + setTimeout(function () { // Due to element replacement, this element may no longer // be part of the DOM - if (!elem.parentNode) {return;} + if (!elem.parentNode) { return; } selectorManager.requestSelector(elem).resize(); }, 0); } // if this element was rotated, and we changed the position of this element // we need to update the rotational transform attribute var angle = svgedit.utilities.getRotationAngle(elem); - if (angle != 0 && attr != 'transform') { + if (angle !== 0 && attr !== 'transform') { var tlist = svgedit.transformlist.getTransformList(elem); var n = tlist.numberOfItems; while (n--) { var xform = tlist.getItem(n); - if (xform.type == 4) { + if (xform.type === 4) { // remove old rotate tlist.removeItem(n); var box = svgedit.utilities.getBBox(elem); - var center = svgedit.math.transformPoint(box.x+box.width/2, box.y+box.height/2, svgedit.math.transformListToTransform(tlist).matrix); + var center = svgedit.math.transformPoint(box.x + box.width / 2, box.y + box.height / 2, svgedit.math.transformListToTransform(tlist).matrix); var cx = center.x, cy = center.y; var newrot = svgroot.createSVGTransform(); @@ -6316,10 +6280,10 @@ var changeSelectedAttributeNoUndo = function(attr, newValue, elems) { // attr - String with the attribute name // newValue - String or number with the new attribute value // elems - The DOM elements to apply the change to -var changeSelectedAttribute = this.changeSelectedAttribute = function(attr, val, elems) { +var changeSelectedAttribute = this.changeSelectedAttribute = function (attr, val, elems) { elems = elems || selectedElements; canvas.undoMgr.beginUndoableChange(attr, elems); - var i = elems.length; + // var i = elems.length; changeSelectedAttributeNoUndo(attr, val, elems); @@ -6332,15 +6296,15 @@ var changeSelectedAttribute = this.changeSelectedAttribute = function(attr, val, // Function: deleteSelectedElements // Removes all selected elements from the DOM and adds the change to the // history stack -this.deleteSelectedElements = function() { +this.deleteSelectedElements = function () { var i; var batchCmd = new svgedit.history.BatchCommand('Delete Elements'); var len = selectedElements.length; - var selectedCopy = []; //selectedElements is being deleted + var selectedCopy = []; // selectedElements is being deleted for (i = 0; i < len; ++i) { var selected = selectedElements[i]; - if (selected == null) {break;} + if (selected == null) { break; } var parent = selected.parentNode; var t = selected; @@ -6359,12 +6323,12 @@ this.deleteSelectedElements = function() { var nextSibling = t.nextSibling; var elem = parent.removeChild(t); - selectedCopy.push(selected); //for the copy + selectedCopy.push(selected); // for the copy batchCmd.addSubCommand(new RemoveElementCommand(elem, nextSibling, parent)); } selectedElements = []; - if (!batchCmd.isEmpty()) {addCommandToHistory(batchCmd);} + if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); } call('changed', selectedCopy); clearSelection(); }; @@ -6372,49 +6336,48 @@ this.deleteSelectedElements = function() { // Function: cutSelectedElements // Removes all selected elements from the DOM and adds the change to the // history stack. Remembers removed elements on the clipboard -this.cutSelectedElements = function() { +this.cutSelectedElements = function () { svgCanvas.copySelectedElements(); svgCanvas.deleteSelectedElements(); }; // Function: copySelectedElements // Remembers the current selected elements on the clipboard -this.copySelectedElements = function() { +this.copySelectedElements = function () { localStorage.setItem('svgedit_clipboard', JSON.stringify( - selectedElements.map(function(x){ return getJsonFromSvgElement(x) }) + selectedElements.map(function (x) { return getJsonFromSvgElement(x); }) )); $('#cmenu_canvas').enableContextMenuItems('#paste,#paste_in_place'); }; -this.pasteElements = function(type, x, y) { +this.pasteElements = function (type, x, y) { var cb = JSON.parse(localStorage.getItem('svgedit_clipboard')); var len = cb.length; - if (!len) {return;} + if (!len) { return; } var pasted = []; var batchCmd = new svgedit.history.BatchCommand('Paste elements'); - var drawing = getCurrentDrawing(); + // var drawing = getCurrentDrawing(); var changedIDs = {}; // Recursively replace IDs and record the changes - function checkIDs(elem) { - if(elem.attr && elem.attr.id) { + function checkIDs (elem) { + if (elem.attr && elem.attr.id) { changedIDs[elem.attr.id] = getNextId(); elem.attr.id = changedIDs[elem.attr.id]; } - if(elem.children) elem.children.forEach(checkIDs); + if (elem.children) elem.children.forEach(checkIDs); } cb.forEach(checkIDs); // Give extensions like the connector extension a chance to reflect new IDs and remove invalid elements - runExtensions('IDsUpdated', {elems: cb, changes: changedIDs}, true).forEach(function(extChanges){ - if(!extChanges || !('remove' in extChanges)) return; - - extChanges.remove.forEach(function(removeID){ - cb = cb.filter(function(cbItem){ - return cbItem.attr.id != removeID; + runExtensions('IDsUpdated', {elems: cb, changes: changedIDs}, true).forEach(function (extChanges) { + if (!extChanges || !('remove' in extChanges)) return; + extChanges.remove.forEach(function (removeID) { + cb = cb.filter(function (cbItem) { + return cbItem.attr.id !== removeID; }); }); }); @@ -6422,7 +6385,7 @@ this.pasteElements = function(type, x, y) { // Move elements to lastClickPoint while (len--) { var elem = cb[len]; - if (!elem) {continue;} + if (!elem) { continue; } var copy = addSvgElementFromJson(elem); pasted.push(copy); @@ -6434,30 +6397,29 @@ this.pasteElements = function(type, x, y) { selectOnly(pasted); if (type !== 'in_place') { - - var ctr_x, ctr_y; + var ctrX, ctrY; if (!type) { - ctr_x = lastClickPoint.x; - ctr_y = lastClickPoint.y; + ctrX = lastClickPoint.x; + ctrY = lastClickPoint.y; } else if (type === 'point') { - ctr_x = x; - ctr_y = y; + ctrX = x; + ctrY = y; } var bbox = getStrokedBBox(pasted); - var cx = ctr_x - (bbox.x + bbox.width/2), - cy = ctr_y - (bbox.y + bbox.height/2), + var cx = ctrX - (bbox.x + bbox.width / 2), + cy = ctrY - (bbox.y + bbox.height / 2), dx = [], dy = []; - $.each(pasted, function(i, item) { + $.each(pasted, function (i, item) { dx.push(cx); dy.push(cy); }); var cmd = canvas.moveSelectedElements(dx, dy, false); - if(cmd) batchCmd.addSubCommand(cmd); + if (cmd) batchCmd.addSubCommand(cmd); } addCommandToHistory(batchCmd); @@ -6469,13 +6431,13 @@ this.pasteElements = function(type, x, y) { // Parameters: // type - type of element to group into, defaults to -this.groupSelectedElements = function(type, urlArg) { - if (!type) {type = 'g';} - var cmd_str = ''; +this.groupSelectedElements = function (type, urlArg) { + if (!type) { type = 'g'; } + var cmdStr = ''; switch (type) { case 'a': - cmd_str = 'Make hyperlink'; + cmdStr = 'Make hyperlink'; var url = ''; if (arguments.length > 1) { url = urlArg; @@ -6483,19 +6445,19 @@ this.groupSelectedElements = function(type, urlArg) { break; default: type = 'g'; - cmd_str = 'Group Elements'; + cmdStr = 'Group Elements'; break; } - var batchCmd = new svgedit.history.BatchCommand(cmd_str); + var batchCmd = new svgedit.history.BatchCommand(cmdStr); // create and insert the group element var g = addSvgElementFromJson({ - 'element': type, - 'attr': { - 'id': getNextId() - } - }); + 'element': type, + 'attr': { + 'id': getNextId() + } + }); if (type === 'a') { setHref(g, url); } @@ -6505,7 +6467,7 @@ this.groupSelectedElements = function(type, urlArg) { var i = selectedElements.length; while (i--) { var elem = selectedElements[i]; - if (elem == null) {continue;} + if (elem == null) { continue; } if (elem.parentNode.tagName === 'a' && elem.parentNode.childNodes.length === 1) { elem = elem.parentNode; @@ -6516,18 +6478,16 @@ this.groupSelectedElements = function(type, urlArg) { g.appendChild(elem); batchCmd.addSubCommand(new svgedit.history.MoveElementCommand(elem, oldNextSibling, oldParent)); } - if (!batchCmd.isEmpty()) {addCommandToHistory(batchCmd);} + if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); } // update selection selectOnly([g], true); }; - // Function: pushGroupProperties // Pushes all appropriate parent group properties down to its children, then // removes them from the group -var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { - +var pushGroupProperties = this.pushGroupProperties = function (g, undoable) { var children = g.childNodes; var len = children.length; var xform = g.getAttribute('transform'); @@ -6554,18 +6514,18 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { for (i = 0; i < len; i++) { var elem = children[i]; - if (elem.nodeType !== 1) {continue;} + if (elem.nodeType !== 1) { continue; } if (gattrs.opacity !== null && gattrs.opacity !== 1) { - var c_opac = elem.getAttribute('opacity') || 1; - var new_opac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100)/100; - changeSelectedAttribute('opacity', new_opac, [elem]); + // var c_opac = elem.getAttribute('opacity') || 1; + var newOpac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100) / 100; + changeSelectedAttribute('opacity', newOpac, [elem]); } if (gattrs.filter) { var cblur = this.getBlur(elem); - var orig_cblur = cblur; - if (!gblur) {gblur = this.getBlur(g);} + var origCblur = cblur; + if (!gblur) { gblur = this.getBlur(g); } if (cblur) { // Is this formula correct? cblur = Number(gblur) + Number(cblur); @@ -6574,7 +6534,7 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { } // If child has no current filter, get group's filter or clone it. - if (!orig_cblur) { + if (!origCblur) { // Set group's filter to use first child's ID if (!gfilter) { gfilter = svgedit.utilities.getRefElem(gattrs.filter); @@ -6588,7 +6548,7 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { } // Change this in future for different filters - var suffix = (gfilter.firstChild.tagName === 'feGaussianBlur')?'blur':'filter'; + var suffix = (gfilter.firstChild.tagName === 'feGaussianBlur') ? 'blur' : 'filter'; gfilter.id = elem.id + '_' + suffix; changeSelectedAttribute('filter', 'url(#' + gfilter.id + ')', [elem]); @@ -6602,19 +6562,19 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { var chtlist = svgedit.transformlist.getTransformList(elem); // Don't process gradient transforms - if (~elem.tagName.indexOf('Gradient')) {chtlist = null;} + if (~elem.tagName.indexOf('Gradient')) { chtlist = null; } // Hopefully not a problem to add this. Necessary for elements like - if (!chtlist) {continue;} + if (!chtlist) { continue; } // Apparently can get get a transformlist, but we don't want it to have one! - if (elem.tagName === 'defs') {continue;} + if (elem.tagName === 'defs') { continue; } if (glist.numberOfItems) { // TODO: if the group's transform is just a rotate, we can always transfer the // rotate() down to the children (collapsing consecutive rotates and factoring // out any translates) - if (gangle && glist.numberOfItems == 1) { + if (gangle && glist.numberOfItems === 1) { // [Rg] [Rc] [Mc] // we want [Tr] [Rc2] [Mc] where: // - [Rc2] is at the child's current center but has the @@ -6637,7 +6597,7 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { // get child's old center of rotation var cbox = svgedit.utilities.getBBox(elem); var ceqm = svgedit.math.transformListToTransform(chtlist).matrix; - var coldc = svgedit.math.transformPoint(cbox.x+cbox.width/2, cbox.y+cbox.height/2, ceqm); + var coldc = svgedit.math.transformPoint(cbox.x + cbox.width / 2, cbox.y + cbox.height / 2, ceqm); // sum group and child's angles var sangle = gangle + cangle; @@ -6672,7 +6632,6 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { } } } else { // more complicated than just a rotate - // transfer the group's transform down to each child and then // call svgedit.recalculate.recalculateDimensions() var oldxform = elem.getAttribute('transform'); @@ -6682,19 +6641,18 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { var newxform = svgroot.createSVGTransform(); // [ gm ] [ chm ] = [ chm ] [ gm' ] - // [ gm' ] = [ chm_inv ] [ gm ] [ chm ] + // [ gm' ] = [ chmInv ] [ gm ] [ chm ] var chm = svgedit.math.transformListToTransform(chtlist).matrix, - chm_inv = chm.inverse(); - var gm = svgedit.math.matrixMultiply( chm_inv, m, chm ); + chmInv = chm.inverse(); + var gm = svgedit.math.matrixMultiply(chmInv, m, chm); newxform.setMatrix(gm); chtlist.appendItem(newxform); } var cmd = svgedit.recalculate.recalculateDimensions(elem); - if (cmd) {batchCmd.addSubCommand(cmd);} + if (cmd) { batchCmd.addSubCommand(cmd); } } } - // remove transform and make it undo-able if (xform) { changes = {}; @@ -6709,11 +6667,10 @@ var pushGroupProperties = this.pushGroupProperties = function(g, undoable) { } }; - // Function: ungroupSelectedElement // Unwraps all the elements in a selected group (g) element. This requires // significant recalculations to apply group's transforms, etc to its children -this.ungroupSelectedElement = function() { +this.ungroupSelectedElement = function () { var g = selectedElements[0]; if (!g) { return; @@ -6730,17 +6687,16 @@ this.ungroupSelectedElement = function() { convertToGroup(g); return; } - var parents_a = $(g).parents('a'); - if (parents_a.length) { - g = parents_a[0]; + var parentsA = $(g).parents('a'); + if (parentsA.length) { + g = parentsA[0]; } // Look for parent "a" if (g.tagName === 'g' || g.tagName === 'a') { - var batchCmd = new svgedit.history.BatchCommand('Ungroup Elements'); var cmd = pushGroupProperties(g, true); - if (cmd) {batchCmd.addSubCommand(cmd);} + if (cmd) { batchCmd.addSubCommand(cmd); } var parent = g.parentNode; var anchor = g.nextSibling; @@ -6773,7 +6729,7 @@ this.ungroupSelectedElement = function() { g = parent.removeChild(g); batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(g, gNextSibling, parent)); - if (!batchCmd.isEmpty()) {addCommandToHistory(batchCmd);} + if (!batchCmd.isEmpty()) { addCommandToHistory(batchCmd); } // update selection addToSelection(children); @@ -6783,7 +6739,7 @@ this.ungroupSelectedElement = function() { // Function: moveToTopSelectedElement // Repositions the selected element to the bottom in the DOM to appear on top of // other elements -this.moveToTopSelectedElement = function() { +this.moveToTopSelectedElement = function () { var selected = selectedElements[0]; if (selected != null) { var t = selected; @@ -6792,7 +6748,7 @@ this.moveToTopSelectedElement = function() { t = t.parentNode.appendChild(t); // If the element actually moved position, add the command and fire the changed // event handler. - if (oldNextSibling != t.nextSibling) { + if (oldNextSibling !== t.nextSibling) { addCommandToHistory(new svgedit.history.MoveElementCommand(t, oldNextSibling, oldParent, 'top')); call('changed', [t]); } @@ -6802,25 +6758,25 @@ this.moveToTopSelectedElement = function() { // Function: moveToBottomSelectedElement // Repositions the selected element to the top in the DOM to appear under // other elements -this.moveToBottomSelectedElement = function() { +this.moveToBottomSelectedElement = function () { var selected = selectedElements[0]; if (selected != null) { var t = selected; var oldParent = t.parentNode; var oldNextSibling = t.nextSibling; var firstChild = t.parentNode.firstChild; - if (firstChild.tagName == 'title') { + if (firstChild.tagName === 'title') { firstChild = firstChild.nextSibling; } // This can probably be removed, as the defs should not ever apppear // inside a layer group - if (firstChild.tagName == 'defs') { + if (firstChild.tagName === 'defs') { firstChild = firstChild.nextSibling; } t = t.parentNode.insertBefore(t, firstChild); // If the element actually moved position, add the command and fire the changed // event handler. - if (oldNextSibling != t.nextSibling) { + if (oldNextSibling !== t.nextSibling) { addCommandToHistory(new svgedit.history.MoveElementCommand(t, oldNextSibling, oldParent, 'bottom')); call('changed', [t]); } @@ -6833,35 +6789,35 @@ this.moveToBottomSelectedElement = function() { // // Parameters: // dir - String that's either 'Up' or 'Down' -this.moveUpDownSelected = function(dir) { +this.moveUpDownSelected = function (dir) { var selected = selectedElements[0]; - if (!selected) {return;} + if (!selected) { return; } curBBoxes = []; - var closest, found_cur; + var closest, foundCur; // jQuery sorts this list var list = $(getIntersectionList(getStrokedBBox([selected]))).toArray(); - if (dir == 'Down') {list.reverse();} + if (dir === 'Down') { list.reverse(); } - $.each(list, function() { - if (!found_cur) { - if (this == selected) { - found_cur = true; + $.each(list, function () { + if (!foundCur) { + if (this === selected) { + foundCur = true; } return; } closest = this; return false; }); - if (!closest) {return;} + if (!closest) { return; } var t = selected; var oldParent = t.parentNode; var oldNextSibling = t.nextSibling; - $(closest)[dir == 'Down'?'before':'after'](t); + $(closest)[dir === 'Down' ? 'before' : 'after'](t); // If the element actually moved position, add the command and fire the changed // event handler. - if (oldNextSibling != t.nextSibling) { + if (oldNextSibling !== t.nextSibling) { addCommandToHistory(new svgedit.history.MoveElementCommand(t, oldNextSibling, oldParent, 'Move ' + dir)); call('changed', [t]); } @@ -6877,12 +6833,12 @@ this.moveUpDownSelected = function(dir) { // // Returns: // Batch command for the move -this.moveSelectedElements = function(dx, dy, undoable) { +this.moveSelectedElements = function (dx, dy, undoable) { // if undoable is not sent, default to true // if single values, scale them to the zoom - if (dx.constructor != Array) { - dx /= current_zoom; - dy /= current_zoom; + if (dx.constructor !== Array) { + dx /= currentZoom; + dy /= currentZoom; } undoable = undoable || true; var batchCmd = new svgedit.history.BatchCommand('position'); @@ -6890,28 +6846,28 @@ this.moveSelectedElements = function(dx, dy, undoable) { while (i--) { var selected = selectedElements[i]; if (selected != null) { -// if (i==0) -// selectedBBoxes[0] = svgedit.utilities.getBBox(selected); - -// var b = {}; -// for (var j in selectedBBoxes[i]) b[j] = selectedBBoxes[i][j]; -// selectedBBoxes[i] = b; + // if (i === 0) { + // selectedBBoxes[0] = svgedit.utilities.getBBox(selected); + // } + // var b = {}; + // for (var j in selectedBBoxes[i]) b[j] = selectedBBoxes[i][j]; + // selectedBBoxes[i] = b; var xform = svgroot.createSVGTransform(); var tlist = svgedit.transformlist.getTransformList(selected); // dx and dy could be arrays - if (dx.constructor == Array) { -// if (i==0) { -// selectedBBoxes[0].x += dx[0]; -// selectedBBoxes[0].y += dy[0]; -// } + if (dx.constructor === Array) { + // if (i === 0) { + // selectedBBoxes[0].x += dx[0]; + // selectedBBoxes[0].y += dy[0]; + // } xform.setTranslate(dx[i], dy[i]); } else { -// if (i==0) { -// selectedBBoxes[0].x += dx; -// selectedBBoxes[0].y += dy; -// } + // if (i === 0) { + // selectedBBoxes[0].x += dx; + // selectedBBoxes[0].y += dy; + // } xform.setTranslate(dx, dy); } @@ -6941,18 +6897,18 @@ this.moveSelectedElements = function(dx, dy, undoable) { // Function: cloneSelectedElements // Create deep DOM copies (clones) of all selected elements and move them slightly // from their originals -this.cloneSelectedElements = function(x, y) { +this.cloneSelectedElements = function (x, y) { var i, elem; var batchCmd = new svgedit.history.BatchCommand('Clone Elements'); // find all the elements selected (stop at first null) var len = selectedElements.length; - function sortfunction(a, b){ - return ($(b).index() - $(a).index()); //causes an array to be sorted numerically and ascending + function sortfunction (a, b) { + return ($(b).index() - $(a).index()); // causes an array to be sorted numerically and ascending } selectedElements.sort(sortfunction); for (i = 0; i < len; ++i) { elem = selectedElements[i]; - if (elem == null) {break;} + if (elem == null) { break; } } // use slice to quickly get the subset of elements we need var copiedElements = selectedElements.slice(0, i); @@ -6964,7 +6920,7 @@ this.cloneSelectedElements = function(x, y) { while (i--) { // clone each element and replace it within copiedElements elem = copiedElements[i] = drawing.copyElem(copiedElements[i]); - (current_group || drawing.getCurrentLayer()).appendChild(elem); + (currentGroup || drawing.getCurrentLayer()).appendChild(elem); batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(elem)); } @@ -6980,25 +6936,28 @@ this.cloneSelectedElements = function(x, y) { // // Parameters: // type - String with single character indicating the alignment type -// relative_to - String that must be one of the following: +// relativeTo - String that must be one of the following: // "selected", "largest", "smallest", "page" -this.alignSelectedElements = function (type, relative_to) { +this.alignSelectedElements = function (type, relativeTo) { var i, elem; - var bboxes = [], angles = []; + var bboxes = []; // angles = []; var minx = Number.MAX_VALUE, maxx = Number.MIN_VALUE, miny = Number.MAX_VALUE, maxy = Number.MIN_VALUE; var curwidth = Number.MIN_VALUE, curheight = Number.MIN_VALUE; var len = selectedElements.length; - if (!len) {return;} + if (!len) { return; } for (i = 0; i < len; ++i) { - if (selectedElements[i] == null) {break;} + if (selectedElements[i] == null) { break; } elem = selectedElements[i]; bboxes[i] = getStrokedBBox([elem]); // now bbox is axis-aligned and handles rotation - switch (relative_to) { + switch (relativeTo) { case 'smallest': - if ( (type == 'l' || type == 'c' || type == 'r') && (curwidth == Number.MIN_VALUE || curwidth > bboxes[i].width) || - (type == 't' || type == 'm' || type == 'b') && (curheight == Number.MIN_VALUE || curheight > bboxes[i].height) ) { + if (((type === 'l' || type === 'c' || type === 'r') && + (curwidth === Number.MIN_VALUE || curwidth > bboxes[i].width)) || + ((type === 't' || type === 'm' || type === 'b') && + (curheight === Number.MIN_VALUE || curheight > bboxes[i].height)) + ) { minx = bboxes[i].x; miny = bboxes[i].y; maxx = bboxes[i].x + bboxes[i].width; @@ -7008,8 +6967,11 @@ this.alignSelectedElements = function (type, relative_to) { } break; case 'largest': - if ( (type == 'l' || type == 'c' || type == 'r') && (curwidth == Number.MIN_VALUE || curwidth < bboxes[i].width) || - (type == 't' || type == 'm' || type == 'b') && (curheight == Number.MIN_VALUE || curheight < bboxes[i].height) ) { + if (((type === 'l' || type === 'c' || type === 'r') && + (curwidth === Number.MIN_VALUE || curwidth < bboxes[i].width)) || + ((type === 't' || type === 'm' || type === 'b') && + (curheight === Number.MIN_VALUE || curheight < bboxes[i].height)) + ) { minx = bboxes[i].x; miny = bboxes[i].y; maxx = bboxes[i].x + bboxes[i].width; @@ -7019,15 +6981,15 @@ this.alignSelectedElements = function (type, relative_to) { } break; default: // 'selected' - if (bboxes[i].x < minx) {minx = bboxes[i].x;} - if (bboxes[i].y < miny) {miny = bboxes[i].y;} - if (bboxes[i].x + bboxes[i].width > maxx) {maxx = bboxes[i].x + bboxes[i].width;} - if (bboxes[i].y + bboxes[i].height > maxy) {maxy = bboxes[i].y + bboxes[i].height;} + if (bboxes[i].x < minx) { minx = bboxes[i].x; } + if (bboxes[i].y < miny) { miny = bboxes[i].y; } + if (bboxes[i].x + bboxes[i].width > maxx) { maxx = bboxes[i].x + bboxes[i].width; } + if (bboxes[i].y + bboxes[i].height > maxy) { maxy = bboxes[i].y + bboxes[i].height; } break; } } // loop for each element to find the bbox and adjust min/max - if (relative_to == 'page') { + if (relativeTo === 'page') { minx = 0; miny = 0; maxx = canvas.contentW; @@ -7037,7 +6999,7 @@ this.alignSelectedElements = function (type, relative_to) { var dx = new Array(len); var dy = new Array(len); for (i = 0; i < len; ++i) { - if (selectedElements[i] == null) {break;} + if (selectedElements[i] == null) { break; } elem = selectedElements[i]; var bbox = bboxes[i]; dx[i] = 0; @@ -7047,7 +7009,7 @@ this.alignSelectedElements = function (type, relative_to) { dx[i] = minx - bbox.x; break; case 'c': // center (horizontal) - dx[i] = (minx+maxx)/2 - (bbox.x + bbox.width/2); + dx[i] = (minx + maxx) / 2 - (bbox.x + bbox.width / 2); break; case 'r': // right (horizontal) dx[i] = maxx - (bbox.x + bbox.width); @@ -7056,7 +7018,7 @@ this.alignSelectedElements = function (type, relative_to) { dy[i] = miny - bbox.y; break; case 'm': // middle (vertical) - dy[i] = (miny+maxy)/2 - (bbox.y + bbox.height/2); + dy[i] = (miny + maxy) / 2 - (bbox.y + bbox.height / 2); break; case 'b': // bottom (vertical) dy[i] = maxy - (bbox.y + bbox.height); @@ -7082,25 +7044,25 @@ this.contentH = getResolution().h; // Object with the following values: // * x - The canvas' new x coordinate // * y - The canvas' new y coordinate -// * old_x - The canvas' old x coordinate -// * old_y - The canvas' old y coordinate +// * oldX - The canvas' old x coordinate +// * oldY - The canvas' old y coordinate // * d_x - The x position difference // * d_y - The y position difference this.updateCanvas = function (w, h) { svgroot.setAttribute('width', w); svgroot.setAttribute('height', h); var bg = $('#canvasBackground')[0]; - var old_x = svgcontent.getAttribute('x'); - var old_y = svgcontent.getAttribute('y'); - var x = (w/2 - this.contentW * current_zoom / 2); - var y = (h/2 - this.contentH * current_zoom / 2); + var oldX = svgcontent.getAttribute('x'); + var oldY = svgcontent.getAttribute('y'); + var x = (w / 2 - this.contentW * currentZoom / 2); + var y = (h / 2 - this.contentH * currentZoom / 2); svgedit.utilities.assignAttributes(svgcontent, { - width: this.contentW * current_zoom, - height: this.contentH * current_zoom, + width: this.contentW * currentZoom, + height: this.contentH * currentZoom, 'x': x, 'y': y, - 'viewBox' : '0 0 ' + this.contentW + ' ' + this.contentH + 'viewBox': '0 0 ' + this.contentW + ' ' + this.contentH }); svgedit.utilities.assignAttributes(bg, { @@ -7110,17 +7072,17 @@ this.updateCanvas = function (w, h) { y: y }); - var bg_img = svgedit.utilities.getElem('background_image'); - if (bg_img) { - svgedit.utilities.assignAttributes(bg_img, { + var bgImg = svgedit.utilities.getElem('background_image'); + if (bgImg) { + svgedit.utilities.assignAttributes(bgImg, { 'width': '100%', 'height': '100%' }); } selectorManager.selectorParentGroup.setAttribute('transform', 'translate(' + x + ',' + y + ')'); - runExtensions('canvasUpdated', {new_x:x, new_y:y, old_x:old_x, old_y:old_y, d_x:x - old_x, d_y:y - old_y}); - return {x:x, y:y, old_x:old_x, old_y:old_y, d_x:x - old_x, d_y:y - old_y}; + runExtensions('canvasUpdated', {new_x: x, new_y: y, old_x: oldX, old_y: oldY, d_x: x - oldX, d_y: y - oldY}); + return {x: x, y: y, old_x: oldX, old_y: oldY, d_x: x - oldX, d_y: y - oldY}; }; // Function: setBackground @@ -7129,26 +7091,26 @@ this.updateCanvas = function (w, h) { // Parameters: // color - String with fill color to apply // url - URL or path to image to use -this.setBackground = function(color, url) { +this.setBackground = function (color, url) { var bg = svgedit.utilities.getElem('canvasBackground'); var border = $(bg).find('rect')[0]; - var bg_img = svgedit.utilities.getElem('background_image'); + var bgImg = svgedit.utilities.getElem('background_image'); border.setAttribute('fill', color); if (url) { - if (!bg_img) { - bg_img = svgdoc.createElementNS(NS.SVG, 'image'); - svgedit.utilities.assignAttributes(bg_img, { + if (!bgImg) { + bgImg = svgdoc.createElementNS(NS.SVG, 'image'); + svgedit.utilities.assignAttributes(bgImg, { 'id': 'background_image', 'width': '100%', 'height': '100%', 'preserveAspectRatio': 'xMinYMin', - 'style':'pointer-events:none' + 'style': 'pointer-events:none' }); } - setHref(bg_img, url); - bg.appendChild(bg_img); - } else if (bg_img) { - bg_img.parentNode.removeChild(bg_img); + setHref(bgImg, url); + bg.appendChild(bgImg); + } else if (bgImg) { + bgImg.parentNode.removeChild(bgImg); } }; @@ -7157,26 +7119,26 @@ this.setBackground = function(color, url) { // // Parameters: // next - Boolean where true = next and false = previous element -this.cycleElement = function(next) { +this.cycleElement = function (next) { var num; - var cur_elem = selectedElements[0]; + var curElem = selectedElements[0]; var elem = false; - var all_elems = getVisibleElements(current_group || getCurrentDrawing().getCurrentLayer()); - if (!all_elems.length) { return; } - if (cur_elem == null) { - num = next ? all_elems.length - 1 : 0; - elem = all_elems[num]; + var allElems = getVisibleElements(currentGroup || getCurrentDrawing().getCurrentLayer()); + if (!allElems.length) { return; } + if (curElem == null) { + num = next ? allElems.length - 1 : 0; + elem = allElems[num]; } else { - var i = all_elems.length; + var i = allElems.length; while (i--) { - if (all_elems[i] == cur_elem) { + if (allElems[i] === curElem) { num = next ? i - 1 : i + 1; - if (num >= all_elems.length) { + if (num >= allElems.length) { num = 0; } else if (num < 0) { - num = all_elems.length-1; + num = allElems.length - 1; } - elem = all_elems[num]; + elem = allElems[num]; break; } } @@ -7187,14 +7149,13 @@ this.cycleElement = function(next) { this.clear(); - // DEPRECATED: getPrivateMethods // Since all methods are/should be public somehow, this function should be removed // Being able to access private methods publicly seems wrong somehow, // but currently appears to be the best way to allow testing and provide // access to them to plugins. -this.getPrivateMethods = function() { +this.getPrivateMethods = function () { var obj = { addCommandToHistory: addCommandToHistory, setGradient: setGradient, @@ -7203,7 +7164,7 @@ this.getPrivateMethods = function() { BatchCommand: BatchCommand, call: call, ChangeElementCommand: ChangeElementCommand, - copyElem: function(elem) {return getCurrentDrawing().copyElem(elem)}, + copyElem: function (elem) { return getCurrentDrawing().copyElem(elem); }, ffClone: ffClone, findDefs: findDefs, findDuplicateGradient: findDuplicateGradient, diff --git a/editor/svgtransformlist.js b/editor/svgtransformlist.js index fc0ce108..d9603a07 100644 --- a/editor/svgtransformlist.js +++ b/editor/svgtransformlist.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals $, svgedit */ /** * SVGTransformList @@ -33,7 +33,7 @@ function transformToString (xform) { text = 'translate(' + m.e + ',' + m.f + ')'; break; case 3: // SCALE - if (m.a == m.d) { + if (m.a === m.d) { text = 'scale(' + m.a + ')'; } else { text = 'scale(' + m.a + ',' + m.d + ')'; @@ -42,7 +42,7 @@ function transformToString (xform) { case 4: // ROTATE var cx = 0, cy = 0; // this prevents divide by zero - if (xform.angle != 0) { + if (xform.angle !== 0) { var K = 1 - m.a; cy = (K * m.f + m.b * m.e) / (K * K + m.b * m.b); cx = (m.e - m.b * cy) / K; @@ -114,19 +114,19 @@ svgedit.transformlist.SVGTransformList = function (elem) { var mtx = svgroot.createSVGMatrix(); $.each(valArr, function (i, item) { valArr[i] = parseFloat(item); - if (name == 'matrix') { + if (name === 'matrix') { mtx[letters[i]] = valArr[i]; } }); var xform = svgroot.createSVGTransform(); var fname = 'set' + name.charAt(0).toUpperCase() + name.slice(1); - var values = name == 'matrix' ? [mtx] : valArr; + var values = name === 'matrix' ? [mtx] : valArr; - if (name == 'scale' && values.length == 1) { + if (name === 'scale' && values.length === 1) { values.push(values[0]); - } else if (name == 'translate' && values.length == 1) { + } else if (name === 'translate' && values.length === 1) { values.push(0); - } else if (name == 'rotate' && values.length == 1) { + } else if (name === 'rotate' && values.length === 1) { values.push(0, 0); } xform[fname].apply(xform, values); @@ -144,7 +144,7 @@ svgedit.transformlist.SVGTransformList = function (elem) { var tl = listMap_[id]; var i, len; for (i = 0, len = tl._xforms.length; i < len; ++i) { - if (tl._xforms[i] == item) { + if (tl._xforms[i] === item) { found = true; tl.removeItem(i); break; diff --git a/editor/svgutils.js b/editor/svgutils.js index 7a982326..b5001e55 100644 --- a/editor/svgutils.js +++ b/editor/svgutils.js @@ -1,4 +1,4 @@ -/* eslint-disable no-var, eqeqeq */ +/* eslint-disable no-var */ /* globals $, svgedit, unescape, DOMParser, ActiveXObject, getStrokedBBox, RGBColor */ /** * Package: svgedit.utilities @@ -148,10 +148,10 @@ svgedit.utilities.decode64 = function (input) { output = output + String.fromCharCode(chr1); - if (enc3 != 64) { + if (enc3 !== 64) { output = output + String.fromCharCode(chr2); } - if (enc4 != 64) { + if (enc4 !== 64) { output = output + String.fromCharCode(chr3); } @@ -176,7 +176,7 @@ svgedit.utilities.encodeUTF8 = function (argString) { * @return {string} object URL or empty string */ svgedit.utilities.dataURLToObjectURL = function (dataurl) { - if (typeof Uint8Array == 'undefined' || typeof Blob == 'undefined' || typeof URL == 'undefined' || !URL.createObjectURL) { + if (typeof Uint8Array === 'undefined' || typeof Blob === 'undefined' || typeof URL === 'undefined' || !URL.createObjectURL) { return ''; } var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], @@ -194,7 +194,7 @@ svgedit.utilities.dataURLToObjectURL = function (dataurl) { * @return {string} object URL or empty string */ svgedit.utilities.createObjectURL = function (blob) { - if (!blob || typeof URL == 'undefined' || !URL.createObjectURL) { + if (!blob || typeof URL === 'undefined' || !URL.createObjectURL) { return ''; } return URL.createObjectURL(blob); @@ -204,7 +204,7 @@ svgedit.utilities.createObjectURL = function (blob) { * @property {string} blankPageObjectURL */ svgedit.utilities.blankPageObjectURL = (function () { - if (typeof Blob == 'undefined') { + if (typeof Blob === 'undefined') { return ''; } var blob = new Blob(['SVG-edit '], {type: 'text/html'}); @@ -293,7 +293,7 @@ svgedit.utilities.walkTree = function (elem, cbFn) { // elem - DOM element to traverse // cbFn - Callback function to run on each element svgedit.utilities.walkTreePost = function (elem, cbFn) { - if (elem && elem.nodeType == 1) { + if (elem && elem.nodeType === 1) { var i = elem.childNodes.length; while (i--) { svgedit.utilities.walkTree(elem.childNodes.item(i), cbFn); @@ -412,8 +412,8 @@ svgedit.utilities.getPathBBox = function (path) { var a = -3 * P0[j] + 9 * P1[j] - 9 * P2[j] + 3 * P3[j]; var c = 3 * P1[j] - 3 * P0[j]; - if (a == 0) { - if (b == 0) { + if (a === 0) { + if (b === 0) { continue; } var t = -c / b; @@ -611,7 +611,7 @@ svgedit.utilities.getPathDFromElement = function (elem) { var cx = a.cx, cy = a.cy; rx = a.rx; ry = a.ry; - if (elem.tagName == 'circle') { + if (elem.tagName === 'circle') { rx = ry = $(elem).attr('r'); } @@ -877,7 +877,7 @@ svgedit.utilities.getBBoxWithTransform = function (elem, addSvgElementFromJson, var elemNames = ['ellipse', 'path', 'line', 'polyline', 'polygon']; if (elemNames.indexOf(elem.tagName) >= 0) { bb = goodBb = svgedit.utilities.getBBoxOfElementAsPath(elem, addSvgElementFromJson, pathActions); - } else if (elem.tagName == 'rect') { + } else if (elem.tagName === 'rect') { // Look for radius var rx = elem.getAttribute('rx'); var ry = elem.getAttribute('ry'); @@ -912,7 +912,7 @@ svgedit.utilities.getBBoxWithTransform = function (elem, addSvgElementFromJson, // TODO: This is problematic with large stroke-width and, for example, a single horizontal line. The calculated BBox extends way beyond left and right sides. function getStrokeOffsetForBBox (elem) { var sw = elem.getAttribute('stroke-width'); - return (!isNaN(sw) && elem.getAttribute('stroke') != 'none') ? sw / 2 : 0; + return (!isNaN(sw) && elem.getAttribute('stroke') !== 'none') ? sw / 2 : 0; }; // Function: getStrokedBBox @@ -961,7 +961,7 @@ svgedit.utilities.getStrokedBBox = function (elems, addSvgElementFromJson, pathA minX = Math.min(minX, curBb.x - offset); minY = Math.min(minY, curBb.y - offset); // TODO: The old code had this test for max, but not min. I suspect this test should be for both min and max - if (elem.nodeType == 1) { + if (elem.nodeType === 1) { maxX = Math.max(maxX, curBb.x + curBb.width + offset); maxY = Math.max(maxY, curBb.y + curBb.height + offset); } @@ -991,7 +991,7 @@ svgedit.utilities.getRotationAngleFromTransformList = function (tlist, toRad) { var i; for (i = 0; i < N; ++i) { var xform = tlist.getItem(i); - if (xform.type == 4) { + if (xform.type === 4) { return toRad ? xform.angle * Math.PI / 180.0 : xform.angle; } } @@ -1104,7 +1104,7 @@ svgedit.utilities.cleanupElement = function (element) { var attr; for (attr in defaults) { var val = defaults[attr]; - if (element.getAttribute(attr) == val) { + if (element.getAttribute(attr) === String(val)) { element.removeAttribute(attr); } } @@ -1183,7 +1183,7 @@ svgedit.utilities.copyElem = function (el, getNextId) { // manually create a copy of the element var newEl = document.createElementNS(el.namespaceURI, el.nodeName); $.each(el.attributes, function (i, attr) { - if (attr.localName != '-moz-math-font-style') { + if (attr.localName !== '-moz-math-font-style') { newEl.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value); } }); @@ -1193,7 +1193,7 @@ svgedit.utilities.copyElem = function (el, getNextId) { // Opera's "d" value needs to be reset for Opera/Win/non-EN // Also needed for webkit (else does not keep curved segments on clone) - if (svgedit.browser.isWebkit() && el.nodeName == 'path') { + if (svgedit.browser.isWebkit() && el.nodeName === 'path') { var fixedD = svgedit.utilities.convertPath(el); newEl.setAttribute('d', fixedD); } @@ -1217,7 +1217,7 @@ svgedit.utilities.copyElem = function (el, getNextId) { } else if ($(el).data('symbol')) { var ref = $(el).data('symbol'); $(newEl).data('ref', ref).data('symbol', ref); - } else if (newEl.tagName == 'image') { + } else if (newEl.tagName === 'image') { svgedit.utilities.preventClickDefault(newEl); } diff --git a/editor/units.js b/editor/units.js index c7d85dfd..f78de469 100644 --- a/editor/units.js +++ b/editor/units.js @@ -106,7 +106,7 @@ svgedit.units.getTypeMap = function () { // // Returns: // If a string/number was given, returns a Float. If an array, return a string -// with comma-seperated floats +// with comma-separated floats svgedit.units.shortFloat = function (val) { var digits = elementContainer_.getRoundDigits(); if (!isNaN(val)) { diff --git a/extras/topo.py b/extras/topo.py index 592cbee8..368c277a 100644 --- a/extras/topo.py +++ b/extras/topo.py @@ -17,7 +17,7 @@ msgstr "" def printstr(flag, i, s): out.append('\n') if flag == '-x-svg-edit-both': - out.append("# Enter the title first, then the contents, seperated by a pipe char (|)\n") + out.append("# Enter the title first, then the contents, separated by a pipe char (|)\n") out.append("#, " + flag + '\n') out.append("msgid \"" + i + "\"" + '\n') out.append("msgstr \"" + s.replace('\n', '\\n') + "\"" + '\n') @@ -36,4 +36,4 @@ for line in infile: pass # The line wasn't really a string outfile.writelines(out) -outfile.close() \ No newline at end of file +outfile.close()