一大波更新

master
yutent 2024-03-06 18:36:03 +08:00
parent 6dc877e229
commit 4ae1ddd373
23 changed files with 5723 additions and 6520 deletions

View File

@ -1,66 +0,0 @@
#0.5.2
* pack fix
* transform into esm
#0.5.1
* Bug fix
#0.5.0
* Added color palettes for Material and FlatUI
* Added methods for gradients: `Element.stops()`, `Element.addStop()`, `Element.setStops()`
* Fixed matrix splitting for better animation of matrices`
* Various bug fixes
* Better integration of tests and ESlint
#0.4.1
* Bug fixes.
#0.4.0
* Moved class and element related code into separate plugins
* Added `Element.align()` and `Element.getAlign()` methods
* Added animation support for `viewBox`
* Added support for `<symbol>`
* Added method `Paper.toDataURL()`
* Added method `Snap.closest()`
* Added methods to work with degrees instead of radians: `Snap.sin()`, `Snap.cos()`, `Snap.tan()`, `Snap.asin()`, `Snap.acos()`, `Snap.atan()` and `Snap.atan2()`
* Added methods `Snap.len()`, `Snap.len2()` and `Snap.closestPoint()`
* Added methods `Element.children()` and `Element.toJSON()`
* Various bug fixes
#0.3.0
* Added `.addClass()`, `.removeClass()`, `.toggleClass()` and `.hasClass()` APIs
* Added `Paper.mask()`, `Paper.ptrn()`, `Paper.use()`, `Paper.svg()`
* Mask & pattern elements are sharing paper methods (just like group)
* Added `Set.bind()` method
* Added syncronisation for `Set.animate()`
* Added opacity to the shadow filter
* Added ability to specify attributes as `"+=10"` or `"-=1em"` or `"*=2"`
* Fix negative scale
* Fix for `path2curve`
* Fixed shared `<defs>` issue
* Various bug fixes
#0.2.0
* Added support for text path
* Added `getBBox` method to the paper object
* Added `Element.appendTo()` and `Element.prependTo()`
* Added `getElementByPoint()`
* Added `Set.remove()` method
* Get rid of internal SVG parser in favor of the browser
* Fix for `xlink:href` setting for images
* Fix `Element.animate()`
* Fix for animate and stroke-dashoffset
* Absolute transforms fix
* Fix for animation of SVG transformations, matrices and polygon points
* Various bug fixes
#0.1.0
* Initial release

View File

@ -11,17 +11,16 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper, Fragment } from './svg.js'
import { is } from './utils.js'
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var box = Snap._.box,
is = Snap.is,
let box = Snap._.box,
firstLetter = /^[^a-z]*([tbmlrc])/i,
toString = function () {
return 'T' + this.dx + ',' + this.dy
}
/*\
* Element.getAlign
* SnapElement.getAlign
[ method ]
**
* Returns shift needed to align the element relatively to given element.
@ -32,15 +31,15 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
> Usage
| el.transform(el.getAlign(el2, "top"));
* or
| var dy = el.getAlign(el2, "top").dy;
| let dy = el.getAlign(el2, "top").dy;
\*/
Element.prototype.getAlign = function (el, way) {
SnapElement.prototype.getAlign = function (el, way) {
if (way == null && is(el, 'string')) {
way = el
el = null
}
el = el || this.paper
var bx = el.getBBox ? el.getBBox() : box(el),
let bx = el.getBBox ? el.getBBox() : box(el),
bb = this.getBBox(),
out = {}
way = way && way.match(firstLetter)
@ -75,7 +74,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return out
}
/*\
* Element.align
* SnapElement.align
[ method ]
**
* Aligns the element relatively to given one via transformation.
@ -88,7 +87,6 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
* or
| el.align("middle");
\*/
Element.prototype.align = function (el, way) {
SnapElement.prototype.align = function (el, way) {
return this.transform('...' + this.getAlign(el, way))
}
})

View File

@ -13,24 +13,23 @@
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper, Fragment } from './svg.js'
import mina from './mina.js'
import { is } from './utils.js'
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var elproto = Element.prototype,
is = Snap.is,
let elproto = SnapElement.prototype,
Str = String,
has = 'hasOwnProperty'
function slice(from, to, f) {
return function (arr) {
var res = arr.slice(from, to)
let res = arr.slice(from, to)
if (res.length == 1) {
res = res[0]
}
return f ? f(res) : res
}
}
var Animation = function (attr, ms, easing, callback) {
let Animation = function (attr, ms, easing, callback) {
if (typeof easing == 'function' && !easing.length) {
callback = easing
easing = mina.linear
@ -57,7 +56,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return new Animation(attr, ms, easing, callback)
}
/*\
* Element.inAnim
* SnapElement.inAnim
[ method ]
**
* Returns a set of animations that may be able to manipulate the current element
@ -72,9 +71,9 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
o }
\*/
elproto.inAnim = function () {
var el = this,
let el = this,
res = []
for (var id in el.anims)
for (let id in el.anims)
if (el.anims[has](id)) {
;(function (a) {
res.push({
@ -113,7 +112,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
o status (function) gets or sets the status of the animation,
o stop (function) stops the animation
o }
| var rect = Snap().rect(0, 0, 10, 10);
| let rect = new Snap().rect(0, 0, 10, 10);
| Snap.animate(0, 10, function (val) {
| rect.attr({
| x: val
@ -127,28 +126,28 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
callback = easing
easing = mina.linear
}
var now = mina.time(),
let now = mina.time(),
anim = mina(from, to, now, now + ms, mina.time, setter, easing)
callback && eve.once('mina.finish.' + anim.id, callback)
return anim
}
/*\
* Element.stop
* SnapElement.stop
[ method ]
**
* Stops all the animations for the current element
**
= (Element) the current element
= (SnapElement) the current element
\*/
elproto.stop = function () {
var anims = this.inAnim()
for (var i = 0, ii = anims.length; i < ii; i++) {
let anims = this.inAnim()
for (let i = 0, ii = anims.length; i < ii; i++) {
anims[i].stop()
}
return this
}
/*\
* Element.animate
* SnapElement.animate
[ method ]
**
* Animates the given attributes of the element
@ -157,7 +156,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
- duration (number) duration of the animation in milliseconds
- easing (function) #optional easing function from @mina or custom
- callback (function) #optional callback function that executes when the animation ends
= (Element) the current element
= (SnapElement) the current element
\*/
elproto.animate = function (attrs, ms, easing, callback) {
if (typeof easing == 'function' && !easing.length) {
@ -170,7 +169,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
ms = attrs.dur
attrs = attrs.attr
}
var fkeys = [],
let fkeys = [],
tkeys = [],
keys = {},
from,
@ -178,7 +177,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
f,
eq,
el = this
for (var key in attrs)
for (let key in attrs)
if (attrs[has](key)) {
if (el.equal) {
eq = el.equal(key, Str(attrs[key]))
@ -189,12 +188,12 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
from = +el.attr(key)
to = +attrs[key]
}
var len = is(from, 'array') ? from.length : 1
let len = is(from, 'array') ? from.length : 1
keys[key] = slice(fkeys.length, fkeys.length + len, f)
fkeys = fkeys.concat(from)
tkeys = tkeys.concat(to)
}
var now = mina.time(),
let now = mina.time(),
anim = mina(
fkeys,
tkeys,
@ -202,8 +201,8 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
now + ms,
mina.time,
function (val) {
var attr = {}
for (var key in keys)
let attr = {}
for (let key in keys)
if (keys[has](key)) {
attr[key] = keys[key](val)
}
@ -226,4 +225,3 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
})
return el
}
})

View File

@ -12,19 +12,14 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper, Fragment, getSomeDefs } from './svg.js'
import { $, is, url } from './utils.js'
import { doc, win, SEPARATOR } from './lib/constants.js'
import { parseColor } from './lib/color.js'
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var has = 'hasOwnProperty',
make = Snap._.make,
wrap = Snap._.wrap,
is = Snap.is,
getSomeDefs = Snap._.getSomeDefs,
let has = 'hasOwnProperty',
reURLValue = /^url\((['"]?)([^)]+)\1\)$/,
$ = Snap._.$,
URL = Snap.url,
Str = String,
separator = Snap._.separator,
E = ''
/*\
* Snap.deurl
@ -35,12 +30,12 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
= (string) unwrapped path
\*/
Snap.deurl = function (value) {
var res = String(value).match(reURLValue)
let res = String(value).match(reURLValue)
return res ? res[2] : value
}
// Attributes event handlers
eve.on('snap.util.attr.mask', function (value) {
if (value instanceof Element || value instanceof Fragment) {
if (value instanceof SnapElement || value instanceof Fragment) {
eve.stop()
if (value instanceof Fragment && value.node.childNodes.length == 1) {
value = value.node.firstChild
@ -48,7 +43,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
value = wrap(value)
}
if (value.type == 'mask') {
var mask = value
let mask = value
} else {
mask = make('mask', getSomeDefs(this))
mask.node.appendChild(value.node)
@ -58,7 +53,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
id: mask.id
})
$(this.node, {
mask: URL(mask.id)
mask: url(mask.id)
})
}
})
@ -67,13 +62,13 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
eve.on('snap.util.attr.clip-path', clipIt)
eve.on('snap.util.attr.clipPath', clipIt)
})(function (value) {
if (value instanceof Element || value instanceof Fragment) {
if (value instanceof SnapElement || value instanceof Fragment) {
eve.stop()
var clip,
let clip,
node = value.node
while (node) {
if (node.nodeName === 'clipPath') {
clip = new Element(node)
clip = new SnapElement(node)
break
}
if (node.nodeName === 'svg') {
@ -91,13 +86,14 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
})
}
$(this.node, {
'clip-path': URL(clip.node.id || clip.id)
'clip-path': url(clip.node.id || clip.id)
})
}
})
function fillStroke(name) {
return function (value) {
eve.stop()
let fill
if (
value instanceof Fragment &&
value.node.childNodes.length == 1 &&
@ -109,7 +105,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
getSomeDefs(this).appendChild(value)
value = wrap(value)
}
if (value instanceof Element) {
if (value instanceof SnapElement) {
if (
value.type == 'radialGradient' ||
value.type == 'linearGradient' ||
@ -120,21 +116,21 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
id: value.id
})
}
var fill = URL(value.node.id)
fill = url(value.node.id)
} else {
fill = value.attr(name)
}
} else {
fill = Snap.color(value)
fill = parseColor(value)
if (fill.error) {
var grad = Snap(getSomeDefs(this).ownerSVGElement).gradient(value)
let grad = new Snap(getSomeDefs(this).ownerSVGElement).gradient(value)
if (grad) {
if (!grad.node.id) {
$(grad.node, {
id: grad.id
})
}
fill = URL(grad.node.id)
fill = url(grad.node.id)
} else {
fill = value
}
@ -142,7 +138,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
fill = Str(fill)
}
}
var attrs = {}
let attrs = {}
attrs[name] = fill
$(this.node, attrs)
this.node.style[name] = E
@ -150,14 +146,14 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
eve.on('snap.util.attr.fill', fillStroke('fill'))
eve.on('snap.util.attr.stroke', fillStroke('stroke'))
var gradrg = /^([lr])(?:\(([^)]*)\))?(.*)$/i
let gradrg = /^([lr])(?:\(([^)]*)\))?(.*)$/i
eve.on('snap.util.grad.parse', function parseGrad(string) {
string = Str(string)
var tokens = string.match(gradrg)
let tokens = string.match(gradrg)
if (!tokens) {
return null
}
var type = tokens[1],
let type = tokens[1],
params = tokens[2],
stops = tokens[3]
params = params.split(/\s*,\s*/).map(function (el) {
@ -169,7 +165,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
stops = stops.split('-')
stops = stops.map(function (el) {
el = el.split(':')
var out = {
let out = {
color: el[0]
}
if (el[1]) {
@ -177,19 +173,19 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
return out
})
var len = stops.length,
let len = stops.length,
start = 0,
j = 0
function seed(i, end) {
var step = (end - start) / (i - j)
for (var k = j; k < i; k++) {
let step = (end - start) / (i - j)
for (let k = j; k < i; k++) {
stops[k].offset = +(+start + step * (k - j)).toFixed(2)
}
j = i
start = end
}
len--
for (var i = 0; i < len; i++)
for (let i = 0; i < len; i++)
if ('offset' in stops[i]) {
seed(i, stops[i].offset)
}
@ -216,7 +212,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
eve.on('snap.util.attr.#text', function (value) {
eve.stop()
value = Str(value)
var txt = glob.doc.createTextNode(value)
let txt = doc.createTextNode(value)
while (this.node.firstChild) {
this.node.removeChild(this.node.firstChild)
}
@ -231,7 +227,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
this.node.className.baseVal = value
})(-1)
eve.on('snap.util.attr.viewBox', function (value) {
var vb
let vb
if (is(value, 'object') && 'x' in value) {
vb = [value.x, value.y, value.width, value.height].join(' ')
} else if (is(value, 'array')) {
@ -260,7 +256,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
eve.on('snap.util.attr.textpath', function (value) {
eve.stop()
if (this.type == 'text') {
var id, tp, node
let id, tp, node
if (!value && this.textPath) {
tp = this.textPath
while (tp.node.firstChild) {
@ -271,14 +267,14 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return
}
if (is(value, 'string')) {
var defs = getSomeDefs(this),
let defs = getSomeDefs(this),
path = wrap(defs.parentNode).path(value)
defs.appendChild(path.node)
id = path.id
path.attr({ id: id })
} else {
value = wrap(value)
if (value instanceof Element) {
if (value instanceof SnapElement) {
id = value.attr('id')
if (!id) {
id = value.id
@ -306,16 +302,16 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
})(-1)
eve.on('snap.util.attr.text', function (value) {
if (this.type == 'text') {
var i = 0,
let i = 0,
node = this.node,
tuner = function (chunk) {
var out = $('tspan')
let out = $('tspan')
if (is(chunk, 'array')) {
for (var i = 0; i < chunk.length; i++) {
for (let i = 0; i < chunk.length; i++) {
out.appendChild(tuner(chunk[i]))
}
} else {
out.appendChild(glob.doc.createTextNode(chunk))
out.appendChild(doc.createTextNode(chunk))
}
out.normalize && out.normalize()
return out
@ -323,7 +319,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
while (node.firstChild) {
node.removeChild(node.firstChild)
}
var tuned = tuner(value)
let tuned = tuner(value)
while (tuned.firstChild) {
node.appendChild(tuned.firstChild)
}
@ -353,30 +349,30 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
function getter(end) {
return function () {
eve.stop()
var style = glob.doc.defaultView
let style = doc.defaultView
.getComputedStyle(this.node, null)
.getPropertyValue('marker-' + end)
if (style == 'none') {
return style
} else {
return Snap(glob.doc.getElementById(style.match(reURLValue)[1]))
return new Snap(doc.getElementById(style.match(reURLValue)[1]))
}
}
}
function setter(end) {
return function (value) {
eve.stop()
var name = 'marker' + end.charAt(0).toUpperCase() + end.substring(1)
let name = 'marker' + end.charAt(0).toUpperCase() + end.substring(1)
if (value == '' || !value) {
this.node.style[name] = 'none'
return
}
if (value.type == 'marker') {
var id = value.node.id
let id = value.node.id
if (!id) {
$(value.node, { id: value.id })
}
this.node.style[name] = URL(id)
this.node.style[name] = url(id)
return
}
}
@ -401,10 +397,10 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
})(-1)
function textExtract(node) {
var out = []
var children = node.childNodes
for (var i = 0, ii = children.length; i < ii; i++) {
var chi = children[i]
let out = []
let children = node.childNodes
for (let i = 0, ii = children.length; i < ii; i++) {
let chi = children[i]
if (chi.nodeType == 3) {
out.push(chi.nodeValue)
}
@ -421,7 +417,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
eve.on('snap.util.getattr.text', function () {
if (this.type == 'text' || this.type == 'tspan') {
eve.stop()
var out = textExtract(this.node)
let out = textExtract(this.node)
return out.length == 1 ? out[0] : out
}
})(-1)
@ -433,38 +429,38 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return
}
eve.stop()
var value = eve('snap.util.getattr.fill', this, true).firstDefined()
return Snap(Snap.deurl(value)) || value
let value = eve('snap.util.getattr.fill', this, true).firstDefined()
return new Snap(Snap.deurl(value)) || value
})(-1)
eve.on('snap.util.getattr.stroke', function (internal) {
if (internal) {
return
}
eve.stop()
var value = eve('snap.util.getattr.stroke', this, true).firstDefined()
return Snap(Snap.deurl(value)) || value
let value = eve('snap.util.getattr.stroke', this, true).firstDefined()
return new Snap(Snap.deurl(value)) || value
})(-1)
eve.on('snap.util.getattr.viewBox', function () {
eve.stop()
var vb = $(this.node, 'viewBox')
let vb = $(this.node, 'viewBox')
if (vb) {
vb = vb.split(separator)
vb = vb.split(SEPARATOR)
return Snap._.box(+vb[0], +vb[1], +vb[2], +vb[3])
} else {
return
}
})(-1)
eve.on('snap.util.getattr.points', function () {
var p = $(this.node, 'points')
let p = $(this.node, 'points')
eve.stop()
if (p) {
return p.split(separator)
return p.split(SEPARATOR)
} else {
return
}
})(-1)
eve.on('snap.util.getattr.path', function () {
var p = $(this.node, 'd')
let p = $(this.node, 'd')
eve.stop()
return p
})(-1)
@ -477,4 +473,3 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
eve.on('snap.util.getattr.fontSize', getFontSize)(-1)
eve.on('snap.util.getattr.font-size', getFontSize)(-1)
})

View File

@ -12,10 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper, Fragment } from './svg.js'
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var operators = {
let operators = {
'+': function (x, y) {
return x + y
},
@ -41,14 +40,14 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
}
eve.on('snap.util.attr', function (val) {
var plus = Str(val).match(reAddon)
let plus = Str(val).match(reAddon)
if (plus) {
var evnt = eve.nt(),
let evnt = eve.nt(),
name = evnt.substring(evnt.lastIndexOf('.') + 1),
a = this.attr(name),
atr = {}
eve.stop()
var unit = plus[3] || '',
let unit = plus[3] || '',
aUnit = a.match(reUnit),
op = operators[plus[1]]
if (aUnit && aUnit == unit) {
@ -65,14 +64,14 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
})(-10)
eve.on('snap.util.equal', function (name, b) {
var A,
let A,
B,
a = Str(this.attr(name) || ''),
el = this,
bplus = Str(b).match(reAddon)
if (bplus) {
eve.stop()
var unit = bplus[3] || '',
let unit = bplus[3] || '',
aUnit = a.match(reUnit),
op = operators[bplus[1]]
if (aUnit && aUnit == unit) {
@ -91,4 +90,3 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
}
})(-10)
})

View File

@ -1,34 +1,26 @@
// Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Snap } from './svg.js'
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var rgNotSpace = /\S+/g,
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2024/03/06 16:34:24
*/
import { Snap, SnapElement, Paper, Fragment } from './svg.js'
let rgNotSpace = /\S+/g,
rgBadSpace = /[\t\r\n\f]/g,
rgTrim = /(^\s+|\s+$)/g,
Str = String,
elproto = Element.prototype
elproto = SnapElement.prototype
/*\
* Element.addClass
[ method ]
**
* Adds given class name or list of class names to the element.
- value (string) class name or space separated list of class names
**
= (Element) original element.
= (SnapElement) original element.
\*/
elproto.addClass = function (value) {
var classes = Str(value || '').match(rgNotSpace) || [],
let classes = Str(value || '').match(rgNotSpace) || [],
elem = this.node,
className = elem.className.baseVal,
curClasses = className.match(rgNotSpace) || [],
@ -54,16 +46,15 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.removeClass
[ method ]
**
* Removes given class name or list of class names from the element.
- value (string) class name or space separated list of class names
**
= (Element) original element.
= (SnapElement) original element.
\*/
elproto.removeClass = function (value) {
var classes = Str(value || '').match(rgNotSpace) || [],
let classes = Str(value || '').match(rgNotSpace) || [],
elem = this.node,
className = elem.className.baseVal,
curClasses = className.match(rgNotSpace) || [],
@ -88,8 +79,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.hasClass
[ method ]
**
* Checks if the element has a given class name in the list of class names applied to it.
- value (string) class name
@ -97,21 +87,20 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
= (boolean) `true` if the element has given class
\*/
elproto.hasClass = function (value) {
var elem = this.node,
let elem = this.node,
className = elem.className.baseVal,
curClasses = className.match(rgNotSpace) || []
return !!~curClasses.indexOf(value)
}
/*\
* Element.toggleClass
[ method ]
**
* Add or remove one or more classes from the element, depending on either
* the classs presence or the value of the `flag` argument.
- value (string) class name or space separated list of class names
- flag (boolean) value to determine whether the class should be added or removed
**
= (Element) original element.
= (SnapElement) original element.
\*/
elproto.toggleClass = function (value, flag) {
if (flag != null) {
@ -121,7 +110,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this.removeClass(value)
}
}
var classes = (value || '').match(rgNotSpace) || [],
let classes = (value || '').match(rgNotSpace) || [],
elem = this.node,
className = elem.className.baseVal,
curClasses = className.match(rgNotSpace) || [],
@ -145,4 +134,3 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
return this
}
})

View File

@ -1,149 +0,0 @@
// Copyright (c) 2017 Adobe Systems Incorporated. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Snap } from './svg.js'
Snap.plugin(function (Snap, Element, Paper, glob) {
// Colours are from https://www.materialui.co
var red =
'#ffebee#ffcdd2#ef9a9a#e57373#ef5350#f44336#e53935#d32f2f#c62828#b71c1c#ff8a80#ff5252#ff1744#d50000',
pink =
'#FCE4EC#F8BBD0#F48FB1#F06292#EC407A#E91E63#D81B60#C2185B#AD1457#880E4F#FF80AB#FF4081#F50057#C51162',
purple =
'#F3E5F5#E1BEE7#CE93D8#BA68C8#AB47BC#9C27B0#8E24AA#7B1FA2#6A1B9A#4A148C#EA80FC#E040FB#D500F9#AA00FF',
deeppurple =
'#EDE7F6#D1C4E9#B39DDB#9575CD#7E57C2#673AB7#5E35B1#512DA8#4527A0#311B92#B388FF#7C4DFF#651FFF#6200EA',
indigo =
'#E8EAF6#C5CAE9#9FA8DA#7986CB#5C6BC0#3F51B5#3949AB#303F9F#283593#1A237E#8C9EFF#536DFE#3D5AFE#304FFE',
blue =
'#E3F2FD#BBDEFB#90CAF9#64B5F6#64B5F6#2196F3#1E88E5#1976D2#1565C0#0D47A1#82B1FF#448AFF#2979FF#2962FF',
lightblue =
'#E1F5FE#B3E5FC#81D4FA#4FC3F7#29B6F6#03A9F4#039BE5#0288D1#0277BD#01579B#80D8FF#40C4FF#00B0FF#0091EA',
cyan =
'#E0F7FA#B2EBF2#80DEEA#4DD0E1#26C6DA#00BCD4#00ACC1#0097A7#00838F#006064#84FFFF#18FFFF#00E5FF#00B8D4',
teal =
'#E0F2F1#B2DFDB#80CBC4#4DB6AC#26A69A#009688#00897B#00796B#00695C#004D40#A7FFEB#64FFDA#1DE9B6#00BFA5',
green =
'#E8F5E9#C8E6C9#A5D6A7#81C784#66BB6A#4CAF50#43A047#388E3C#2E7D32#1B5E20#B9F6CA#69F0AE#00E676#00C853',
lightgreen =
'#F1F8E9#DCEDC8#C5E1A5#AED581#9CCC65#8BC34A#7CB342#689F38#558B2F#33691E#CCFF90#B2FF59#76FF03#64DD17',
lime =
'#F9FBE7#F0F4C3#E6EE9C#DCE775#D4E157#CDDC39#C0CA33#AFB42B#9E9D24#827717#F4FF81#EEFF41#C6FF00#AEEA00',
yellow =
'#FFFDE7#FFF9C4#FFF59D#FFF176#FFEE58#FFEB3B#FDD835#FBC02D#F9A825#F57F17#FFFF8D#FFFF00#FFEA00#FFD600',
amber =
'#FFF8E1#FFECB3#FFE082#FFD54F#FFCA28#FFC107#FFB300#FFA000#FF8F00#FF6F00#FFE57F#FFD740#FFC400#FFAB00',
orange =
'#FFF3E0#FFE0B2#FFCC80#FFB74D#FFA726#FF9800#FB8C00#F57C00#EF6C00#E65100#FFD180#FFAB40#FF9100#FF6D00',
deeporange =
'#FBE9E7#FFCCBC#FFAB91#FF8A65#FF7043#FF5722#F4511E#E64A19#D84315#BF360C#FF9E80#FF6E40#FF3D00#DD2C00',
brown =
'#EFEBE9#D7CCC8#BCAAA4#A1887F#8D6E63#795548#6D4C41#5D4037#4E342E#3E2723',
grey =
'#FAFAFA#F5F5F5#EEEEEE#E0E0E0#BDBDBD#9E9E9E#757575#616161#424242#212121',
bluegrey =
'#ECEFF1#CFD8DC#B0BEC5#90A4AE#78909C#607D8B#546E7A#455A64#37474F#263238'
/*\
* Snap.mui
[ property ]
**
* Contain Material UI colours.
| Snap().rect(0, 0, 10, 10).attr({fill: Snap.mui.deeppurple, stroke: Snap.mui.amber[600]});
# For colour reference: <a href="https://www.materialui.co">https://www.materialui.co</a>.
\*/
Snap.mui = {}
/*\
* Snap.flat
[ property ]
**
* Contain Flat UI colours.
| Snap().rect(0, 0, 10, 10).attr({fill: Snap.flat.carrot, stroke: Snap.flat.wetasphalt});
# For colour reference: <a href="https://www.materialui.co">https://www.materialui.co</a>.
\*/
Snap.flat = {}
function saveColor(colors) {
colors = colors.split(/(?=#)/)
var color = new String(colors[5])
color[50] = colors[0]
color[100] = colors[1]
color[200] = colors[2]
color[300] = colors[3]
color[400] = colors[4]
color[500] = colors[5]
color[600] = colors[6]
color[700] = colors[7]
color[800] = colors[8]
color[900] = colors[9]
if (colors[10]) {
color.A100 = colors[10]
color.A200 = colors[11]
color.A400 = colors[12]
color.A700 = colors[13]
}
return color
}
Snap.mui.red = saveColor(red)
Snap.mui.pink = saveColor(pink)
Snap.mui.purple = saveColor(purple)
Snap.mui.deeppurple = saveColor(deeppurple)
Snap.mui.indigo = saveColor(indigo)
Snap.mui.blue = saveColor(blue)
Snap.mui.lightblue = saveColor(lightblue)
Snap.mui.cyan = saveColor(cyan)
Snap.mui.teal = saveColor(teal)
Snap.mui.green = saveColor(green)
Snap.mui.lightgreen = saveColor(lightgreen)
Snap.mui.lime = saveColor(lime)
Snap.mui.yellow = saveColor(yellow)
Snap.mui.amber = saveColor(amber)
Snap.mui.orange = saveColor(orange)
Snap.mui.deeporange = saveColor(deeporange)
Snap.mui.brown = saveColor(brown)
Snap.mui.grey = saveColor(grey)
Snap.mui.bluegrey = saveColor(bluegrey)
Snap.flat.turquoise = '#1abc9c'
Snap.flat.greensea = '#16a085'
Snap.flat.sunflower = '#f1c40f'
Snap.flat.orange = '#f39c12'
Snap.flat.emerland = '#2ecc71'
Snap.flat.nephritis = '#27ae60'
Snap.flat.carrot = '#e67e22'
Snap.flat.pumpkin = '#d35400'
Snap.flat.peterriver = '#3498db'
Snap.flat.belizehole = '#2980b9'
Snap.flat.alizarin = '#e74c3c'
Snap.flat.pomegranate = '#c0392b'
Snap.flat.amethyst = '#9b59b6'
Snap.flat.wisteria = '#8e44ad'
Snap.flat.clouds = '#ecf0f1'
Snap.flat.silver = '#bdc3c7'
Snap.flat.wetasphalt = '#34495e'
Snap.flat.midnightblue = '#2c3e50'
Snap.flat.concrete = '#95a5a6'
Snap.flat.asbestos = '#7f8c8d'
/*\
* Snap.importMUIColors
[ method ]
**
* Imports Material UI colours into global object.
| Snap.importMUIColors();
| Snap().rect(0, 0, 10, 10).attr({fill: deeppurple, stroke: amber[600]});
# For colour reference: <a href="https://www.materialui.co">https://www.materialui.co</a>.
\*/
Snap.importMUIColors = function () {
for (var color in Snap.mui) {
if (Snap.mui.hasOwnProperty(color)) {
window[color] = Snap.mui[color]
}
}
}
})

View File

@ -12,21 +12,23 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import {
Snap,
SnapElement,
Paper,
Fragment,
getSomeDefs,
make,
wrap,
unit2px
} from './svg.js'
import { $, is } from './utils.js'
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var elproto = Element.prototype,
is = Snap.is,
let elproto = SnapElement.prototype,
Str = String,
unit2px = Snap._unit2px,
$ = Snap._.$,
make = Snap._.make,
getSomeDefs = Snap._.getSomeDefs,
has = 'hasOwnProperty',
wrap = Snap._.wrap
has = 'hasOwnProperty'
/*\
* Element.getBBox
[ method ]
**
* Returns the bounding box descriptor for the given element
**
@ -56,7 +58,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
if (!Snap.Matrix || !Snap.path) {
return this.node.getBBox()
}
var el = this,
let el = this,
m = new Snap.Matrix()
if (el.removed) {
return Snap._.box()
@ -72,13 +74,13 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
if (el.original) {
el = el.original
} else {
var href = el.attr('xlink:href')
let href = el.attr('xlink:href')
el = el.original = el.node.ownerDocument.getElementById(
href.substring(href.indexOf('#') + 1)
)
}
}
var _ = el._,
let _ = el._,
pathfinder = Snap.path.get[el.type] || Snap.path.get.deflt
try {
if (isWithoutTransform) {
@ -97,12 +99,13 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return Snap._.box()
}
}
var propString = function () {
let propString = function () {
return this.string
}
function extractTransform(el, tstr) {
let doReturn
if (tstr == null) {
var doReturn = true
doReturn = true
if (el.type == 'linearGradient' || el.type == 'radialGradient') {
tstr = el.node.getAttribute('gradientTransform')
} else if (el.type == 'pattern') {
@ -125,7 +128,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
el._.transform = tstr
}
var m = Snap._.transform2matrix(tstr, el.getBBox(1))
let m = Snap._.transform2matrix(tstr, el.getBBox(1))
if (doReturn) {
return m
} else {
@ -133,13 +136,13 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
}
/*\
* Element.transform
* SnapElement.transform
[ method ]
**
* Gets or sets transformation of the element
**
- tstr (string) transform string in Snap or SVG format
= (Element) the current element
= (SnapElement) the current element
* or
= (object) transformation descriptor:
o {
@ -153,9 +156,9 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
o }
\*/
elproto.transform = function (tstr) {
var _ = this._
let _ = this._
if (tstr == null) {
var papa = this,
let papa = this,
global = new Snap.Matrix(this.node.getCTM()),
local = extractTransform(this),
ms = [local],
@ -202,35 +205,35 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.parent
* SnapElement.parent
[ method ]
**
* Returns the element's parent
**
= (Element) the parent element
= (SnapElement) the parent element
\*/
elproto.parent = function () {
return wrap(this.node.parentNode)
}
/*\
* Element.append
* SnapElement.append
[ method ]
**
* Appends the given element to current one
**
- el (Element|Set) element to append
= (Element) the parent element
- el (SnapElement|Set) element to append
= (SnapElement) the parent element
\*/
/*\
* Element.add
* SnapElement.add
[ method ]
**
* See @Element.append
* See @SnapElement.append
\*/
elproto.append = elproto.add = function (el) {
if (el) {
if (el.type == 'set') {
var it = this
let it = this
el.forEach(function (el) {
it.add(el)
})
@ -243,13 +246,13 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.appendTo
* SnapElement.appendTo
[ method ]
**
* Appends the current element to the given one
**
- el (Element) parent element to append to
= (Element) the child element
- el (SnapElement) parent element to append to
= (SnapElement) the child element
\*/
elproto.appendTo = function (el) {
if (el) {
@ -259,18 +262,18 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.prepend
* SnapElement.prepend
[ method ]
**
* Prepends the given element to the current one
**
- el (Element) element to prepend
= (Element) the parent element
- el (SnapElement) element to prepend
= (SnapElement) the parent element
\*/
elproto.prepend = function (el) {
if (el) {
if (el.type == 'set') {
var it = this,
let it = this,
first
el.forEach(function (el) {
if (first) {
@ -283,7 +286,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
el = wrap(el)
var parent = el.parent()
let parent = el.parent()
this.node.insertBefore(el.node, this.node.firstChild)
this.add && this.add()
el.paper = this.paper
@ -293,13 +296,13 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.prependTo
* SnapElement.prependTo
[ method ]
**
* Prepends the current element to the given one
**
- el (Element) parent element to prepend to
= (Element) the child element
- el (SnapElement) parent element to prepend to
= (SnapElement) the child element
\*/
elproto.prependTo = function (el) {
el = wrap(el)
@ -307,19 +310,19 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.before
* SnapElement.before
[ method ]
**
* Inserts given element before the current one
**
- el (Element) element to insert
= (Element) the parent element
- el (SnapElement) element to insert
= (SnapElement) the parent element
\*/
elproto.before = function (el) {
if (el.type == 'set') {
var it = this
let it = this
el.forEach(function (el) {
var parent = el.parent()
let parent = el.parent()
it.node.parentNode.insertBefore(el.node, it.node)
parent && parent.add()
})
@ -327,7 +330,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
el = wrap(el)
var parent = el.parent()
let parent = el.parent()
this.node.parentNode.insertBefore(el.node, this.node)
this.parent() && this.parent().add()
parent && parent.add()
@ -335,17 +338,17 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.after
* SnapElement.after
[ method ]
**
* Inserts given element after the current one
**
- el (Element) element to insert
= (Element) the parent element
- el (SnapElement) element to insert
= (SnapElement) the parent element
\*/
elproto.after = function (el) {
el = wrap(el)
var parent = el.parent()
let parent = el.parent()
if (this.node.nextSibling) {
this.node.parentNode.insertBefore(el.node, this.node.nextSibling)
} else {
@ -357,17 +360,17 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.insertBefore
* SnapElement.insertBefore
[ method ]
**
* Inserts the element after the given one
**
- el (Element) element next to whom insert to
= (Element) the parent element
- el (SnapElement) element next to whom insert to
= (SnapElement) the parent element
\*/
elproto.insertBefore = function (el) {
el = wrap(el)
var parent = this.parent()
let parent = this.parent()
el.node.parentNode.insertBefore(this.node, el.node)
this.paper = el.paper
parent && parent.add()
@ -375,17 +378,17 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.insertAfter
* SnapElement.insertAfter
[ method ]
**
* Inserts the element after the given one
**
- el (Element) element next to whom insert to
= (Element) the parent element
- el (SnapElement) element next to whom insert to
= (SnapElement) the parent element
\*/
elproto.insertAfter = function (el) {
el = wrap(el)
var parent = this.parent()
let parent = this.parent()
el.node.parentNode.insertBefore(this.node, el.node.nextSibling)
this.paper = el.paper
parent && parent.add()
@ -393,14 +396,14 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.remove
* SnapElement.remove
[ method ]
**
* Removes element from the DOM
= (Element) the detached element
= (SnapElement) the detached element
\*/
elproto.remove = function () {
var parent = this.parent()
let parent = this.parent()
this.node.parentNode && this.node.parentNode.removeChild(this.node)
delete this.paper
this.removed = true
@ -408,43 +411,43 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.select
* SnapElement.select
[ method ]
**
* Gathers the nested @Element matching the given set of CSS selectors
* Gathers the nested @SnapElement matching the given set of CSS selectors
**
- query (string) CSS selector
= (Element) result of query selection
= (SnapElement) result of query selection
\*/
elproto.select = function (query) {
return wrap(this.node.querySelector(query))
}
/*\
* Element.selectAll
* SnapElement.selectAll
[ method ]
**
* Gathers nested @Element objects matching the given set of CSS selectors
* Gathers nested @SnapElement objects matching the given set of CSS selectors
**
- query (string) CSS selector
= (Set|array) result of query selection
\*/
elproto.selectAll = function (query) {
var nodelist = this.node.querySelectorAll(query),
let nodelist = this.node.querySelectorAll(query),
set = (Snap.set || Array)()
for (var i = 0; i < nodelist.length; i++) {
for (let i = 0; i < nodelist.length; i++) {
set.push(wrap(nodelist[i]))
}
return set
}
/*\
* Element.asPX
* SnapElement.asPX
[ method ]
**
* Returns given attribute of the element as a `px` value (not %, em, etc.)
**
- attr (string) attribute name
- value (string) #optional attribute value
= (Element) result of query selection
= (SnapElement) result of query selection
\*/
elproto.asPX = function (attr, value) {
if (value == null) {
@ -452,17 +455,17 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
return +unit2px(this, attr, value)
}
// SIERRA Element.use(): I suggest adding a note about how to access the original element the returned <use> instantiates. It's a part of SVG with which ordinary web developers may be least familiar.
// SIERRA SnapElement.use(): I suggest adding a note about how to access the original element the returned <use> instantiates. It's a part of SVG with which ordinary web developers may be least familiar.
/*\
* Element.use
* SnapElement.use
[ method ]
**
* Creates a `<use>` element linked to the current element
**
= (Element) the `<use>` element
= (SnapElement) the `<use>` element
\*/
elproto.use = function () {
var use,
let use,
id = this.node.id
if (!id) {
id = this.id
@ -486,13 +489,13 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return use
}
function fixids(el) {
var els = el.selectAll('*'),
let els = el.selectAll('*'),
it,
url = /^\s*url\(("|'|)(.*)\1\)\s*$/,
ids = [],
uses = {}
function urltest(it, name) {
var val = $(it.node, name)
let val = $(it.node, name)
val = val && val.match(url)
val = val && val[2]
if (val && val.charAt() == '#') {
@ -502,14 +505,14 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
if (val) {
uses[val] = (uses[val] || []).concat(function (id) {
var attr = {}
let attr = {}
attr[name] = Snap.url(id)
$(it.node, attr)
})
}
}
function linktest(it) {
var val = $(it.node, 'xlink:href')
let val = $(it.node, 'xlink:href')
if (val && val.charAt() == '#') {
val = val.substring(1)
} else {
@ -521,7 +524,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
})
}
}
for (var i = 0, ii = els.length; i < ii; i++) {
for (let i = 0, ii = els.length; i < ii; i++) {
it = els[i]
urltest(it, 'fill')
urltest(it, 'stroke')
@ -529,7 +532,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
urltest(it, 'mask')
urltest(it, 'clip-path')
linktest(it)
var oldid = $(it.node, 'id')
let oldid = $(it.node, 'id')
if (oldid) {
$(it.node, { id: it.id })
ids.push({
@ -539,24 +542,24 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
}
for (i = 0, ii = ids.length; i < ii; i++) {
var fs = uses[ids[i].old]
let fs = uses[ids[i].old]
if (fs) {
for (var j = 0, jj = fs.length; j < jj; j++) {
for (let j = 0, jj = fs.length; j < jj; j++) {
fs[j](ids[i].id)
}
}
}
}
/*\
* Element.clone
* SnapElement.clone
[ method ]
**
* Creates a clone of the element and inserts it after the element
**
= (Element) the clone
= (SnapElement) the clone
\*/
elproto.clone = function () {
var clone = wrap(this.node.cloneNode(true))
let clone = wrap(this.node.cloneNode(true))
if ($(clone.node, 'id')) {
$(clone.node, { id: clone.id })
}
@ -565,20 +568,20 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return clone
}
/*\
* Element.toDefs
* SnapElement.toDefs
[ method ]
**
* Moves element to the shared `<defs>` area
**
= (Element) the element
= (SnapElement) the element
\*/
elproto.toDefs = function () {
var defs = getSomeDefs(this)
let defs = getSomeDefs(this)
defs.appendChild(this.node)
return this
}
/*\
* Element.toPattern
* SnapElement.toPattern
[ method ]
**
* Creates a `<pattern>` element from the current element
@ -588,9 +591,9 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
- y (string|number)
- width (string|number)
- height (string|number)
= (Element) the `<pattern>` element
= (SnapElement) the `<pattern>` element
* You can use pattern later on as an argument for `fill` attribute:
| var p = paper.path("M10-5-10,15M15,0,0,15M0-5-20,15").attr({
| let p = paper.path("M10-5-10,15M15,0,0,15M0-5-20,15").attr({
| fill: "none",
| stroke: "#bada55",
| strokeWidth: 5
@ -601,7 +604,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
| });
\*/
elproto.pattern = elproto.toPattern = function (x, y, width, height) {
var p = make('pattern', getSomeDefs(this))
let p = make('pattern', getSomeDefs(this))
if (x == null) {
x = this.getBBox()
}
@ -623,10 +626,10 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
p.node.appendChild(this.node)
return p
}
// SIERRA Element.marker(): clarify what a reference point is. E.g., helps you offset the object from its edge such as when centering it over a path.
// SIERRA Element.marker(): I suggest the method should accept default reference point values. Perhaps centered with (refX = width/2) and (refY = height/2)? Also, couldn't it assume the element's current _width_ and _height_? And please specify what _x_ and _y_ mean: offsets? If so, from where? Couldn't they also be assigned default values?
// SIERRA SnapElement.marker(): clarify what a reference point is. E.g., helps you offset the object from its edge such as when centering it over a path.
// SIERRA SnapElement.marker(): I suggest the method should accept default reference point values. Perhaps centered with (refX = width/2) and (refY = height/2)? Also, couldn't it assume the element's current _width_ and _height_? And please specify what _x_ and _y_ mean: offsets? If so, from where? Couldn't they also be assigned default values?
/*\
* Element.marker
* SnapElement.marker
[ method ]
**
* Creates a `<marker>` element from the current element
@ -638,12 +641,12 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
- height (number)
- refX (number)
- refY (number)
= (Element) the `<marker>` element
= (SnapElement) the `<marker>` element
* You can specify the marker later as an argument for `marker-start`, `marker-end`, `marker-mid`, and `marker` attributes. The `marker` attribute places the marker at every point along the path, and `marker-mid` places them at every point except the start and end.
\*/
// TODO add usage for markers
elproto.marker = function (x, y, width, height, refX, refY) {
var p = make('marker', getSomeDefs(this))
let p = make('marker', getSomeDefs(this))
if (x == null) {
x = this.getBBox()
}
@ -667,22 +670,22 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
p.node.appendChild(this.node)
return p
}
var eldata = {}
let eldata = {}
/*\
* Element.data
* SnapElement.data
[ method ]
**
* Adds or retrieves given value associated with given key. (Dont confuse
* with `data-` attributes)
*
* See also @Element.removeData
* See also @SnapElement.removeData
- key (string) key to store data
- value (any) #optional value to store
= (object) @Element
= (object) @SnapElement
* or, if value is not specified:
= (any) value
> Usage
| for (var i = 0, i < 5, i++) {
| for (let i = 0, i < 5, i++) {
| paper.circle(10 + 15 * i, 10, 10)
| .attr({fill: "#000"})
| .data("i", i)
@ -692,14 +695,14 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
| }
\*/
elproto.data = function (key, value) {
var data = (eldata[this.id] = eldata[this.id] || {})
let data = (eldata[this.id] = eldata[this.id] || {})
if (arguments.length == 0) {
eve('snap.data.get.' + this.id, this, data, null)
return data
}
if (arguments.length == 1) {
if (Snap.is(key, 'object')) {
for (var i in key)
if (is(key, 'object')) {
for (let i in key)
if (key[has](i)) {
this.data(i, key[i])
}
@ -713,13 +716,13 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.removeData
* SnapElement.removeData
[ method ]
**
* Removes value associated with an element by given key.
* If key is not provided, removes all the data of the element.
- key (string) #optional key
= (object) @Element
= (object) @SnapElement
\*/
elproto.removeData = function (key) {
if (key == null) {
@ -730,23 +733,23 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
/*\
* Element.outerSVG
* SnapElement.outerSVG
[ method ]
**
* Returns SVG code for the element, equivalent to HTML's `outerHTML`.
*
* See also @Element.innerSVG
* See also @SnapElement.innerSVG
= (string) SVG code for the element
\*/
/*\
* Element.toString
* SnapElement.toString
[ method ]
**
* See @Element.outerSVG
* See @SnapElement.outerSVG
\*/
elproto.outerSVG = elproto.toString = toString(1)
/*\
* Element.innerSVG
* SnapElement.innerSVG
[ method ]
**
* Returns SVG code for the element's contents, equivalent to HTML's `innerHTML`
@ -755,11 +758,11 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
elproto.innerSVG = toString()
function toString(type) {
return function () {
var res = type ? '<' + this.type : '',
let res = type ? '<' + this.type : '',
attr = this.node.attributes,
chld = this.node.childNodes
if (type) {
for (var i = 0, ii = attr.length; i < ii; i++) {
for (let i = 0, ii = attr.length; i < ii; i++) {
res +=
' ' + attr[i].name + '="' + attr[i].value.replace(/"/g, '\\"') + '"'
}
@ -781,35 +784,29 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
}
elproto.toDataURL = function () {
if (window && window.btoa) {
var bb = this.getBBox(),
svg = Snap.format(
'<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="{width}" height="{height}" viewBox="{x} {y} {width} {height}">{contents}</svg>',
{
let bb = this.getBBox()
let { x, y, width, height } = {
x: +bb.x.toFixed(3),
y: +bb.y.toFixed(3),
width: +bb.width.toFixed(3),
height: +bb.height.toFixed(3),
contents: this.outerSVG()
}
)
return (
'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)))
)
height: +bb.height.toFixed(3)
}
let contents = this.outerSVG()
let svg = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${width}" height="${height}" viewBox="${x} ${y} ${width} ${height}">${contents}</svg>`
return 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)))
}
/*\
* Fragment.select
[ method ]
**
* See @Element.select
* See @SnapElement.select
\*/
Fragment.prototype.select = elproto.select
/*\
* Fragment.selectAll
[ method ]
**
* See @Element.selectAll
* See @SnapElement.selectAll
\*/
Fragment.prototype.selectAll = elproto.selectAll
})

View File

@ -12,15 +12,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper, Fragment } from './svg.js'
import { is } from './utils.js'
import { SEPARATOR } from './lib/constants.js'
import { parseColor } from './lib/color.js'
Snap.plugin(function (Snap, Element, Paper, glob) {
var names = {},
let names = {},
reUnit = /[%a-z]+$/i,
Str = String
names.stroke = names.fill = 'colour'
function getEmpty(item) {
var l = item[0]
let l = item[0]
switch (l.toLowerCase()) {
case 't':
return [l, 0, 0]
@ -47,7 +49,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
t2 = t2 || new Snap.Matrix()
t1 = Snap.parseTransformString(t1.toTransformString()) || []
t2 = Snap.parseTransformString(t2.toTransformString()) || []
var maxlength = Math.max(t1.length, t2.length),
let maxlength = Math.max(t1.length, t2.length),
from = [],
to = [],
i = 0,
@ -60,8 +62,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
tt2 = t2[i] || getEmpty(tt1)
if (
tt1[0] != tt2[0] ||
(tt1[0].toLowerCase() == 'r' &&
(tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
(tt1[0].toLowerCase() == 'r' && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) ||
(tt1[0].toLowerCase() == 's' && (tt1[3] != tt2[3] || tt1[4] != tt2[4]))
) {
t1 = Snap._.transform2matrix(t1, getBBox())
@ -98,7 +99,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return Snap.rgb(clr[0], clr[1], clr[2], clr[3])
}
function getPath(path) {
var k = 0,
let k = 0,
i,
ii,
j,
@ -118,9 +119,9 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return Function('val', 'return Snap.path.toString.call([' + b + '])')
}
function path2array(path) {
var out = []
for (var i = 0, ii = path.length; i < ii; i++) {
for (var j = 1, jj = path[i].length; j < jj; j++) {
let out = []
for (let i = 0, ii = path.length; i < ii; i++) {
for (let j = 1, jj = path[i].length; j < jj; j++) {
out.push(path[i][j])
}
}
@ -130,22 +131,22 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return isFinite(obj)
}
function arrayEqual(arr1, arr2) {
if (!Snap.is(arr1, 'array') || !Snap.is(arr2, 'array')) {
if (!is(arr1, 'array') || !is(arr2, 'array')) {
return false
}
return arr1.toString() == arr2.toString()
}
Element.prototype.equal = function (name, b) {
SnapElement.prototype.equal = function (name, b) {
return eve('snap.util.equal', this, name, b).firstDefined()
}
eve.on('snap.util.equal', function (name, b) {
var A,
let A,
B,
a = Str(this.attr(name) || ''),
el = this
if (names[name] == 'colour') {
A = Snap.color(a)
B = Snap.color(b)
A = parseColor(a)
B = parseColor(b)
return {
from: [A.r, A.g, A.b, A.opacity],
to: [B.r, B.g, B.b, B.opacity],
@ -171,10 +172,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
a = this.matrix
if (!Snap._.rgTransform.test(b)) {
b = Snap._.transform2matrix(
Snap._.svgTransform2string(b),
this.getBBox()
)
b = Snap._.transform2matrix(Snap._.svgTransform2string(b), this.getBBox())
} else {
b = Snap._.transform2matrix(b, this.getBBox())
}
@ -191,8 +189,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
}
if (name == 'points') {
A = Str(a).split(Snap._.separator)
B = Str(b).split(Snap._.separator)
A = Str(a).split(SEPARATOR)
B = Str(b).split(SEPARATOR)
return {
from: A,
to: B,
@ -208,7 +206,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
f: getNumber
}
}
var aUnit = a.match(reUnit),
let aUnit = a.match(reUnit),
bUnit = Str(b).match(reUnit)
if (aUnit && arrayEqual(aUnit, bUnit)) {
return {
@ -224,4 +222,3 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
}
})
})

View File

@ -17,7 +17,7 @@
// │ Author Dmitry Baranovskiy (http://dmitry.baranovskiy.com/) │ \\
// └────────────────────────────────────────────────────────────┘ \\
var version = '0.5.4',
let version = '0.5.4',
has = 'hasOwnProperty',
separator = /[\.\/]/,
comaseparator = /\s*,\s*/,
@ -29,16 +29,16 @@ var version = '0.5.4',
stop,
events = { n: {} },
firstDefined = function () {
for (var i = 0, ii = this.length; i < ii; i++) {
if (typeof this[i] != 'undefined') {
for (let i = 0, ii = this.length; i < ii; i++) {
if (this[i] !== void 0) {
return this[i]
}
}
},
lastDefined = function () {
var i = this.length
let i = this.length
while (--i) {
if (typeof this[i] != 'undefined') {
if (this[i] !== void 0) {
return this[i]
}
}
@ -63,7 +63,7 @@ var version = '0.5.4',
= (object) array of returned values from the listeners. Array has two methods `.firstDefined()` and `.lastDefined()` to get first or last not `undefined` value.
\*/
eve = function (name, scope) {
var oldstop = stop,
let oldstop = stop,
args = Array.prototype.slice.call(arguments, 2),
listeners = eve.listeners(name),
z = 0,
@ -76,7 +76,7 @@ var version = '0.5.4',
out.lastDefined = lastDefined
current_event = name
stop = 0
for (var i = 0, ii = listeners.length; i < ii; i++)
for (let i = 0; i < listeners.length; i++)
if ('zIndex' in listeners[i]) {
indexed.push(listeners[i].zIndex)
if (listeners[i].zIndex < 0) {
@ -92,7 +92,7 @@ var version = '0.5.4',
return out
}
}
for (i = 0; i < ii; i++) {
for (let i = 0; i < listeners.length; i++) {
l = listeners[i]
if ('zIndex' in l) {
if (l.zIndex == indexed[z]) {
@ -135,7 +135,7 @@ eve._events = events
= (array) array of event handlers
\*/
eve.listeners = function (name) {
var names = isArray(name) ? name : name.split(separator),
let names = isArray(name) ? name : name.split(separator),
e = events,
item,
items,
@ -213,17 +213,17 @@ eve.on = function (name, f) {
if (typeof f != 'function') {
return function () {}
}
var names = isArray(name)
let names = isArray(name)
? isArray(name[0])
? name
: [name]
: Str(name).split(comaseparator)
for (var i = 0, ii = names.length; i < ii; i++) {
for (let i = 0, ii = names.length; i < ii; i++) {
;(function (name) {
var names = isArray(name) ? name : Str(name).split(separator),
let names = isArray(name) ? name : Str(name).split(separator),
e = events,
exist
for (var i = 0, ii = names.length; i < ii; i++) {
for (let i = 0, ii = names.length; i < ii; i++) {
e = e.n
e =
(e.hasOwnProperty(names[i]) && e[names[i]]) ||
@ -245,8 +245,6 @@ eve.on = function (name, f) {
}
}
/*\
* eve.f
[ method ]
**
* Returns function that will fire given event with optional arguments.
* Arguments that will be passed to the result function will be also
@ -259,18 +257,12 @@ eve.on = function (name, f) {
- varargs () and any other arguments
= (function) possible event handler function
\*/
eve.f = function (event) {
var attrs = [].slice.call(arguments, 1)
return function () {
eve.apply(
null,
[event, null].concat(attrs).concat([].slice.call(arguments, 0))
)
eve.f = function (event, ...attrs) {
return function (...args) {
eve.apply(null, [event, null].concat(attrs).concat(args))
}
}
/*\
* eve.stop
[ method ]
**
* Is used inside an event handler to stop the event, preventing any subsequent listeners from firing.
\*/
@ -290,7 +282,7 @@ eve.stop = function () {
= (boolean) `true`, if current events name contains `subname`
\*/
eve.nt = function (subname) {
var cur = isArray(current_event) ? current_event.join('.') : current_event
let cur = isArray(current_event) ? current_event.join('.') : current_event
if (subname) {
return new RegExp('(?:\\.|\\/|^)' + subname + '(?:\\.|\\/|$)').test(cur)
}
@ -329,19 +321,19 @@ eve.off = eve.unbind = function (name, f) {
eve._events = events = { n: {} }
return
}
var names = isArray(name)
let names = isArray(name)
? isArray(name[0])
? name
: [name]
: Str(name).split(comaseparator)
if (names.length > 1) {
for (var i = 0, ii = names.length; i < ii; i++) {
for (let i = 0, ii = names.length; i < ii; i++) {
eve.off(names[i], f)
}
return
}
names = isArray(name) ? name : Str(name).split(separator)
var e,
let e,
key,
splice,
i,
@ -389,7 +381,7 @@ eve.off = eve.unbind = function (name, f) {
}
for (key in e.n)
if (e.n[has](key) && e.n[key].f) {
var funcs = e.n[key].f
let funcs = e.n[key].f
for (j = 0, jj = funcs.length; j < jj; j++)
if (funcs[j] == f) {
funcs.splice(j, 1)
@ -438,21 +430,11 @@ eve.off = eve.unbind = function (name, f) {
= (function) same return function as @eve.on
\*/
eve.once = function (name, f) {
var f2 = function () {
let f2 = function () {
eve.off(name, f2)
return f.apply(this, arguments)
}
return eve.on(name, f2)
}
/*\
* eve.version
[ property (string) ]
**
* Current version of the library.
\*/
eve.version = version
eve.toString = function () {
return 'You are running Eve ' + version
}
export default eve

View File

@ -12,61 +12,28 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper, Fragment } from './svg.js'
import { $ } from './utils.js'
import { parseColor } from './lib/color.js'
Snap.plugin(function (Snap, Element, Paper, glob) {
var elproto = Element.prototype,
pproto = Paper.prototype,
let elproto = SnapElement.prototype,
rgurl = /^\s*url\((.+)\)/,
Str = String,
$ = Snap._.$
Str = String
Snap.filter = {}
/*\
* Paper.filter
[ method ]
**
* Creates a `<filter>` element
**
- filstr (string) SVG fragment of filter provided as a string
= (object) @Element
* Note: It is recommended to use filters embedded into the page inside an empty SVG element.
> Usage
| var f = paper.filter('<feGaussianBlur stdDeviation="2"/>'),
| c = paper.circle(10, 10, 10).attr({
| filter: f
| });
\*/
pproto.filter = function (filstr) {
var paper = this
if (paper.type != 'svg') {
paper = paper.paper
}
var f = Snap.parse(Str(filstr)),
id = Snap._.id(),
width = paper.node.offsetWidth,
height = paper.node.offsetHeight,
filter = $('filter')
$(filter, {
id: id,
filterUnits: 'userSpaceOnUse'
})
filter.appendChild(f.node)
paper.defs.appendChild(filter)
return new Element(filter)
}
eve.on('snap.util.getattr.filter', function () {
eve.stop()
var p = $(this.node, 'filter')
let p = $(this.node, 'filter')
if (p) {
var match = Str(p).match(rgurl)
let match = Str(p).match(rgurl)
return match && Snap.select(match[1])
}
})
eve.on('snap.util.attr.filter', function (value) {
if (value instanceof Element && value.type == 'filter') {
if (value instanceof SnapElement && value.type == 'filter') {
eve.stop()
var id = value.node.id
let id = value.node.id
if (!id) {
$(value.node, { id: value.id })
id = value.id
@ -90,7 +57,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
- y (number) #optional amount of vertical blur, in pixels
= (string) filter representation
> Usage
| var f = paper.filter(Snap.filter.blur(5, 10)),
| let f = paper.filter(Snap.filter.blur(5, 10)),
| c = paper.circle(10, 10, 10).attr({
| filter: f
| });
@ -99,10 +66,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (x == null) {
x = 2
}
var def = y == null ? x : [x, y]
return Snap.format('<feGaussianBlur stdDeviation="{def}"/>', {
def: def
})
let def = y == null ? x : [x, y]
return `<feGaussianBlur stdDeviation="${def}"/>`
}
Snap.filter.blur.toString = function () {
return this()
@ -129,7 +94,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
- opacity (number) #optional `0..1` opacity of the shadow
= (string) filter representation
> Usage
| var f = paper.filter(Snap.filter.shadow(0, 2, .3)),
| let f = paper.filter(Snap.filter.shadow(0, 2, .3)),
| c = paper.circle(10, 10, 10).attr({
| filter: f
| });
@ -159,17 +124,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (dy == null) {
dy = dx
}
color = Snap.color(color)
return Snap.format(
'<feGaussianBlur in="SourceAlpha" stdDeviation="{blur}"/><feOffset dx="{dx}" dy="{dy}" result="offsetblur"/><feFlood flood-color="{color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="{opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge>',
{
color: color,
dx: dx,
dy: dy,
blur: blur,
opacity: opacity
}
)
color = parseColor(color)
return `<feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge>`
}
Snap.filter.shadow.toString = function () {
return this()
@ -187,19 +143,17 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (amount == null) {
amount = 1
}
return Snap.format(
'<feColorMatrix type="matrix" values="{a} {b} {c} 0 0 {d} {e} {f} 0 0 {g} {b} {h} 0 0 0 0 0 1 0"/>',
{
a: 0.2126 + 0.7874 * (1 - amount),
b: 0.7152 - 0.7152 * (1 - amount),
c: 0.0722 - 0.0722 * (1 - amount),
d: 0.2126 - 0.2126 * (1 - amount),
e: 0.7152 + 0.2848 * (1 - amount),
f: 0.0722 - 0.0722 * (1 - amount),
g: 0.2126 - 0.2126 * (1 - amount),
h: 0.0722 + 0.9278 * (1 - amount)
}
)
let a = 0.2126 + 0.7874 * (1 - amount)
let b = 0.7152 - 0.7152 * (1 - amount)
let c = 0.0722 - 0.0722 * (1 - amount)
let d = 0.2126 - 0.2126 * (1 - amount)
let e = 0.7152 + 0.2848 * (1 - amount)
let f = 0.0722 - 0.0722 * (1 - amount)
let g = 0.2126 - 0.2126 * (1 - amount)
let h = 0.0722 + 0.9278 * (1 - amount)
return `<feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/>`
}
Snap.filter.grayscale.toString = function () {
return this()
@ -217,20 +171,18 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (amount == null) {
amount = 1
}
return Snap.format(
'<feColorMatrix type="matrix" values="{a} {b} {c} 0 0 {d} {e} {f} 0 0 {g} {h} {i} 0 0 0 0 0 1 0"/>',
{
a: 0.393 + 0.607 * (1 - amount),
b: 0.769 - 0.769 * (1 - amount),
c: 0.189 - 0.189 * (1 - amount),
d: 0.349 - 0.349 * (1 - amount),
e: 0.686 + 0.314 * (1 - amount),
f: 0.168 - 0.168 * (1 - amount),
g: 0.272 - 0.272 * (1 - amount),
h: 0.534 - 0.534 * (1 - amount),
i: 0.131 + 0.869 * (1 - amount)
}
)
let a = 0.393 + 0.607 * (1 - amount)
let b = 0.769 - 0.769 * (1 - amount)
let c = 0.189 - 0.189 * (1 - amount)
let d = 0.349 - 0.349 * (1 - amount)
let e = 0.686 + 0.314 * (1 - amount)
let f = 0.168 - 0.168 * (1 - amount)
let g = 0.272 - 0.272 * (1 - amount)
let h = 0.534 - 0.534 * (1 - amount)
let i = 0.131 + 0.869 * (1 - amount)
return `<feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/>`
}
Snap.filter.sepia.toString = function () {
return this()
@ -248,9 +200,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (amount == null) {
amount = 1
}
return Snap.format('<feColorMatrix type="saturate" values="{amount}"/>', {
amount: 1 - amount
})
return `<feColorMatrix type="saturate" values="${1 - amount}"/>`
}
Snap.filter.saturate.toString = function () {
return this()
@ -266,9 +216,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
\*/
Snap.filter.hueRotate = function (angle) {
angle = angle || 0
return Snap.format('<feColorMatrix type="hueRotate" values="{angle}"/>', {
angle: angle
})
return `<feColorMatrix type="hueRotate" values="${angle}"/>`
}
Snap.filter.hueRotate.toString = function () {
return this()
@ -287,13 +235,13 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
amount = 1
}
// <feColorMatrix type="matrix" values="-1 0 0 0 1 0 -1 0 0 1 0 0 -1 0 1 0 0 0 1 0" color-interpolation-filters="sRGB"/>
return Snap.format(
'<feComponentTransfer><feFuncR type="table" tableValues="{amount} {amount2}"/><feFuncG type="table" tableValues="{amount} {amount2}"/><feFuncB type="table" tableValues="{amount} {amount2}"/></feComponentTransfer>',
{
amount: amount,
amount2: 1 - amount
}
)
return `<feComponentTransfer><feFuncR type="table" tableValues="${amount} ${
1 - amount
}"/><feFuncG type="table" tableValues="${amount} ${
1 - amount
}"/><feFuncB type="table" tableValues="${amount} ${
1 - amount
}"/></feComponentTransfer>`
}
Snap.filter.invert.toString = function () {
return this()
@ -311,12 +259,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (amount == null) {
amount = 1
}
return Snap.format(
'<feComponentTransfer><feFuncR type="linear" slope="{amount}"/><feFuncG type="linear" slope="{amount}"/><feFuncB type="linear" slope="{amount}"/></feComponentTransfer>',
{
amount: amount
}
)
return `<feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer>`
}
Snap.filter.brightness.toString = function () {
return this()
@ -334,15 +277,10 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (amount == null) {
amount = 1
}
return Snap.format(
'<feComponentTransfer><feFuncR type="linear" slope="{amount}" intercept="{amount2}"/><feFuncG type="linear" slope="{amount}" intercept="{amount2}"/><feFuncB type="linear" slope="{amount}" intercept="{amount2}"/></feComponentTransfer>',
{
amount: amount,
amount2: 0.5 - amount / 2
}
)
let amount2 = 0.5 - amount / 2
return `<feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer>`
}
Snap.filter.contrast.toString = function () {
return this()
}
})

View File

@ -1,17 +1,17 @@
import { Snap } from './svg.js'
import './paper.js'
import './element.js'
import './animation.js'
import './matrix.js'
import './attr.js'
import './class.js'
import './attradd.js'
import './paper.js'
import './path.js'
import './set.js'
import './equal.js'
import './mouse.js'
import './filter.js'
import './align.js'
import './colors.js'
// import './colors.js'
export default Snap

444
src/lib/color.js Normal file
View File

@ -0,0 +1,444 @@
/**
* {颜色处理}
* @author yutent<yutent.io@gmail.com>
* @date 2024/03/06 13:05:09
*/
import { cacher, is } from '../utils.js'
const hsrg = { hs: 1, rg: 1 }
const colourRegExp =
/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?%?)\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?%?)\s*\))\s*$/i
function toHex(color) {
let i =
doc.getElementsByTagName('head')[0] || doc.getElementsByTagName('svg')[0],
red = 'rgb(255, 0, 0)'
toHex = cacher(function (color) {
if (color.toLowerCase() == 'red') {
return red
}
i.style.color = red
i.style.color = color
let out = doc.defaultView.getComputedStyle(i, E).getPropertyValue('color')
return out == red ? null : out
})
return toHex(color)
}
function hsbtoString() {
return 'hsb(' + [this.h, this.s, this.b] + ')'
}
function hsltoString() {
return 'hsl(' + [this.h, this.s, this.l] + ')'
}
function rgbtoString() {
return this.opacity == 1 || this.opacity == null
? this.hex
: 'rgba(' + [this.r, this.g, this.b, this.opacity] + ')'
}
function prepareRGB(r, g, b) {
if (g == null && is(r, 'object') && 'r' in r && 'g' in r && 'b' in r) {
b = r.b
g = r.g
r = r.r
}
if (g == null && is(r, string)) {
let clr = getRGB(r)
r = clr.r
g = clr.g
b = clr.b
}
if (r > 1 || g > 1 || b > 1) {
r /= 255
g /= 255
b /= 255
}
return [r, g, b]
}
function packageRGB(r, g, b, o) {
r = Math.round(r * 255)
g = Math.round(g * 255)
b = Math.round(b * 255)
let rgb = {
r: r,
g: g,
b: b,
opacity: is(o, 'finite') ? o : 1,
hex: rgb(r, g, b),
toString: rgbtoString
}
is(o, 'finite') && (rgb.opacity = o)
return rgb
}
// Colour
/*\
**
* Parses color string as RGB object
- color (string) color string in one of the following formats:
# <ul>
# <li>Color name (<code>red</code>, <code>green</code>, <code>cornflowerblue</code>, etc)</li>
# <li># shortened HTML color: (<code>#000</code>, <code>#fc0</code>, etc.)</li>
# <li># full length HTML color: (<code>#000000</code>, <code>#bd2300</code>)</li>
# <li>rgb(, , ) red, green and blue channels values: (<code>rgb(200,&nbsp;100,&nbsp;0)</code>)</li>
# <li>rgba(, , , ) also with opacity</li>
# <li>rgb(%, %, %) same as above, but in %: (<code>rgb(100%,&nbsp;175%,&nbsp;0%)</code>)</li>
# <li>rgba(%, %, %, %) also with opacity</li>
# <li>hsb(, , ) hue, saturation and brightness values: (<code>hsb(0.5,&nbsp;0.25,&nbsp;1)</code>)</li>
# <li>hsba(, , , ) also with opacity</li>
# <li>hsb(%, %, %) same as above, but in %</li>
# <li>hsba(%, %, %, %) also with opacity</li>
# <li>hsl(, , ) hue, saturation and luminosity values: (<code>hsb(0.5,&nbsp;0.25,&nbsp;0.5)</code>)</li>
# <li>hsla(, , , ) also with opacity</li>
# <li>hsl(%, %, %) same as above, but in %</li>
# <li>hsla(%, %, %, %) also with opacity</li>
# </ul>
* Note that `%` can be used any time: `rgb(20%, 255, 50%)`.
= (object) RGB object in the following format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #,
o error (boolean) true if string can't be parsed
o }
\*/
export const getRGB = cacher(function (colour) {
if (!colour || !!((colour = String(colour)).indexOf('-') + 1)) {
return {
r: -1,
g: -1,
b: -1,
hex: 'none',
error: 1,
toString: rgbtoString
}
}
if (colour == 'none') {
return { r: -1, g: -1, b: -1, hex: 'none', toString: rgbtoString }
}
!(
hsrg.hasOwnProperty(colour.toLowerCase().slice(0, 2)) ||
colour.charAt() == '#'
) && (colour = toHex(colour))
if (!colour) {
return {
r: -1,
g: -1,
b: -1,
hex: 'none',
error: 1,
toString: rgbtoString
}
}
let res,
red,
green,
blue,
opacity,
t,
values,
rgb = colour.match(colourRegExp)
if (rgb) {
if (rgb[2]) {
blue = parseInt(rgb[2].substring(5), 16)
green = parseInt(rgb[2].substring(3, 5), 16)
red = parseInt(rgb[2].substring(1, 3), 16)
}
if (rgb[3]) {
blue = parseInt((t = rgb[3].charAt(3)) + t, 16)
green = parseInt((t = rgb[3].charAt(2)) + t, 16)
red = parseInt((t = rgb[3].charAt(1)) + t, 16)
}
if (rgb[4]) {
values = rgb[4].split(commaSpaces)
red = +values[0]
values[0].slice(-1) == '%' && (red *= 2.55)
green = +values[1]
values[1].slice(-1) == '%' && (green *= 2.55)
blue = +values[2]
values[2].slice(-1) == '%' && (blue *= 2.55)
rgb[1].toLowerCase().slice(0, 4) == 'rgba' && (opacity = +values[3])
values[3] && values[3].slice(-1) == '%' && (opacity /= 100)
}
if (rgb[5]) {
values = rgb[5].split(commaSpaces)
red = +values[0]
values[0].slice(-1) == '%' && (red /= 100)
green = +values[1]
values[1].slice(-1) == '%' && (green /= 100)
blue = +values[2]
values[2].slice(-1) == '%' && (blue /= 100)
;(values[0].slice(-3) == 'deg' || values[0].slice(-1) == '\xb0') &&
(red /= 360)
rgb[1].toLowerCase().slice(0, 4) == 'hsba' && (opacity = +values[3])
values[3] && values[3].slice(-1) == '%' && (opacity /= 100)
return hsb2rgb(red, green, blue, opacity)
}
if (rgb[6]) {
values = rgb[6].split(commaSpaces)
red = +values[0]
values[0].slice(-1) == '%' && (red /= 100)
green = +values[1]
values[1].slice(-1) == '%' && (green /= 100)
blue = +values[2]
values[2].slice(-1) == '%' && (blue /= 100)
;(values[0].slice(-3) == 'deg' || values[0].slice(-1) == '\xb0') &&
(red /= 360)
rgb[1].toLowerCase().slice(0, 4) == 'hsla' && (opacity = +values[3])
values[3] && values[3].slice(-1) == '%' && (opacity /= 100)
return hsl2rgb(red, green, blue, opacity)
}
red = Math.min(Math.round(red), 255)
green = Math.min(Math.round(green), 255)
blue = Math.min(Math.round(blue), 255)
opacity = Math.min(Math.max(opacity, 0), 1)
rgb = { r: red, g: green, b: blue, toString: rgbtoString }
rgb.hex =
'#' + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1)
rgb.opacity = is(opacity, 'finite') ? opacity : 1
return rgb
}
return { r: -1, g: -1, b: -1, hex: 'none', error: 1, toString: rgbtoString }
})
/*\
**
* Converts HSB values to a hex representation of the color
- h (number) hue
- s (number) saturation
- b (number) value or brightness
= (string) hex representation of the color
\*/
export const hsb = cacher(function (h, s, b) {
return hsb2rgb(h, s, b).hex
})
/*\
**
* Converts HSL values to a hex representation of the color
- h (number) hue
- s (number) saturation
- l (number) luminosity
= (string) hex representation of the color
\*/
export const hsl = cacher(function (h, s, l) {
return hsl2rgb(h, s, l).hex
})
/*\
**
* Converts RGB values to a hex representation of the color
- r (number) red
- g (number) green
- b (number) blue
= (string) hex representation of the color
\*/
export const rgb = cacher(function (r, g, b, o) {
if (is(o, 'finite')) {
let round = Math.round
return 'rgba(' + [round(r), round(g), round(b), +o.toFixed(2)] + ')'
}
return '#' + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1)
})
/*\
**
* Parses the color string and returns an object featuring the color's component values
- clr (string) color string in one of the supported formats (see getRGB)
= (object) Combined RGB/HSB object in the following format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #,
o error (boolean) `true` if string can't be parsed,
o h (number) hue,
o s (number) saturation,
o v (number) value (brightness),
o l (number) lightness
o }
\*/
export const parseColor = function (clr) {
let rgb
if (is(clr, 'object') && 'h' in clr && 's' in clr && 'b' in clr) {
rgb = hsb2rgb(clr)
clr.r = rgb.r
clr.g = rgb.g
clr.b = rgb.b
clr.opacity = 1
clr.hex = rgb.hex
} else if (is(clr, 'object') && 'h' in clr && 's' in clr && 'l' in clr) {
rgb = hsl2rgb(clr)
clr.r = rgb.r
clr.g = rgb.g
clr.b = rgb.b
clr.opacity = 1
clr.hex = rgb.hex
} else {
if (is(clr, 'string')) {
clr = getRGB(clr)
}
if (
is(clr, 'object') &&
'r' in clr &&
'g' in clr &&
'b' in clr &&
!('error' in clr)
) {
rgb = rgb2hsl(clr)
clr.h = rgb.h
clr.s = rgb.s
clr.l = rgb.l
rgb = rgb2hsb(clr)
clr.v = rgb.b
} else {
clr = { hex: 'none' }
clr.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1
clr.error = 1
}
}
clr.toString = rgbtoString
return clr
}
/*\
**
* Converts HSB values to an RGB object
- h (number) hue
- s (number) saturation
- v (number) value or brightness
= (object) RGB object in the following format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #
o }
\*/
export const hsb2rgb = function (h, s, v, o) {
if (is(h, 'object') && 'h' in h && 's' in h && 'b' in h) {
v = h.b
s = h.s
o = h.o
h = h.h
}
h *= 360
let R, G, B, X, C
h = (h % 360) / 60
C = v * s
X = C * (1 - abs((h % 2) - 1))
R = G = B = v - C
h = ~~h
R += [C, X, 0, 0, X, C][h]
G += [X, C, C, X, 0, 0][h]
B += [0, 0, X, C, C, X][h]
return packageRGB(R, G, B, o)
}
/*\
**
* Converts HSL values to an RGB object
- h (number) hue
- s (number) saturation
- l (number) luminosity
= (object) RGB object in the following format:
o {
o r (number) red,
o g (number) green,
o b (number) blue,
o hex (string) color in HTML/CSS format: #
o }
\*/
export const hsl2rgb = function (h, s, l, o) {
if (is(h, 'object') && 'h' in h && 's' in h && 'l' in h) {
l = h.l
s = h.s
h = h.h
}
if (h > 1 || s > 1 || l > 1) {
h /= 360
s /= 100
l /= 100
}
h *= 360
let R, G, B, X, C
h = (h % 360) / 60
C = 2 * s * (l < 0.5 ? l : 1 - l)
X = C * (1 - abs((h % 2) - 1))
R = G = B = l - C / 2
h = ~~h
R += [C, X, 0, 0, X, C][h]
G += [X, C, C, X, 0, 0][h]
B += [0, 0, X, C, C, X][h]
return packageRGB(R, G, B, o)
}
/*\
**
* Converts RGB values to an HSB object
- r (number) red
- g (number) green
- b (number) blue
= (object) HSB object in the following format:
o {
o h (number) hue,
o s (number) saturation,
o b (number) brightness
o }
\*/
export const rgb2hsb = function (r, g, b) {
b = prepareRGB(r, g, b)
r = b[0]
g = b[1]
b = b[2]
let H, S, V, C
V = Math.max(r, g, b)
C = V - Math.min(r, g, b)
H =
C == 0
? null
: V == r
? (g - b) / C
: V == g
? (b - r) / C + 2
: (r - g) / C + 4
H = (((H + 360) % 6) * 60) / 360
S = C == 0 ? 0 : C / V
return { h: H, s: S, b: V, toString: hsbtoString }
}
/*\
**
* Converts RGB values to an HSL object
- r (number) red
- g (number) green
- b (number) blue
= (object) HSL object in the following format:
o {
o h (number) hue,
o s (number) saturation,
o l (number) luminosity
o }
\*/
export const rgb2hsl = function (r, g, b) {
b = prepareRGB(r, g, b)
r = b[0]
g = b[1]
b = b[2]
let H, S, L, M, m, C
M = Math.max(r, g, b)
m = Math.min(r, g, b)
C = M - m
H =
C == 0
? null
: M == r
? (g - b) / C
: M == g
? (b - r) / C + 2
: (r - g) / C + 4
H = (((H + 360) % 6) * 60) / 360
L = (M + m) / 2
S = C == 0 ? 0 : L < 0.5 ? C / (2 * L) : C / (2 - 2 * L)
return { h: H, s: S, l: L, toString: hsltoString }
}

86
src/lib/constants.js Normal file
View File

@ -0,0 +1,86 @@
/**
* {一些常量}
* @author yutent<yutent.io@gmail.com>
* @date 2024/03/06 16:25:01
*/
export const doc = document
export const win = window
export const xlink = 'http://www.w3.org/1999/xlink'
export const xmlns = 'http://www.w3.org/2000/svg'
export const CSS_ATTR = {
'alignment-baseline': 1,
'baseline-shift': 1,
clip: 1,
'clip-path': 1,
'clip-rule': 1,
color: 1,
'color-interpolation': 1,
'color-interpolation-filters': 1,
'color-profile': 1,
'color-rendering': 1,
cursor: 1,
direction: 1,
display: 1,
'dominant-baseline': 1,
'enable-background': 1,
fill: 1,
'fill-opacity': 1,
'fill-rule': 1,
filter: 1,
'flood-color': 1,
'flood-opacity': 1,
font: 1,
'font-family': 1,
'font-size': 1,
'font-size-adjust': 1,
'font-stretch': 1,
'font-style': 1,
'font-variant': 1,
'font-weight': 1,
'glyph-orientation-horizontal': 1,
'glyph-orientation-vertical': 1,
'image-rendering': 1,
kerning: 1,
'letter-spacing': 1,
'lighting-color': 1,
marker: 1,
'marker-end': 1,
'marker-mid': 1,
'marker-start': 1,
mask: 1,
opacity: 1,
overflow: 1,
'pointer-events': 1,
'shape-rendering': 1,
'stop-color': 1,
'stop-opacity': 1,
stroke: 1,
'stroke-dasharray': 1,
'stroke-dashoffset': 1,
'stroke-linecap': 1,
'stroke-linejoin': 1,
'stroke-miterlimit': 1,
'stroke-opacity': 1,
'stroke-width': 1,
'text-anchor': 1,
'text-decoration': 1,
'text-rendering': 1,
'unicode-bidi': 1,
visibility: 1,
'word-spacing': 1,
'writing-mode': 1
}
export const ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i
export const SEPARATOR = /[,\s]+/
export const whitespace = /[\s]/g
export const commaSpaces = /[\s]*,[\s]*/
export const bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/
export const pathCommand =
/([a-z])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\s]*,?[\s]*)+)/gi
export const T_COMMAND =
/([rstm])[\s,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\s]*,?[\s]*)+)/gi
export const PATH_VALUES = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\s]*,?[\s]*/gi

91
src/lib/math.js Normal file
View File

@ -0,0 +1,91 @@
/**
* {数学相关}
* @author yutent<yutent.io@gmail.com>
* @date 2024/03/06 13:05:25
*/
/* -------------------------------------------------------- */
/* --------------------- 数学方法 ---------------------- */
/* -------------------------------------------------------- */
/**
* Returns an angle between two or three points
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
- x3 (number) #optional x coord of third point
- y3 (number) #optional y coord of third point
= (number) angle in degrees
*/
export function angle(x1, y1, x2, y2, x3, y3) {
if (x3 == null) {
let x = x1 - x2,
y = y1 - y2
if (!x && !y) {
return 0
}
return (180 + (Math.atan2(-y, -x) * 180) / Math.PI + 360) % 360
} else {
return angle(x1, y1, x3, y3) - angle(x2, y2, x3, y3)
}
}
export function rad(deg) {
return ((deg % 360) * Math.PI) / 180
}
export function deg(radius) {
return ((radius * 180) / Math.PI) % 360
}
export function sin(angle) {
return Math.sin(rad(angle))
}
export function tan(angle) {
return Math.tan(rad(angle))
}
export function cos(angle) {
return Math.cos(rad(angle))
}
export function asin(num) {
return deg(Math.asin(num))
}
export function acos(num) {
return deg(Math.acos(num))
}
export function atan(num) {
return deg(Math.atan(num))
}
export function atan2(x, y) {
return deg(Math.atan2(x, y))
}
/*\
**
* Returns distance between two points
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
\*/
export function len(x1, y1, x2, y2) {
return Math.sqrt(len2(x1, y1, x2, y2))
}
/*\
**
* Returns squared distance between two points
- x1 (number) x coord of first point
- y1 (number) y coord of first point
- x2 (number) x coord of second point
- y2 (number) y coord of second point
\*/
export function len2(x1, y1, x2, y2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
}

View File

@ -11,9 +11,8 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Snap } from './svg.js'
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var objectToString = Object.prototype.toString,
import { Snap, SnapElement, Paper, Fragment } from './svg.js'
let objectToString = Object.prototype.toString,
Str = String,
math = Math,
E = ''
@ -62,7 +61,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
if (a && a instanceof Matrix) {
return this.add(a.a, a.b, a.c, a.d, a.e, a.f)
}
var aNew = a * this.a + b * this.c,
let aNew = a * this.a + b * this.c,
bNew = a * this.b + b * this.d
this.e += e * this.a + f * this.c
this.f += e * this.b + f * this.d
@ -91,7 +90,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
if (a && a instanceof Matrix) {
return this.multLeft(a.a, a.b, a.c, a.d, a.e, a.f)
}
var aNew = a * this.a + c * this.b,
let aNew = a * this.a + c * this.b,
cNew = a * this.c + c * this.d,
eNew = a * this.e + c * this.f + e
this.b = b * this.a + d * this.b
@ -111,7 +110,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
= (object) @Matrix
\*/
matrixproto.invert = function () {
var me = this,
let me = this,
x = me.a * me.d - me.b * me.c
return new Matrix(
me.d / x,
@ -179,7 +178,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
a = Snap.rad(a)
x = x || 0
y = y || 0
var cos = +math.cos(a).toFixed(9),
let cos = +math.cos(a).toFixed(9),
sin = +math.sin(a).toFixed(9)
this.add(cos, sin, -sin, cos, x, y)
return this.add(1, 0, 0, 1, -x, -y)
@ -217,8 +216,8 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
y = y || 0
x = Snap.rad(x)
y = Snap.rad(y)
var c = math.tan(x).toFixed(9)
var b = math.tan(y).toFixed(9)
let c = math.tan(x).toFixed(9)
let b = math.tan(y).toFixed(9)
return this.add(1, b, c, 1, 0, 0)
}
/*\
@ -269,7 +268,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return a[0] * a[0] + a[1] * a[1]
}
function normalize(a) {
var mag = math.sqrt(norm(a))
let mag = math.sqrt(norm(a))
a[0] && (a[0] /= mag)
a[1] && (a[1] /= mag)
}
@ -298,13 +297,13 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
o isSimple (boolean) could it be represented via simple transformations
\*/
matrixproto.split = function () {
var out = {}
let out = {}
// translation
out.dx = this.e
out.dy = this.f
// scale and shear
var row = [
let row = [
[this.a, this.b],
[this.c, this.d]
]
@ -326,7 +325,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
// rotation
var sin = row[0][1],
let sin = row[0][1],
cos = row[1][1]
if (cos < 0) {
out.rotate = Snap.deg(math.acos(cos))
@ -355,7 +354,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
= (string) transform string
\*/
matrixproto.toTransformString = function (shorter) {
var s = shorter || this.split()
let s = shorter || this.split()
if (!+s.shear.toFixed(9)) {
s.scalex = +s.scalex.toFixed(4)
s.scaley = +s.scaley.toFixed(4)
@ -363,9 +362,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return (
(s.dx || s.dy ? 't' + [+s.dx.toFixed(4), +s.dy.toFixed(4)] : E) +
(s.rotate ? 'r' + [+s.rotate.toFixed(4), 0, 0] : E) +
(s.scalex != 1 || s.scaley != 1
? 's' + [s.scalex, s.scaley, 0, 0]
: E)
(s.scalex != 1 || s.scaley != 1 ? 's' + [s.scalex, s.scaley, 0, 0] : E)
)
} else {
return (
@ -410,4 +407,3 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
Snap.matrix = function (a, b, c, d, e, f) {
return new Matrix(a, b, c, d, e, f)
}
})

View File

@ -13,83 +13,59 @@
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import { uuid } from './utils.js'
var animations = {},
let animations = {},
requestAnimFrame =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
setTimeout(callback, 16, new Date().getTime())
return true
},
window.mozRequestAnimationFrame,
requestID,
isArray =
Array.isArray ||
function (a) {
return (
a instanceof Array ||
Object.prototype.toString.call(a) == '[object Array]'
)
},
idgen = 0,
idprefix = 'M' + (+new Date()).toString(36),
ID = function () {
return idprefix + (idgen++).toString(36)
},
isArray = Array.isArray,
diff = function (a, b, A, B) {
if (isArray(a)) {
res = []
for (var i = 0, ii = a.length; i < ii; i++) {
for (let i = 0, ii = a.length; i < ii; i++) {
res[i] = diff(a[i], b, A[i], B)
}
return res
}
var dif = (A - a) / (B - b)
let dif = (A - a) / (B - b)
return function (bb) {
return a + dif * (bb - b)
}
},
timer =
Date.now ||
function () {
return +new Date()
},
timer = Date.now,
sta = function (val) {
var a = this
let a = this
if (val == null) {
return a.s
}
var ds = a.s - val
let ds = a.s - val
a.b += a.dur * ds
a.B += a.dur * ds
a.s = val
},
speed = function (val) {
var a = this
if (val == null) {
return a.spd
return this.spd
}
a.spd = val
this.spd = val
},
duration = function (val) {
var a = this
if (val == null) {
return a.dur
return this.dur
}
a.s = (a.s * val) / a.dur
a.dur = val
this.s = (this.s * val) / this.dur
this.dur = val
},
stopit = function () {
var a = this
delete animations[a.id]
a.update()
eve('mina.stop.' + a.id, a)
delete animations[this.id]
this.update()
eve('mina.stop.' + this.id, a)
},
pause = function () {
var a = this
let a = this
if (a.pdif) {
return
}
@ -98,7 +74,7 @@ var animations = {},
a.pdif = a.get() - a.b
},
resume = function () {
var a = this
let a = this
if (!a.pdif) {
return
}
@ -108,11 +84,11 @@ var animations = {},
frame()
},
update = function () {
var a = this,
let a = this,
res
if (isArray(a.start)) {
res = []
for (var j = 0, jj = a.start.length; j < jj; j++) {
for (let j = 0, jj = a.start.length; j < jj; j++) {
res[j] = +a.start[j] + (a.end[j] - a.start[j]) * a.easing(a.s)
}
} else {
@ -130,10 +106,10 @@ var animations = {},
}
return
}
var len = 0
for (var i in animations)
let len = 0
for (let i in animations)
if (animations.hasOwnProperty(i)) {
var a = animations[i],
let a = animations[i],
b = a.get(),
res
len++
@ -187,8 +163,8 @@ var animations = {},
o }
\*/
mina = function (a, A, b, B, get, set, easing) {
var anim = {
id: ID(),
let anim = {
id: uuid('M'),
start: a,
end: A,
b: b,
@ -207,7 +183,7 @@ var animations = {},
update: update
}
animations[anim.id] = anim
var len = 0,
let len = 0,
i
for (i in animations)
if (animations.hasOwnProperty(i)) {
@ -289,7 +265,7 @@ mina.easeinout = function (n) {
if (n == 0) {
return 0
}
var q = 0.48 - n / 1.04,
let q = 0.48 - n / 1.04,
Q = Math.sqrt(0.1734 + q * q),
x = Q - q,
X = Math.pow(Math.abs(x), 1 / 3) * (x < 0 ? -1 : 1),
@ -310,7 +286,7 @@ mina.backin = function (n) {
if (n == 1) {
return 1
}
var s = 1.70158
let s = 1.70158
return n * n * ((s + 1) * n - s)
}
/*\
@ -326,7 +302,7 @@ mina.backout = function (n) {
return 0
}
n = n - 1
var s = 1.70158
let s = 1.70158
return n * n * ((s + 1) * n + s) + 1
}
/*\
@ -354,7 +330,7 @@ mina.elastic = function (n) {
= (number) output 0..1
\*/
mina.bounce = function (n) {
var s = 7.5625,
let s = 7.5625,
p = 2.75,
l
if (n < 1 / p) {

View File

@ -12,10 +12,11 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper } from './svg.js'
import { is } from './utils.js'
import { doc, win } from './lib/constants.js'
Snap.plugin(function (Snap, Element, Paper, glob) {
var elproto = Element.prototype,
let elproto = SnapElement.prototype,
has = 'hasOwnProperty',
supportsTouch =
'ontouchstart' in window ||
@ -40,8 +41,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
mouseup: 'touchend'
},
getScroll = function (xy, el) {
var name = xy == 'y' ? 'scrollTop' : 'scrollLeft',
doc = el && el.node ? el.node.ownerDocument : glob.doc
let name = xy == 'y' ? 'scrollTop' : 'scrollLeft',
doc = el && el.node ? el.node.ownerDocument : doc
return doc[name in doc.documentElement ? 'documentElement' : 'body'][name]
},
preventDefault = function () {
@ -57,13 +58,13 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return this.originalEvent.stopPropagation()
},
addEvent = function (obj, type, fn, element) {
var realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
let realName = supportsTouch && touchMap[type] ? touchMap[type] : type,
f = function (e) {
var scrollY = getScroll('y', element),
let scrollY = getScroll('y', element),
scrollX = getScroll('x', element)
if (supportsTouch && touchMap[has](type)) {
for (
var i = 0, ii = e.targetTouches && e.targetTouches.length;
let i = 0, ii = e.targetTouches && e.targetTouches.length;
i < ii;
i++
) {
@ -71,7 +72,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
e.targetTouches[i].target == obj ||
obj.contains(e.targetTouches[i].target)
) {
var olde = e
let olde = e
e = e.targetTouches[i]
e.originalEvent = olde
e.preventDefault = preventTouch
@ -80,7 +81,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
}
}
var x = e.clientX + scrollX,
let x = e.clientX + scrollX,
y = e.clientY + scrollY
return fn.call(element, e, x, y)
}
@ -102,7 +103,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
},
drag = [],
dragMove = function (e) {
var x = e.clientX,
let x = e.clientX,
y = e.clientY,
scrollY = getScroll('y'),
scrollX = getScroll('x'),
@ -111,7 +112,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
while (j--) {
dragi = drag[j]
if (supportsTouch) {
var i = e.touches && e.touches.length,
let i = e.touches && e.touches.length,
touch
while (i--) {
touch = e.touches[i]
@ -128,16 +129,16 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
} else {
e.preventDefault()
}
var node = dragi.el.node,
let node = dragi.el.node,
o,
next = node.nextSibling,
parent = node.parentNode,
display = node.style.display
// glob.win.opera && parent.removeChild(node);
// win.opera && parent.removeChild(node);
// node.style.display = "none";
// o = dragi.el.paper.getElementByPoint(x, y);
// node.style.display = display;
// glob.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
// win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node));
// o && eve("snap.drag.over." + dragi.el.id, dragi.el, o);
x += scrollX
y += scrollY
@ -154,7 +155,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
},
dragUp = function (e) {
Snap.unmousemove(dragMove).unmouseup(dragUp)
var i = drag.length,
let i = drag.length,
dragi
while (i--) {
dragi = drag[i]
@ -169,208 +170,203 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
drag = []
}
/*\
* Element.click
* SnapElement.click
[ method ]
**
* Adds a click event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.unclick
* SnapElement.unclick
[ method ]
**
* Removes a click event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.dblclick
* SnapElement.dblclick
[ method ]
**
* Adds a double click event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.undblclick
* SnapElement.undblclick
[ method ]
**
* Removes a double click event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.mousedown
* SnapElement.mousedown
[ method ]
**
* Adds a mousedown event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.unmousedown
* SnapElement.unmousedown
[ method ]
**
* Removes a mousedown event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.mousemove
* SnapElement.mousemove
[ method ]
**
* Adds a mousemove event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.unmousemove
* SnapElement.unmousemove
[ method ]
**
* Removes a mousemove event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.mouseout
* SnapElement.mouseout
[ method ]
**
* Adds a mouseout event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.unmouseout
* SnapElement.unmouseout
[ method ]
**
* Removes a mouseout event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.mouseover
* SnapElement.mouseover
[ method ]
**
* Adds a mouseover event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.unmouseover
* SnapElement.unmouseover
[ method ]
**
* Removes a mouseover event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.mouseup
* SnapElement.mouseup
[ method ]
**
* Adds a mouseup event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.unmouseup
* SnapElement.unmouseup
[ method ]
**
* Removes a mouseup event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.touchstart
* SnapElement.touchstart
[ method ]
**
* Adds a touchstart event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.untouchstart
* SnapElement.untouchstart
[ method ]
**
* Removes a touchstart event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.touchmove
* SnapElement.touchmove
[ method ]
**
* Adds a touchmove event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.untouchmove
* SnapElement.untouchmove
[ method ]
**
* Removes a touchmove event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.touchend
* SnapElement.touchend
[ method ]
**
* Adds a touchend event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.untouchend
* SnapElement.untouchend
[ method ]
**
* Removes a touchend event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.touchcancel
* SnapElement.touchcancel
[ method ]
**
* Adds a touchcancel event handler to the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
/*\
* Element.untouchcancel
* SnapElement.untouchcancel
[ method ]
**
* Removes a touchcancel event handler from the element
- handler (function) handler for the event
= (object) @Element
= (object) @SnapElement
\*/
for (var i = events.length; i--; ) {
for (let i = events.length; i--; ) {
;(function (eventName) {
Snap[eventName] = elproto[eventName] = function (fn, scope) {
if (Snap.is(fn, 'function')) {
if (is(fn, 'function')) {
this.events = this.events || []
this.events.push({
name: eventName,
f: fn,
unbind: addEvent(
this.node || document,
eventName,
fn,
scope || this
)
unbind: addEvent(this.node || document, eventName, fn, scope || this)
})
} else {
for (var i = 0, ii = this.events.length; i < ii; i++)
for (let i = 0, ii = this.events.length; i < ii; i++)
if (this.events[i].name == eventName) {
try {
this.events[i].f.call(this)
@ -380,7 +376,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return this
}
Snap['un' + eventName] = elproto['un' + eventName] = function (fn) {
var events = this.events || [],
let events = this.events || [],
l = events.length
while (l--)
if (events[l].name == eventName && (events[l].f == fn || !fn)) {
@ -394,7 +390,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
})(events[i])
}
/*\
* Element.hover
* SnapElement.hover
[ method ]
**
* Adds hover event handlers to the element
@ -402,30 +398,30 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
- f_out (function) handler for hover out
- icontext (object) #optional context for hover in handler
- ocontext (object) #optional context for hover out handler
= (object) @Element
= (object) @SnapElement
\*/
elproto.hover = function (f_in, f_out, scope_in, scope_out) {
return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in)
}
/*\
* Element.unhover
* SnapElement.unhover
[ method ]
**
* Removes hover event handlers from the element
- f_in (function) handler for hover in
- f_out (function) handler for hover out
= (object) @Element
= (object) @SnapElement
\*/
elproto.unhover = function (f_in, f_out) {
return this.unmouseover(f_in).unmouseout(f_out)
}
var draggable = []
let draggable = []
// SIERRA unclear what _context_ refers to for starting, ending, moving the drag gesture.
// SIERRA Element.drag(): _x position of the mouse_: Where are the x/y values offset from?
// SIERRA Element.drag(): much of this member's doc appears to be duplicated for some reason.
// SIERRA Unclear about this sentence: _Additionally following drag events will be triggered: drag.start.<id> on start, drag.end.<id> on end and drag.move.<id> on every move._ Is there a global _drag_ object to which you can assign handlers keyed by an element's ID?
// SIERRA SnapElement.drag(): _x position of the mouse_: Where are the x/y values offset from?
// SIERRA SnapElement.drag(): much of this member's doc appears to be duplicated for some reason.
// SIERRA Unclear about this sentence: _Additionally following drag events will be triggered: drag.start.<id> on start, drag.end.<id> on end and drag.move.<id> on every move._ Is there a global _drag_ object to which you can assign handlers keyed by an element's id?
/*\
* Element.drag
* SnapElement.drag
[ method ]
**
* Adds event handlers for an element's drag gesture
@ -452,7 +448,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
o event (object) DOM event object
* End event and end handler are called in specified context or in context of the element with following parameters:
o event (object) DOM event object
= (object) @Element
= (object) @SnapElement
\*/
elproto.drag = function (
onmove,
@ -462,9 +458,9 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
start_scope,
end_scope
) {
var el = this
let el = this
if (!arguments.length) {
var origTransform
let origTransform
return el.drag(
function (dx, dy) {
this.attr({
@ -503,23 +499,23 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return el
}
/*
* Element.onDragOver
* SnapElement.onDragOver
[ method ]
**
* Shortcut to assign event handler for `drag.over.<id>` event, where `id` is the element's `id` (see @Element.id)
* Shortcut to assign event handler for `drag.over.<id>` event, where `id` is the element's `id` (see @SnapElement.id)
- f (function) handler for event, first argument would be the element you are dragging over
\*/
// elproto.onDragOver = function (f) {
// f ? eve.on("snap.drag.over." + this.id, f) : eve.unbind("snap.drag.over." + this.id);
// };
/*\
* Element.undrag
* SnapElement.undrag
[ method ]
**
* Removes all drag event handlers from the given element
\*/
elproto.undrag = function () {
var i = draggable.length
let i = draggable.length
while (i--)
if (draggable[i].el == this) {
this.unmousedown(draggable[i].init)
@ -530,4 +526,3 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
!draggable.length && Snap.unmousemove(dragMove).unmouseup(dragUp)
return this
}
})

View File

@ -12,511 +12,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper, Fragment, make, wrap } from './svg.js'
import { $, is, uuid, preload } from './utils.js'
import { doc, win } from './lib/constants.js'
Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
var proto = Paper.prototype,
is = Snap.is
/*\
* Paper.rect
[ method ]
*
* Draws a rectangle
**
- x (number) x coordinate of the top left corner
- y (number) y coordinate of the top left corner
- width (number) width
- height (number) height
- rx (number) #optional horizontal radius for rounded corners, default is 0
- ry (number) #optional vertical radius for rounded corners, default is rx or 0
= (object) the `rect` element
**
> Usage
| // regular rectangle
| var c = paper.rect(10, 10, 50, 50);
| // rectangle with rounded corners
| var c = paper.rect(40, 40, 50, 50, 10);
\*/
proto.rect = function (x, y, w, h, rx, ry) {
var attr
if (ry == null) {
ry = rx
}
if (is(x, 'object') && x == '[object Object]') {
attr = x
} else if (x != null) {
attr = {
x: x,
y: y,
width: w,
height: h
}
if (rx != null) {
attr.rx = rx
attr.ry = ry
}
}
return this.el('rect', attr)
}
/*\
* Paper.circle
[ method ]
**
* Draws a circle
**
- x (number) x coordinate of the centre
- y (number) y coordinate of the centre
- r (number) radius
= (object) the `circle` element
**
> Usage
| var c = paper.circle(50, 50, 40);
\*/
proto.circle = function (cx, cy, r) {
var attr
if (is(cx, 'object') && cx == '[object Object]') {
attr = cx
} else if (cx != null) {
attr = {
cx: cx,
cy: cy,
r: r
}
}
return this.el('circle', attr)
}
let proto = Paper.prototype
var preload = (function () {
function onerror() {
this.parentNode.removeChild(this)
}
return function (src, f) {
var img = glob.doc.createElement('img'),
body = glob.doc.body
img.style.cssText = 'position:absolute;left:-9999em;top:-9999em'
img.onload = function () {
f.call(img)
img.onload = img.onerror = null
body.removeChild(img)
}
img.onerror = onerror
body.appendChild(img)
img.src = src
}
})()
/*\
* Paper.image
[ method ]
**
* Places an image on the surface
**
- src (string) URI of the source image
- x (number) x offset position
- y (number) y offset position
- width (number) width of the image
- height (number) height of the image
= (object) the `image` element
* or
= (object) Snap element object with type `image`
**
> Usage
| var c = paper.image("apple.png", 10, 10, 80, 80);
\*/
proto.image = function (src, x, y, width, height) {
var el = this.el('image')
if (is(src, 'object') && 'src' in src) {
el.attr(src)
} else if (src != null) {
var set = {
'xlink:href': src,
preserveAspectRatio: 'none'
}
if (x != null && y != null) {
set.x = x
set.y = y
}
if (width != null && height != null) {
set.width = width
set.height = height
} else {
preload(src, function () {
Snap._.$(el.node, {
width: this.offsetWidth,
height: this.offsetHeight
})
})
}
Snap._.$(el.node, set)
}
return el
}
/*\
* Paper.ellipse
[ method ]
**
* Draws an ellipse
**
- x (number) x coordinate of the centre
- y (number) y coordinate of the centre
- rx (number) horizontal radius
- ry (number) vertical radius
= (object) the `ellipse` element
**
> Usage
| var c = paper.ellipse(50, 50, 40, 20);
\*/
proto.ellipse = function (cx, cy, rx, ry) {
var attr
if (is(cx, 'object') && cx == '[object Object]') {
attr = cx
} else if (cx != null) {
attr = {
cx: cx,
cy: cy,
rx: rx,
ry: ry
}
}
return this.el('ellipse', attr)
}
// SIERRA Paper.path(): Unclear from the link what a Catmull-Rom curveto is, and why it would make life any easier.
/*\
* Paper.path
[ method ]
**
* Creates a `<path>` element using the given string as the path's definition
- pathString (string) #optional path string in SVG format
* Path string consists of one-letter commands, followed by comma seprarated arguments in numerical form. Example:
| "M10,20L30,40"
* This example features two commands: `M`, with arguments `(10, 20)` and `L` with arguments `(30, 40)`. Uppercase letter commands express coordinates in absolute terms, while lowercase commands express them in relative terms from the most recently declared coordinates.
*
# <p>Here is short list of commands available, for more details see <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path's data attribute's format are described in the SVG specification.">SVG path string format</a> or <a href="https://developer.mozilla.org/en/SVG/Tutorial/Paths">article about path strings at MDN</a>.</p>
# <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody>
# <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr>
# <tr><td>Z</td><td>closepath</td><td>(none)</td></tr>
# <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr>
# <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr>
# <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr>
# <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr>
# <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr>
# <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr>
# <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr>
# <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr>
# <tr><td>R</td><td><a href="http://en.wikipedia.org/wiki/CatmullRom_spline#Catmull.E2.80.93Rom_spline">Catmull-Rom curveto</a>*</td><td>x1 y1 (x y)+</td></tr></tbody></table>
* * _Catmull-Rom curveto_ is a not standard SVG command and added to make life easier.
* Note: there is a special case when a path consists of only three commands: `M10,10R…z`. In this case the path connects back to its starting point.
> Usage
| var c = paper.path("M10 10L90 90");
| // draw a diagonal line:
| // move to 10,10, line to 90,90
\*/
proto.path = function (d) {
var attr
if (is(d, 'object') && !is(d, 'array')) {
attr = d
} else if (d) {
attr = { d: d }
}
return this.el('path', attr)
}
/*\
* Paper.g
[ method ]
**
* Creates a group element
**
- varargs () #optional elements to nest within the group
= (object) the `g` element
**
> Usage
| var c1 = paper.circle(),
| c2 = paper.rect(),
| g = paper.g(c2, c1); // note that the order of elements is different
* or
| var c1 = paper.circle(),
| c2 = paper.rect(),
| g = paper.g();
| g.add(c2, c1);
\*/
/*\
* Paper.group
[ method ]
**
* See @Paper.g
\*/
proto.group = proto.g = function (first) {
var attr,
el = this.el('g')
if (arguments.length == 1 && first && !first.type) {
el.attr(first)
} else if (arguments.length) {
el.add(Array.prototype.slice.call(arguments, 0))
}
return el
}
/*\
* Paper.svg
[ method ]
**
* Creates a nested SVG element.
- x (number) @optional X of the element
- y (number) @optional Y of the element
- width (number) @optional width of the element
- height (number) @optional height of the element
- vbx (number) @optional viewbox X
- vby (number) @optional viewbox Y
- vbw (number) @optional viewbox width
- vbh (number) @optional viewbox height
**
= (object) the `svg` element
**
\*/
proto.svg = function (x, y, width, height, vbx, vby, vbw, vbh) {
var attrs = {}
if (is(x, 'object') && y == null) {
attrs = x
} else {
if (x != null) {
attrs.x = x
}
if (y != null) {
attrs.y = y
}
if (width != null) {
attrs.width = width
}
if (height != null) {
attrs.height = height
}
if (vbx != null && vby != null && vbw != null && vbh != null) {
attrs.viewBox = [vbx, vby, vbw, vbh]
}
}
return this.el('svg', attrs)
}
/*\
* Paper.mask
[ method ]
**
* Equivalent in behaviour to @Paper.g, except its a mask.
**
= (object) the `mask` element
**
\*/
proto.mask = function (first) {
var attr,
el = this.el('mask')
if (arguments.length == 1 && first && !first.type) {
el.attr(first)
} else if (arguments.length) {
el.add(Array.prototype.slice.call(arguments, 0))
}
return el
}
/*\
* Paper.ptrn
[ method ]
**
* Equivalent in behaviour to @Paper.g, except its a pattern.
- x (number) @optional X of the element
- y (number) @optional Y of the element
- width (number) @optional width of the element
- height (number) @optional height of the element
- vbx (number) @optional viewbox X
- vby (number) @optional viewbox Y
- vbw (number) @optional viewbox width
- vbh (number) @optional viewbox height
**
= (object) the `pattern` element
**
\*/
proto.ptrn = function (x, y, width, height, vx, vy, vw, vh) {
if (is(x, 'object')) {
var attr = x
} else {
attr = { patternUnits: 'userSpaceOnUse' }
if (x) {
attr.x = x
}
if (y) {
attr.y = y
}
if (width != null) {
attr.width = width
}
if (height != null) {
attr.height = height
}
if (vx != null && vy != null && vw != null && vh != null) {
attr.viewBox = [vx, vy, vw, vh]
} else {
attr.viewBox = [x || 0, y || 0, width || 0, height || 0]
}
}
return this.el('pattern', attr)
}
/*\
* Paper.use
[ method ]
**
* Creates a <use> element.
- id (string) @optional id of element to link
* or
- id (Element) @optional element to link
**
= (object) the `use` element
**
\*/
proto.use = function (id) {
if (id != null) {
if (id instanceof Element) {
if (!id.attr('id')) {
id.attr({ id: Snap._.id(id) })
}
id = id.attr('id')
}
if (String(id).charAt() == '#') {
id = id.substring(1)
}
return this.el('use', { 'xlink:href': '#' + id })
} else {
return Element.prototype.use.call(this)
}
}
/*\
* Paper.symbol
[ method ]
**
* Creates a <symbol> element.
- vbx (number) @optional viewbox X
- vby (number) @optional viewbox Y
- vbw (number) @optional viewbox width
- vbh (number) @optional viewbox height
= (object) the `symbol` element
**
\*/
proto.symbol = function (vx, vy, vw, vh) {
var attr = {}
if (vx != null && vy != null && vw != null && vh != null) {
attr.viewBox = [vx, vy, vw, vh]
}
return this.el('symbol', attr)
}
/*\
* Paper.text
[ method ]
**
* Draws a text string
**
- x (number) x coordinate position
- y (number) y coordinate position
- text (string|array) The text string to draw or array of strings to nest within separate `<tspan>` elements
= (object) the `text` element
**
> Usage
| var t1 = paper.text(50, 50, "Snap");
| var t2 = paper.text(50, 50, ["S","n","a","p"]);
| // Text path usage
| t1.attr({textpath: "M10,10L100,100"});
| // or
| var pth = paper.path("M10,10L100,100");
| t1.attr({textpath: pth});
\*/
proto.text = function (x, y, text) {
var attr = {}
if (is(x, 'object')) {
attr = x
} else if (x != null) {
attr = {
x: x,
y: y,
text: text || ''
}
}
return this.el('text', attr)
}
/*\
* Paper.line
[ method ]
**
* Draws a line
**
- x1 (number) x coordinate position of the start
- y1 (number) y coordinate position of the start
- x2 (number) x coordinate position of the end
- y2 (number) y coordinate position of the end
= (object) the `line` element
**
> Usage
| var t1 = paper.line(50, 50, 100, 100);
\*/
proto.line = function (x1, y1, x2, y2) {
var attr = {}
if (is(x1, 'object')) {
attr = x1
} else if (x1 != null) {
attr = {
x1: x1,
x2: x2,
y1: y1,
y2: y2
}
}
return this.el('line', attr)
}
/*\
* Paper.polyline
[ method ]
**
* Draws a polyline
**
- points (array) array of points
* or
- varargs () points
= (object) the `polyline` element
**
> Usage
| var p1 = paper.polyline([10, 10, 100, 100]);
| var p2 = paper.polyline(10, 10, 100, 100);
\*/
proto.polyline = function (points) {
if (arguments.length > 1) {
points = Array.prototype.slice.call(arguments, 0)
}
var attr = {}
if (is(points, 'object') && !is(points, 'array')) {
attr = points
} else if (points != null) {
attr = { points: points }
}
return this.el('polyline', attr)
}
/*\
* Paper.polygon
[ method ]
**
* Draws a polygon. See @Paper.polyline
\*/
proto.polygon = function (points) {
if (arguments.length > 1) {
points = Array.prototype.slice.call(arguments, 0)
}
var attr = {}
if (is(points, 'object') && !is(points, 'array')) {
attr = points
} else if (points != null) {
attr = { points: points }
}
return this.el('polygon', attr)
}
// gradients
;(function () {
var $ = Snap._.$
// gradients' helpers
/*\
* Element.stops
* SnapElement.stops
[ method ]
**
* Only for gradients!
@ -527,7 +33,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this.selectAll('stop')
}
/*\
* Element.addStop
* SnapElement.addStop
[ method ]
**
* Only for gradients!
@ -537,20 +43,20 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
= (object) gradient element
\*/
function GaddStop(color, offset) {
var stop = $('stop'),
let stop = $('stop'),
attr = {
offset: +offset + '%'
}
color = Snap.color(color)
color = parseColor(color)
attr['stop-color'] = color.hex
if (color.opacity < 1) {
attr['stop-opacity'] = color.opacity
}
$(stop, attr)
var stops = this.stops(),
let stops = this.stops(),
inserted
for (var i = 0; i < stops.length; i++) {
var stopOffset = parseFloat(stops[i].attr('offset'))
for (let i = 0; i < stops.length; i++) {
let stopOffset = parseFloat(stops[i].attr('offset'))
if (stopOffset > offset) {
this.node.insertBefore(stop, stops[i].node)
inserted = true
@ -564,31 +70,31 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
function GgetBBox() {
if (this.type == 'linearGradient') {
var x1 = $(this.node, 'x1') || 0,
let x1 = $(this.node, 'x1') || 0,
x2 = $(this.node, 'x2') || 1,
y1 = $(this.node, 'y1') || 0,
y2 = $(this.node, 'y2') || 0
return Snap._.box(x1, y1, math.abs(x2 - x1), math.abs(y2 - y1))
} else {
var cx = this.node.cx || 0.5,
let cx = this.node.cx || 0.5,
cy = this.node.cy || 0.5,
r = this.node.r || 0
return Snap._.box(cx - r, cy - r, r * 2, r * 2)
}
}
/*\
* Element.setStops
* SnapElement.setStops
[ method ]
**
* Only for gradients!
* Updates stops of the gradient based on passed gradient descriptor. See @Ppaer.gradient
- str (string) gradient descriptor part after `()`.
= (object) gradient element
| var g = paper.gradient("l(0, 0, 1, 1)#000-#f00-#fff");
| let g = paper.gradient("l(0, 0, 1, 1)#000-#f00-#fff");
| g.setStops("#fff-#000-#f00-#fc0");
\*/
function GsetStops(str) {
var grad = str,
let grad = str,
stops = this.stops()
if (typeof str == 'string') {
grad = eve(
@ -597,12 +103,12 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
'l(0,0,0,1)' + str
).firstDefined().stops
}
if (!Snap.is(grad, 'array')) {
if (!is(grad, 'array')) {
return
}
for (var i = 0; i < stops.length; i++) {
for (let i = 0; i < stops.length; i++) {
if (grad[i]) {
var color = Snap.color(grad[i].color),
let color = parseColor(grad[i].color),
attr = { offset: grad[i].offset + '%' }
attr['stop-color'] = color.hex
if (color.opacity < 1) {
@ -619,7 +125,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return this
}
function gradient(defs, str) {
var grad = eve('snap.util.grad.parse', null, str).firstDefined(),
let grad = eve('snap.util.grad.parse', null, str).firstDefined(),
el
if (!grad) {
return null
@ -635,16 +141,16 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
gradientUnits: 'userSpaceOnUse'
})
}
var stops = grad.stops,
let stops = grad.stops,
len = stops.length
for (var i = 0; i < len; i++) {
var stop = stops[i]
for (let i = 0; i < len; i++) {
let stop = stops[i]
el.addStop(stop.color, stop.offset)
}
return el
}
function gradientLinear(defs, x1, y1, x2, y2) {
var el = Snap._.make('linearGradient', defs)
let el = make('linearGradient', defs)
el.stops = Gstops
el.addStop = GaddStop
el.getBBox = GgetBBox
@ -660,7 +166,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
return el
}
function gradientRadial(defs, cx, cy, r, fx, fy) {
var el = Snap._.make('radialGradient', defs)
let el = make('radialGradient', defs)
el.stops = Gstops
el.addStop = GaddStop
el.getBBox = GgetBBox
@ -679,43 +185,7 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
}
return el
}
/*\
* Paper.gradient
[ method ]
**
* Creates a gradient element
**
- gradient (string) gradient descriptor
> Gradient Descriptor
* The gradient descriptor is an expression formatted as
* follows: `<type>(<coords>)<colors>`. The `<type>` can be
* either linear or radial. The uppercase `L` or `R` letters
* indicate absolute coordinates offset from the SVG surface.
* Lowercase `l` or `r` letters indicate coordinates
* calculated relative to the element to which the gradient is
* applied. Coordinates specify a linear gradient vector as
* `x1`, `y1`, `x2`, `y2`, or a radial gradient as `cx`, `cy`,
* `r` and optional `fx`, `fy` specifying a focal point away
* from the center of the circle. Specify `<colors>` as a list
* of dash-separated CSS color values. Each color may be
* followed by a custom offset value, separated with a colon
* character.
> Examples
* Linear gradient, relative from top-left corner to bottom-right
* corner, from black through red to white:
| var g = paper.gradient("l(0, 0, 1, 1)#000-#f00-#fff");
* Linear gradient, absolute from (0, 0) to (100, 100), from black
* through red at 25% to white:
| var g = paper.gradient("L(0, 0, 100, 100)#000-#f00:25-#fff");
* Radial gradient, relative from the center of the element with radius
* half the width, from black to white:
| var g = paper.gradient("r(0.5, 0.5, 0.5)#000-#fff");
* To apply the gradient:
| paper.circle(50, 50, 40).attr({
| fill: g
| });
= (object) the `gradient` element
\*/
proto.gradient = function (str) {
return gradient(this.defs, str)
}
@ -725,59 +195,4 @@ Snap.plugin(function (Snap, Element, Paper, glob, Fragment) {
proto.gradientRadial = function (cx, cy, r, fx, fy) {
return gradientRadial(this.defs, cx, cy, r, fx, fy)
}
/*\
* Paper.toString
[ method ]
**
* Returns SVG code for the @Paper
= (string) SVG code for the @Paper
\*/
proto.toString = function () {
var doc = this.node.ownerDocument,
f = doc.createDocumentFragment(),
d = doc.createElement('div'),
svg = this.node.cloneNode(true),
res
f.appendChild(d)
d.appendChild(svg)
Snap._.$(svg, { xmlns: 'http://www.w3.org/2000/svg' })
res = d.innerHTML
f.removeChild(f.firstChild)
return res
}
/*\
* Paper.toDataURL
[ method ]
**
* Returns SVG code for the @Paper as Data URI string.
= (string) Data URI string
\*/
proto.toDataURL = function () {
if (window && window.btoa) {
return (
'data:image/svg+xml;base64,' +
btoa(unescape(encodeURIComponent(this)))
)
}
}
/*\
* Paper.clear
[ method ]
**
* Removes all child nodes of the paper, except <defs>.
\*/
proto.clear = function () {
var node = this.node.firstChild,
next
while (node) {
next = node.nextSibling
if (node.tagName != 'defs') {
node.parentNode.removeChild(node)
} else {
proto.clear.call({ node: node })
}
node = next
}
}
})()
})

View File

@ -11,12 +11,10 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper, Fragment, unit2px } from './svg.js'
import { is, clone, cacher } from './utils.js'
Snap.plugin(function (Snap, Element, Paper, glob) {
var elproto = Element.prototype,
is = Snap.is,
clone = Snap._.clone,
let elproto = SnapElement.prototype,
has = 'hasOwnProperty',
p2s = /,?([a-z]),?/gi,
toFloat = parseFloat,
@ -27,7 +25,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
pow = math.pow,
abs = math.abs
function paths(ps) {
var p = (paths.ps = paths.ps || {})
let p = (paths.ps = paths.ps || {})
if (p[ps]) {
p[ps].sleep = 100
} else {
@ -36,7 +34,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
}
setTimeout(function () {
for (var key in p)
for (let key in p)
if (p[has](key) && key != ps) {
p[key].sleep--
!p[key].sleep && delete p[key]
@ -76,7 +74,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return this.join(',').replace(p2s, '$1')
}
function pathClone(pathArray) {
var res = clone(pathArray)
let res = clone(pathArray)
res.toString = toString
return res
}
@ -111,13 +109,13 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
function O(val) {
return +(+val).toFixed(3)
}
return Snap._.cacher(
return cacher(
function (path, length, onlystart) {
if (path instanceof Element) {
if (path instanceof SnapElement) {
path = path.attr('d')
}
path = path2curve(path)
var x,
let x,
y,
p,
l,
@ -125,22 +123,13 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
subpaths = {},
point,
len = 0
for (var i = 0, ii = path.length; i < ii; i++) {
for (let i = 0, ii = path.length; i < ii; i++) {
p = path[i]
if (p[0] == 'M') {
x = +p[1]
y = +p[2]
} else {
l = getPointAtSegmentLength(
x,
y,
p[1],
p[2],
p[3],
p[4],
p[5],
p[6]
)
l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6])
if (len + l > length) {
if (subpath && !subpaths.start) {
point = getPointAtSegmentLength(
@ -210,14 +199,14 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return point
},
null,
Snap._.clone
clone
)
}
var getTotalLength = getLengthFactory(1),
let getTotalLength = getLengthFactory(1),
getPointAtLength = getLengthFactory(),
getSubpathsAtLength = getLengthFactory(0, 1)
function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t,
let t1 = 1 - t,
t13 = pow(t1, 3),
t12 = pow(t1, 2),
t2 = t * t,
@ -245,10 +234,10 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
}
function bezierBBox(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) {
if (!Snap.is(p1x, 'array')) {
if (!is(p1x, 'array')) {
p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y]
}
var bbox = curveDim.apply(null, p1x)
let bbox = curveDim.apply(null, p1x)
return box(
bbox.min.x,
bbox.min.y,
@ -283,7 +272,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
)
}
function base3(t, p1, p2, p3, p4) {
var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4,
let t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4,
t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3
return t * t2 - 3 * p1 + 3 * p2
}
@ -292,7 +281,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
z = 1
}
z = z > 1 ? 1 : z < 0 ? 0 : z
var z2 = z / 2,
let z2 = z / 2,
n = 12,
Tvalues = [
-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699,
@ -303,8 +292,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
0.1069, 0.0472, 0.0472
],
sum = 0
for (var i = 0; i < n; i++) {
var ct = z2 * Tvalues[i] + z2,
for (let i = 0; i < n; i++) {
let ct = z2 * Tvalues[i] + z2,
xbase = base3(ct, x1, x2, x3, x4),
ybase = base3(ct, y1, y2, y3, y4),
comb = xbase * xbase + ybase * ybase
@ -316,7 +305,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) {
return
}
var t = 1,
let t = 1,
step = t / 2,
t2 = t - step,
l,
@ -338,14 +327,14 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
) {
return
}
var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4),
let nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4),
ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4),
denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if (!denominator) {
return
}
var px = nx / denominator,
let px = nx / denominator,
py = ny / denominator,
px2 = +px.toFixed(2),
py2 = +py.toFixed(2)
@ -370,12 +359,12 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return interHelper(bez1, bez2, 1)
}
function interHelper(bez1, bez2, justCount) {
var bbox1 = bezierBBox(bez1),
let bbox1 = bezierBBox(bez1),
bbox2 = bezierBBox(bez2)
if (!isBBoxIntersect(bbox1, bbox2)) {
return justCount ? 0 : []
}
var l1 = bezlen.apply(0, bez1),
let l1 = bezlen.apply(0, bez1),
l2 = bezlen.apply(0, bez2),
n1 = ~~(l1 / 8),
n2 = ~~(l2 / 8),
@ -383,8 +372,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
dots2 = [],
xy = {},
res = justCount ? 0 : []
for (var i = 0; i < n1 + 1; i++) {
var p = findDotsAtSegment.apply(0, bez1.concat(i / n1))
for (let i = 0; i < n1 + 1; i++) {
let p = findDotsAtSegment.apply(0, bez1.concat(i / n1))
dots1.push({ x: p.x, y: p.y, t: i / n1 })
}
for (i = 0; i < n2 + 1; i++) {
@ -392,8 +381,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
dots2.push({ x: p.x, y: p.y, t: i / n2 })
}
for (i = 0; i < n1; i++) {
for (var j = 0; j < n2; j++) {
var di = dots1[i],
for (let j = 0; j < n2; j++) {
let di = dots1[i],
di1 = dots1[i + 1],
dj = dots2[j],
dj1 = dots2[j + 1],
@ -405,12 +394,10 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
continue
}
xy[is.x.toFixed(4)] = is.y.toFixed(4)
var t1 =
di.t +
abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t),
let t1 =
di.t + abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t),
t2 =
dj.t +
abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t)
dj.t + abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t)
if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) {
if (justCount) {
res++
@ -437,7 +424,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
function interPathHelper(path1, path2, justCount) {
path1 = path2curve(path1)
path2 = path2curve(path2)
var x1,
let x1,
y1,
x2,
y2,
@ -448,8 +435,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
bez1,
bez2,
res = justCount ? 0 : []
for (var i = 0, ii = path1.length; i < ii; i++) {
var pi = path1[i]
for (let i = 0, ii = path1.length; i < ii; i++) {
let pi = path1[i]
if (pi[0] == 'M') {
x1 = x1m = pi[1]
y1 = y1m = pi[2]
@ -463,8 +450,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
x1 = x1m
y1 = y1m
}
for (var j = 0, jj = path2.length; j < jj; j++) {
var pj = path2[j]
for (let j = 0, jj = path2.length; j < jj; j++) {
let pj = path2[j]
if (pj[0] == 'M') {
x2 = x2m = pj[1]
y2 = y2m = pj[2]
@ -478,11 +465,11 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
x2 = x2m
y2 = y2m
}
var intr = interHelper(bez1, bez2, justCount)
let intr = interHelper(bez1, bez2, justCount)
if (justCount) {
res += intr
} else {
for (var k = 0, kk = intr.length; k < kk; k++) {
for (let k = 0, kk = intr.length; k < kk; k++) {
intr[k].segment1 = i
intr[k].segment2 = j
intr[k].bez1 = bez1
@ -497,7 +484,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return res
}
function isPointInsidePath(path, x, y) {
var bbox = pathBBox(path)
let bbox = pathBBox(path)
return (
isPointInsideBBox(bbox, x, y) &&
interPathHelper(
@ -513,7 +500,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
)
}
function pathBBox(path) {
var pth = paths(path)
let pth = paths(path)
if (pth.bbox) {
return clone(pth.bbox)
}
@ -521,12 +508,12 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return box()
}
path = path2curve(path)
var x = 0,
let x = 0,
y = 0,
X = [],
Y = [],
p
for (var i = 0, ii = path.length; i < ii; i++) {
for (let i = 0, ii = path.length; i < ii; i++) {
p = path[i]
if (p[0] == 'M') {
x = p[1]
@ -534,14 +521,14 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
X.push(x)
Y.push(y)
} else {
var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6])
let dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6])
X = X.concat(dim.min.x, dim.max.x)
Y = Y.concat(dim.min.y, dim.max.y)
x = p[5]
y = p[6]
}
}
var xmin = mmin.apply(0, X),
let xmin = mmin.apply(0, X),
ymin = mmin.apply(0, Y),
xmax = mmax.apply(0, X),
ymax = mmax.apply(0, Y),
@ -564,7 +551,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
['z']
]
}
var res = [['M', x, y], ['l', w, 0], ['l', 0, h], ['l', -w, 0], ['z']]
let res = [['M', x, y], ['l', w, 0], ['l', 0, h], ['l', -w, 0], ['z']]
res.toString = toString
return res
}
@ -577,7 +564,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
rx = +rx
ry = +ry
if (a != null) {
var rad = Math.PI / 180,
let rad = Math.PI / 180,
x1 = x + rx * Math.cos(-ry * rad),
x2 = x + rx * Math.cos(-a * rad),
y1 = y + rx * Math.sin(-ry * rad),
@ -598,21 +585,20 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
res.toString = toString
return res
}
var unit2px = Snap._unit2px,
getPath = {
let getPath = {
path: function (el) {
return el.attr('path')
},
circle: function (el) {
var attr = unit2px(el)
let attr = unit2px(el)
return ellipsePath(attr.cx, attr.cy, attr.r)
},
ellipse: function (el) {
var attr = unit2px(el)
let attr = unit2px(el)
return ellipsePath(attr.cx || 0, attr.cy || 0, attr.rx, attr.ry)
},
rect: function (el) {
var attr = unit2px(el)
let attr = unit2px(el)
return rectPath(
attr.x || 0,
attr.y || 0,
@ -623,7 +609,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
)
},
image: function (el) {
var attr = unit2px(el)
let attr = unit2px(el)
return rectPath(attr.x || 0, attr.y || 0, attr.width, attr.height)
},
line: function (el) {
@ -639,23 +625,20 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return 'M' + el.attr('points') + 'z'
},
deflt: function (el) {
var bbox = el.node.getBBox()
let bbox = el.node.getBBox()
return rectPath(bbox.x, bbox.y, bbox.width, bbox.height)
}
}
function pathToRelative(pathArray) {
var pth = paths(pathArray),
let pth = paths(pathArray),
lowerCase = String.prototype.toLowerCase
if (pth.rel) {
return pathClone(pth.rel)
}
if (
!Snap.is(pathArray, 'array') ||
!Snap.is(pathArray && pathArray[0], 'array')
) {
if (!is(pathArray, 'array') || !is(pathArray && pathArray[0], 'array')) {
pathArray = Snap.parsePathString(pathArray)
}
var res = [],
let res = [],
x = 0,
y = 0,
mx = 0,
@ -669,8 +652,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
start++
res.push(['M', x, y])
}
for (var i = start, ii = pathArray.length; i < ii; i++) {
var r = (res[i] = []),
for (let i = start, ii = pathArray.length; i < ii; i++) {
let r = (res[i] = []),
pa = pathArray[i]
if (pa[0] != lowerCase.call(pa[0])) {
r[0] = lowerCase.call(pa[0])
@ -691,7 +674,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
mx = pa[1]
my = pa[2]
default:
for (var j = 1, jj = pa.length; j < jj; j++) {
for (let j = 1, jj = pa.length; j < jj; j++) {
r[j] = +(pa[j] - (j % 2 ? x : y)).toFixed(3)
}
}
@ -701,11 +684,11 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
mx = pa[1] + x
my = pa[2] + y
}
for (var k = 0, kk = pa.length; k < kk; k++) {
for (let k = 0, kk = pa.length; k < kk; k++) {
res[i][k] = pa[k]
}
}
var len = res[i].length
let len = res[i].length
switch (res[i][0]) {
case 'z':
x = mx
@ -727,7 +710,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return res
}
function pathToAbsolute(pathArray) {
var pth = paths(pathArray)
let pth = paths(pathArray)
if (pth.abs) {
return pathClone(pth.abs)
}
@ -738,7 +721,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (!pathArray || !pathArray.length) {
return [['M', 0, 0]]
}
var res = [],
let res = [],
x = 0,
y = 0,
mx = 0,
@ -753,12 +736,12 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
start++
res[0] = ['M', x, y]
}
var crz =
let crz =
pathArray.length == 3 &&
pathArray[0][0] == 'M' &&
pathArray[1][0].toUpperCase() == 'R' &&
pathArray[2][0].toUpperCase() == 'Z'
for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) {
for (let r, pa, i = start, ii = pathArray.length; i < ii; i++) {
res.push((r = []))
pa = pathArray[i]
pa0 = pa[0]
@ -781,8 +764,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
r[1] = +pa[1] + x
break
case 'R':
var dots = [x, y].concat(pa.slice(1))
for (var j = 2, jj = dots.length; j < jj; j++) {
let dots = [x, y].concat(pa.slice(1))
for (let j = 2, jj = dots.length; j < jj; j++) {
dots[j] = +dots[j] + x
dots[++j] = +dots[j] + y
}
@ -823,7 +806,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3]))
r = ['U'].concat(res[res.length - 1].slice(-2))
} else {
for (var k = 0, kk = pa.length; k < kk; k++) {
for (let k = 0, kk = pa.length; k < kk; k++) {
r[k] = pa[k]
}
}
@ -857,7 +840,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return [x1, y1, x2, y2, x2, y2]
}
function q2c(x1, y1, ax, ay, x2, y2) {
var _13 = 1 / 3,
let _13 = 1 / 3,
_23 = 2 / 3
return [
_13 * x1 + _23 * ax,
@ -882,12 +865,12 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
) {
// for more information of where this math came from visit:
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
var _120 = (PI * 120) / 180,
let _120 = (PI * 120) / 180,
rad = (PI / 180) * (+angle || 0),
res = [],
xy,
rotate = Snap._.cacher(function (x, y, rad) {
var X = x * math.cos(rad) - y * math.sin(rad),
rotate = cacher(function (x, y, rad) {
let X = x * math.cos(rad) - y * math.sin(rad),
Y = x * math.sin(rad) + y * math.cos(rad)
return { x: X, y: Y }
})
@ -901,17 +884,17 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
xy = rotate(x2, y2, -rad)
x2 = xy.x
y2 = xy.y
var cos = math.cos((PI / 180) * angle),
let cos = math.cos((PI / 180) * angle),
sin = math.sin((PI / 180) * angle),
x = (x1 - x2) / 2,
y = (y1 - y2) / 2
var h = (x * x) / (rx * rx) + (y * y) / (ry * ry)
let h = (x * x) / (rx * rx) + (y * y) / (ry * ry)
if (h > 1) {
h = math.sqrt(h)
rx = h * rx
ry = h * ry
}
var rx2 = rx * rx,
let rx2 = rx * rx,
ry2 = ry * ry,
k =
(large_arc_flag == sweep_flag ? -1 : 1) *
@ -942,9 +925,9 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
cx = recursive[2]
cy = recursive[3]
}
var df = f2 - f1
let df = f2 - f1
if (abs(df) > _120) {
var f2old = f2,
let f2old = f2,
x2old = x2,
y2old = y2
f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1)
@ -958,7 +941,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
])
}
df = f2 - f1
var c1 = math.cos(f1),
let c1 = math.cos(f1),
s1 = math.sin(f1),
c2 = math.cos(f2),
s2 = math.sin(f2),
@ -975,8 +958,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return [m2, m3, m4].concat(res)
} else {
res = [m2, m3, m4].concat(res).join().split(',')
var newres = []
for (var i = 0, ii = res.length; i < ii; i++) {
let newres = []
for (let i = 0, ii = res.length; i < ii; i++) {
newres[i] =
i % 2
? rotate(res[i - 1], res[i], rad).y
@ -986,7 +969,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
}
function findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) {
var t1 = 1 - t
let t1 = 1 - t
return {
x:
pow(t1, 3) * p1x +
@ -1006,7 +989,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
// Original version: NISHIO Hirokazu
// Modifications: https://github.com/timo22345
function curveDim(x0, y0, x1, y1, x2, y2, x3, y3) {
var tvalues = [],
let tvalues = [],
bounds = [[], []],
a,
b,
@ -1016,7 +999,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
t2,
b2ac,
sqrtb2ac
for (var i = 0; i < 2; ++i) {
for (let i = 0; i < 2; ++i) {
if (i == 0) {
b = 6 * x0 - 12 * x1 + 6 * x2
a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3
@ -1051,7 +1034,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
}
var x,
let x,
y,
j = tvalues.length,
jlen = j,
@ -1084,16 +1067,16 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
function path2curve(path, path2) {
var pth = !path2 && paths(path)
let pth = !path2 && paths(path)
if (!path2 && pth.curve) {
return pathClone(pth.curve)
}
var p = pathToAbsolute(path),
let p = pathToAbsolute(path),
p2 = path2 && pathToAbsolute(path2),
attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null },
attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null },
processPath = function (path, d, pcom) {
var nx, ny
let nx, ny
if (!path) {
return ['C', d.x, d.y, d.x, d.y, d.x, d.y]
}
@ -1133,9 +1116,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
case 'Q':
d.qx = path[1]
d.qy = path[2]
path = ['C'].concat(
q2c(d.x, d.y, path[1], path[2], path[3], path[4])
)
path = ['C'].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4]))
break
case 'L':
path = ['C'].concat(l2c(d.x, d.y, path[1], path[2]))
@ -1155,7 +1136,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
fixArc = function (pp, i) {
if (pp[i].length > 7) {
pp[i].shift()
var pi = pp[i]
let pi = pp[i]
while (pi.length) {
pcoms1[i] = 'A' // if created multiple C:s, their original seg is saved
p2 && (pcoms2[i] = 'A') // the same as above
@ -1179,7 +1160,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
pcoms2 = [], // path commands of original path p2
pfirst = '', // temporary holder for original path command
pcom = '' // holder for previous path command of original path
for (var i = 0, ii = mmax(p.length, (p2 && p2.length) || 0); i < ii; i++) {
for (let i = 0, ii = mmax(p.length, (p2 && p2.length) || 0); i < ii; i++) {
p[i] && (pfirst = p[i][0]) // save current path command
if (pfirst != 'C') {
@ -1212,7 +1193,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
}
fixM(p, p2, attrs, attrs2, i)
fixM(p2, p, attrs2, attrs, i)
var seg = p[i],
let seg = p[i],
seg2 = p2 && p2[i],
seglen = seg.length,
seg2len = p2 && seg2.length
@ -1234,7 +1215,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (!matrix) {
return path
}
var x, y, i, j, ii, jj, pathi
let x, y, i, j, ii, jj, pathi
path = path2curve(path)
for (i = 0, ii = path.length; i < ii; i++) {
pathi = path[i]
@ -1250,9 +1231,9 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
// http://schepers.cc/getting-to-the-point
function catmullRom2bezier(crp, z) {
var d = []
for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
var p = [
let d = []
for (let i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) {
let p = [
{ x: +crp[i - 2], y: +crp[i - 1] },
{ x: +crp[i], y: +crp[i + 1] },
{ x: +crp[i + 2], y: +crp[i + 3] },
@ -1335,11 +1316,11 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (this.getTotalLength(path) - to < 1e-6) {
return getSubpathsAtLength(path, from).end
}
var a = getSubpathsAtLength(path, to, 1)
let a = getSubpathsAtLength(path, to, 1)
return from ? getSubpathsAtLength(a, from).end : a
}
/*\
* Element.getTotalLength
* SnapElement.getTotalLength
[ method ]
**
* Returns the length of the path in pixels (only works for `path` elements)
@ -1350,9 +1331,9 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
return this.node.getTotalLength()
}
}
// SIERRA Element.getPointAtLength()/Element.getTotalLength(): If a <path> is broken into different segments, is the jump distance to the new coordinates set by the _M_ or _m_ commands calculated as part of the path's total length?
// SIERRA SnapElement.getPointAtLength()/SnapElement.getTotalLength(): If a <path> is broken into different segments, is the jump distance to the new coordinates set by the _M_ or _m_ commands calculated as part of the path's total length?
/*\
* Element.getPointAtLength
* SnapElement.getPointAtLength
[ method ]
**
* Returns coordinates of the point located at the given length on the given path (only works for `path` elements)
@ -1369,9 +1350,9 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
elproto.getPointAtLength = function (length) {
return getPointAtLength(this.attr('d'), length)
}
// SIERRA Element.getSubpath(): Similar to the problem for Element.getPointAtLength(). Unclear how this would work for a segmented path. Overall, the concept of _subpath_ and what I'm calling a _segment_ (series of non-_M_ or _Z_ commands) is unclear.
// SIERRA SnapElement.getSubpath(): Similar to the problem for SnapElement.getPointAtLength(). Unclear how this would work for a segmented path. Overall, the concept of _subpath_ and what I'm calling a _segment_ (series of non-_M_ or _Z_ commands) is unclear.
/*\
* Element.getSubpath
* SnapElement.getSubpath
[ method ]
**
* Returns subpath of a given element from given start and end lengths (only works for `path` elements)
@ -1467,7 +1448,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
\*/
Snap.path.isPointInsideBBox = isPointInsideBBox
Snap.closest = function (x, y, X, Y) {
var r = 100,
let r = 100,
b = box(x - r / 2, y - r / 2, r, r),
inside = [],
getter = X[0].hasOwnProperty('x')
@ -1485,8 +1466,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
},
found = 0
while (r <= 1e6 && !found) {
for (var i = 0, ii = X.length; i < ii; i++) {
var xy = getter(i)
for (let i = 0, ii = X.length; i < ii; i++) {
let xy = getter(i)
if (isPointInsideBBox(b, xy.x, xy.y)) {
found++
inside.push(xy)
@ -1501,10 +1482,10 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
if (r == 1e6) {
return
}
var len = Infinity,
let len = Infinity,
res
for (i = 0, ii = inside.length; i < ii; i++) {
var l = Snap.len(x, y, inside[i].x, inside[i].y)
let l = Snap.len(x, y, inside[i].x, inside[i].y)
if (len > l) {
len = l
inside[i].len = l
@ -1630,4 +1611,3 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
Snap.path.map = mapPath
Snap.path.toString = toString
Snap.path.clone = pathClone
})

View File

@ -12,21 +12,21 @@
// See the License for the specific language governing permissions and
// limitations under the License.
import eve from './eve.js'
import { Snap } from './svg.js'
import { Snap, SnapElement, Paper, Fragment } from './svg.js'
import mina from './mina.js'
import { is } from './utils.js'
Snap.plugin(function (Snap, Element, Paper, glob) {
var mmax = Math.max,
let mmax = Math.max,
mmin = Math.min
// Set
var Set = function (items) {
let Set = function (items) {
this.items = []
this.bindings = {}
this.length = 0
this.type = 'set'
if (items) {
for (var i = 0, ii = items.length; i < ii; i++) {
for (let i = 0, ii = items.length; i < ii; i++) {
if (items[i]) {
this[this.items.length] = this.items[this.items.length] = items[i]
this.length++
@ -43,8 +43,8 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
= (object) original element
\*/
setproto.push = function () {
var item, len
for (var i = 0, ii = arguments.length; i < ii; i++) {
let item, len
for (let i = 0, ii = arguments.length; i < ii; i++) {
item = arguments[i]
if (item) {
len = this.items.length
@ -78,7 +78,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
= (object) Set object
\*/
setproto.forEach = function (callback, thisArg) {
for (var i = 0, ii = this.items.length; i < ii; i++) {
for (let i = 0, ii = this.items.length; i < ii; i++) {
if (callback.call(thisArg, this.items[i], i) === false) {
return this
}
@ -104,7 +104,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
| // or
| // animate first element to radius 10, but second to radius 20 and in different time
| set.animate([{r: 10}, 500, mina.easein], [{r: 20}, 1500, mina.easein]);
= (Element) the current element
= (SnapElement) the current element
\*/
setproto.animate = function (attrs, ms, easing, callback) {
if (typeof easing == 'function' && !easing.length) {
@ -117,11 +117,11 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
ms = easing.dur
attrs = attrs.attr
}
var args = arguments
if (Snap.is(attrs, 'array') && Snap.is(args[args.length - 1], 'array')) {
var each = true
let args = arguments
if (is(attrs, 'array') && is(args[args.length - 1], 'array')) {
let each = true
}
var begin,
let begin,
handler = function () {
if (begin) {
this.b = begin
@ -173,19 +173,19 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
- callback (function) function to run
* or
- attr (string) attribute name
- element (Element) specific element in the set to apply the attribute to
- element (SnapElement) specific element in the set to apply the attribute to
* or
- attr (string) attribute name
- element (Element) specific element in the set to apply the attribute to
- element (SnapElement) specific element in the set to apply the attribute to
- eattr (string) attribute on the element to bind the attribute to
= (object) Set object
\*/
setproto.bind = function (attr, a, b) {
var data = {}
let data = {}
if (typeof a == 'function') {
this.bindings[attr] = a
} else {
var aname = b || attr
let aname = b || attr
this.bindings[attr] = function (v) {
data[aname] = v
a.attr(data)
@ -197,19 +197,19 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
* Set.attr
[ method ]
**
* Equivalent of @Element.attr.
* Equivalent of @SnapElement.attr.
= (object) Set object
\*/
setproto.attr = function (value) {
var unbound = {}
for (var k in value) {
let unbound = {}
for (let k in value) {
if (this.bindings[k]) {
this.bindings[k](value[k])
} else {
unbound[k] = value[k]
}
}
for (var i = 0, ii = this.items.length; i < ii; i++) {
for (let i = 0, ii = this.items.length; i < ii; i++) {
this.items[i].attr(unbound)
}
return this
@ -239,7 +239,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
setproto.splice = function (index, count, insertion) {
index = index < 0 ? mmax(this.length + index, 0) : index
count = mmax(0, mmin(this.length - index, count))
var tail = [],
let tail = [],
todel = [],
args = [],
i
@ -252,7 +252,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
for (; i < this.length - index; i++) {
tail.push(this[index + i])
}
var arglen = args.length
let arglen = args.length
for (i = 0; i < arglen + tail.length; i++) {
this.items[index + i] = this[index + i] =
i < arglen ? args[i] : tail[i - arglen]
@ -273,7 +273,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
= (boolean) `true` if object was found and removed from the set
\*/
setproto.exclude = function (el) {
for (var i = 0, ii = this.length; i < ii; i++)
for (let i = 0, ii = this.length; i < ii; i++)
if (this[i] == el) {
this.splice(i, 1)
return true
@ -290,7 +290,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
= (object) Set object
\*/
setproto.insertAfter = function (el) {
var i = this.items.length
let i = this.items.length
while (i--) {
this.items[i].insertAfter(el)
}
@ -300,17 +300,17 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
* Set.getBBox
[ method ]
**
* Union of all bboxes of the set. See @Element.getBBox.
= (object) bounding box descriptor. See @Element.getBBox.
* Union of all bboxes of the set. See @SnapElement.getBBox.
= (object) bounding box descriptor. See @SnapElement.getBBox.
\*/
setproto.getBBox = function () {
var x = [],
let x = [],
y = [],
x2 = [],
y2 = []
for (var i = this.items.length; i--; )
for (let i = this.items.length; i--; )
if (!this.items[i].removed) {
var box = this.items[i].getBBox()
let box = this.items[i].getBBox()
x.push(box.x)
y.push(box.y)
x2.push(box.x + box.width)
@ -341,7 +341,7 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
\*/
setproto.clone = function (s) {
s = new Set()
for (var i = 0, ii = this.items.length; i < ii; i++) {
for (let i = 0, ii = this.items.length; i < ii; i++) {
s.push(this.items[i].clone())
}
return s
@ -365,15 +365,14 @@ Snap.plugin(function (Snap, Element, Paper, glob) {
* Creates a set and fills it with list of arguments.
**
= (object) New Set object
| var r = paper.rect(0, 0, 10, 10),
| let r = paper.rect(0, 0, 10, 10),
| s1 = Snap.set(), // empty set
| s2 = Snap.set(r, paper.circle(100, 100, 20)); // prefilled set
\*/
Snap.set = function () {
var set = new Set()
let set = new Set()
if (arguments.length) {
set.push.apply(set, Array.prototype.slice.call(arguments, 0))
}
return set
}
})

2123
src/svg.js

File diff suppressed because it is too large Load Diff

154
src/utils.js Normal file
View File

@ -0,0 +1,154 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2024/03/06 09:55:31
*/
import { xlink, xmlns, doc, win } from './lib/constants.js'
export function uuid(prefix = '') {
return prefix + Math.random().toString(16).slice(-8)
}
export function is(o, type) {
type = String(type).toLowerCase()
let _type = Object.prototype.toString.call(o).slice(8, -1).toLowerCase()
if (type === 'finite') {
return isFinite(o)
}
if (type === 'array' && Array.isArray(o)) {
return true
}
return (
(type === 'null' && o === null) ||
(type === typeof o && o !== null) ||
(type === 'object' && o === Object(o)) ||
_type === type
)
}
export function $(el, attr) {
if (attr) {
if (el == '#text') {
el = doc.createTextNode(attr.text || attr['#text'] || '')
}
if (el == '#comment') {
el = doc.createComment(attr.text || attr['#text'] || '')
}
if (typeof el == 'string') {
el = $(el)
}
if (typeof attr == 'string') {
if (el.nodeType == 1) {
if (attr.slice(0, 6) == 'xlink:') {
return el.getAttributeNS(xlink, attr.slice(6))
}
if (attr.slice(0, 4) == 'xml:') {
return el.getAttributeNS(xmlns, attr.slice(4))
}
return el.getAttribute(attr)
} else if (attr == 'text') {
return el.nodeValue
} else {
return null
}
}
if (el.nodeType == 1) {
for (let key in attr)
if (attr.hasOwnProperty(key)) {
let val = String(attr[key])
if (val) {
if (key.slice(0, 6) == 'xlink:') {
el.setAttributeNS(xlink, key.slice(6), val)
} else if (key.slice(0, 4) == 'xml:') {
el.setAttributeNS(xmlns, key.slice(4), val)
} else {
el.setAttribute(key, val)
}
} else {
el.removeAttribute(key)
}
}
} else if ('text' in attr) {
el.nodeValue = attr.text
}
} else {
el = doc.createElementNS(xmlns, el)
}
return el
}
export function clone(obj) {
if (typeof obj == 'function' || Object(obj) !== obj) {
return obj
}
let res = new obj.constructor()
for (let key in obj)
if (obj.hasOwnProperty(key)) {
res[key] = clone(obj[key])
}
return res
}
export function preload(src, f) {
let img = new Image()
img.onload = function () {
f.call(img)
}
img.src = src
}
function repush(arr, item) {
let l = arr.length - 1 // 要减1, 最后如果本身在最后, 不用变
for (let i = 0; i < l; i++) {
if (arr[i] === item) {
;[a[i], a[l]] = [a[l], a[i]]
break
}
}
}
export function cacher(fn, scope, postprocessor) {
function newf(...args) {
let key = args.join('\u2400'),
cache = (newf.cache = newf.cache || {}),
count = (newf.count = newf.count || [])
if (cache.hasOwnProperty(key)) {
repush(count, key)
return postprocessor ? postprocessor(cache[key]) : cache[key]
}
count.length >= 1e3 && delete cache[count.shift()]
count.push(key)
cache[key] = fn.apply(scope, args)
return postprocessor ? postprocessor(cache[key]) : cache[key]
}
return newf
}
export function jsonFiller(root, o) {
for (let i = 0, ii = root.length; i < ii; i++) {
let item = {
type: root[i].type,
attr: root[i].attr()
},
children = root[i].children()
o.push(item)
if (children.length) {
jsonFiller(children, (item.childNodes = []))
}
}
}
export function extend(origin, target) {
let methods = Object.getOwnPropertyNames(target).filter(
n => n !== 'constructor'
)
for (let k of methods) {
Object.defineProperty(origin, k, { value: target[k] })
}
}
export function url(id) {
return "url('#" + id + "')"
}