jama1017's picture
Initial commit
89592d6
Raw History Blame Contribute Delete
18.3 kB
// Observe SVG geometry and styles per node in root SVG coordinates.
;(opts) => {
const wantDiff = !!(opts && opts.wantDiff)
// Null reads all computed styles.
const styles = (opts && opts.styles) || null
const resourceStyles = (opts && opts.resourceStyles) || null
const reuseOutline = !(opts && opts.reuseOutline === false)
const r = (v) => Math.round(v * 1e4) / 1e4
const root = document.querySelector('svg')
if (!root) return { error: 'no <svg> in the document' }
const baseline = window.__baseline
if (wantDiff && !baseline) return { needsBaseline: true }
// Remove page layout from the measured coordinates.
const rootCTM = root.getScreenCTM()
const inv = rootCTM ? rootCTM.inverse() : null
const OUTLINE_SAMPLES = 32
// Definitions are not painted, even though <defs> is an SVGGraphicsElement.
const paints = (el) => el instanceof SVGGraphicsElement && el.tagName.toLowerCase() !== 'defs'
const styleOf = (el, properties = styles) => {
const cs = getComputedStyle(el)
const out = {}
if (properties) {
for (const k of properties) out[k] = cs.getPropertyValue(k)
return out
}
for (let i = 0; i < cs.length; i++) {
const k = cs[i]
out[k] = cs.getPropertyValue(k)
}
return out
}
// CSS geometry overrides SVG presentation attributes.
const OUTLINE_INPUTS = {
path: [['d'], []],
circle: [['cx', 'cy', 'r'], []],
ellipse: [['cx', 'cy', 'rx', 'ry'], []],
rect: [['x', 'y', 'width', 'height', 'rx', 'ry'], []],
line: [[], ['x1', 'y1', 'x2', 'y2']],
polyline: [[], ['points']],
polygon: [[], ['points']],
}
if (!window.__outline) window.__outline = {}
const outlineCache = window.__outline
const outlineSignature = (el, tag) => {
const inputs = OUTLINE_INPUTS[tag]
if (!inputs) return null
const cs = getComputedStyle(el)
let sig = tag
for (const k of inputs[0]) sig += '|' + cs.getPropertyValue(k)
for (const k of inputs[1]) sig += '|' + (el.getAttribute(k) || '')
return sig
}
const sampleOutline = (el, length, ends) => {
if (!ends) return null
if (length <= 0) return [ends[0]]
const closed = Math.hypot(ends[0][0] - ends[1][0], ends[0][1] - ends[1][1]) <= 1e-4
const divisor = OUTLINE_SAMPLES - 1
const points = []
for (let i = 0; i < OUTLINE_SAMPLES; i++) {
const p = el.getPointAtLength((length * i) / divisor)
points.push([r(p.x), r(p.y)])
}
if (closed) points[points.length - 1] = points[0]
return points
}
const placePoints = (points, matrix) => {
if (!points || !matrix) return null
return points.map(([x, y]) => [
r(matrix.a * x + matrix.c * y + matrix.e),
r(matrix.b * x + matrix.d * y + matrix.f),
])
}
// Fill interiors can remain visible when their outlines are clipped away.
const paintedSamples = (el, bbox, contour, matrix) => {
if (!matrix || !(el instanceof SVGGeometryElement)) return null
const cs = getComputedStyle(el)
const fillOpacity = parseFloat(cs.fillOpacity)
if (bbox && cs.fill !== 'none' && (!Number.isFinite(fillOpacity) || fillOpacity > 0)) {
const [x, y, width, height] = bbox
const points = []
for (let row = 0; row < 8; row++) {
for (let column = 0; column < 8; column++) {
const point = new DOMPoint(
x + (width * (column + 0.5)) / 8,
y + (height * (row + 0.5)) / 8,
)
if (el.isPointInFill(point)) points.push([point.x, point.y])
}
}
if (points.length) return placePoints(points, matrix)
}
const strokeOpacity = parseFloat(cs.strokeOpacity)
return cs.stroke !== 'none' && (!Number.isFinite(strokeOpacity) || strokeOpacity > 0)
? contour
: null
}
// Stroke width is approximate under nonuniform scale.
const linearScale = (matrix) =>
matrix ? Math.sqrt((matrix.a ** 2 + matrix.b ** 2 + matrix.c ** 2 + matrix.d ** 2) / 2) : null
const effectiveStrokeWidth = (el, matrix) => {
if (!matrix) return null
const cs = getComputedStyle(el)
const width = parseFloat(cs.strokeWidth)
const strokeOpacity = parseFloat(cs.strokeOpacity)
if (cs.stroke === 'none' || !Number.isFinite(width) || width <= 0 || strokeOpacity === 0)
return 0
const scale =
cs.vectorEffect === 'non-scaling-stroke' ? 1 / linearScale(rootCTM) : linearScale(matrix)
return Number.isFinite(scale) ? r(width * scale) : null
}
const definitionOf = (reference) => {
const found = /url\(["']?#([^"')]+)/.exec(reference || '')
return found ? document.getElementById(found[1]) : null
}
// Definition records describe inputs, not composited pixels.
const referenceStyles = [
'fill',
'stroke',
'filter',
'clip-path',
'mask-image',
'marker-start',
'marker-mid',
'marker-end',
]
const hrefTags = new Set([
'use',
'image',
'lineargradient',
'radialgradient',
'pattern',
'textpath',
'feimage',
'mpath',
])
const referencesOf = (el, cs) => {
const refs = new Set()
for (const property of referenceStyles) {
const value = cs.getPropertyValue(property)
for (const match of value.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*?))\s*\)/g)) {
refs.add((match[1] ?? match[2] ?? match[3]).trim())
}
}
if (hrefTags.has(el.tagName.toLowerCase())) {
const href = el.hasAttribute('href')
? el.getAttribute('href')
: el.getAttributeNS('http://www.w3.org/1999/xlink', 'href')
if (href) refs.add(href)
}
return refs
}
const resourceCache = new WeakMap()
const definitionTags = new Set([
'defs',
'mask',
'clippath',
'filter',
'lineargradient',
'radialgradient',
'pattern',
'marker',
'symbol',
])
const resourceNode = (el) => {
if (resourceCache.has(el)) return resourceCache.get(el)
const cs = getComputedStyle(el)
const attrs = Object.fromEntries(Array.from(el.attributes, (a) => [a.name, a.value]))
const style = styleOf(el, resourceStyles)
const children = Array.from(el.children)
// Include nested definitions only when referenced.
.filter(
(child) => child instanceof SVGElement && !definitionTags.has(child.tagName.toLowerCase()),
)
.map(resourceNode)
const refs = referencesOf(el, cs)
for (const child of children) for (const ref of child.refs) refs.add(ref)
const result = {
value: {
tag: el.tagName.toLowerCase(),
attrs,
style,
children: children.map((c) => c.value),
},
refs,
}
resourceCache.set(el, result)
return result
}
const resourceInputsOf = (el) => {
const inputs = Object.create(null)
const pending = Array.from(referencesOf(el, getComputedStyle(el)))
for (let i = 0; i < pending.length; i++) {
const reference = pending[i]
if (Object.hasOwn(inputs, reference)) continue
inputs[reference] = null // Unresolved references remain explicit.
let target = null
try {
const url = new URL(reference, document.baseURI)
if (url.hash && url.href.split('#')[0] === document.URL.split('#')[0]) {
target = document.getElementById(decodeURIComponent(url.hash.slice(1)))
}
} catch (e) {
/* malformed reference */
}
if (!(target instanceof SVGElement)) continue
const record = resourceNode(target)
inputs[reference] = record.value
pending.push(...record.refs)
}
return inputs
}
// Place definition bounds using the referencing element's transform.
const definitionBox = (el, reference) => {
const def = reference.includes(',') ? null : definitionOf(reference)
if (!def) return null
let box = null
for (const child of def.children) {
try {
const b = child.getBBox()
const one = { x0: b.x, y0: b.y, x1: b.x + b.width, y1: b.y + b.height }
box = box
? {
x0: Math.min(box.x0, one.x0),
y0: Math.min(box.y0, one.y0),
x1: Math.max(box.x1, one.x1),
y1: Math.max(box.y1, one.y1),
}
: one
} catch (e) {
/* a child with no box contributes nothing */
}
}
if (!box) return null
const m = el.getScreenCTM()
if (!m || !inv) return null
const l = inv.multiply(m)
const xs = [],
ys = []
for (const [x, y] of [
[box.x0, box.y0],
[box.x1, box.y0],
[box.x1, box.y1],
[box.x0, box.y1],
]) {
xs.push(l.a * x + l.c * y + l.e)
ys.push(l.b * x + l.d * y + l.f)
}
return { x0: Math.min(...xs), y0: Math.min(...ys), x1: Math.max(...xs), y1: Math.max(...ys) }
}
// Nonrectangular clip bounds can overestimate visible area.
const clipOf = (el) => definitionBox(el, getComputedStyle(el).clipPath)
// Hidden source nodes can produce unusable zero-area mask bounds.
const maskOf = (el) => {
const box = definitionBox(el, getComputedStyle(el).maskImage)
if (!box || box.x1 <= box.x0 || box.y1 <= box.y0) return null
return box
}
const chainTo = (el, one) => {
let box = null
for (let node = el; node && node.nodeType === 1; node = node.parentNode) {
const here = one(node)
if (!here) continue
box = box
? {
x0: Math.max(box.x0, here.x0),
y0: Math.max(box.y0, here.y0),
x1: Math.min(box.x1, here.x1),
y1: Math.min(box.y1, here.y1),
}
: here
}
return box ? [r(box.x0), r(box.y0), r(box.x1), r(box.y1)] : null
}
// Unsupported clip or mask constructs remain unmeasurable.
const constraintCache = new WeakMap()
const opaquePaint = (paint, opacity) => {
if (paint === 'none' || opacity === 0) return false
if (opacity !== 1 || paint.startsWith('url(')) return null
const rgba = /^rgba\([^,]+,[^,]+,[^,]+,\s*([\d.]+)\)$/.exec(paint)
if (!rgba) return true
const alpha = Number(rgba[1])
return alpha === 0 ? false : alpha === 1 ? true : null
}
const constraintOf = (el, kind, reference) => {
const cached = constraintCache.get(el) || {}
if (kind in cached) return cached[kind]
const def = reference.includes(',') ? null : definitionOf(reference)
let checker = null
if (
def &&
((kind === 'clip' && def.tagName.toLowerCase() === 'clippath') ||
(kind === 'mask' && def.tagName.toLowerCase() === 'mask'))
) {
const unit = kind === 'clip' ? def.clipPathUnits : def.maskContentUnits
const binaryAlphaMask =
kind !== 'mask' ||
((def.getAttribute('mask-type') || getComputedStyle(def).maskType) === 'alpha' &&
!['x', 'y', 'width', 'height'].some((name) => def.hasAttribute(name)))
const descendants = Array.from(def.querySelectorAll('*'))
const allowedContainers = new Set(['g', 'a', 'switch', 'title', 'desc', 'metadata'])
const unsupportedNode = descendants.some(
(node) =>
!(node instanceof SVGGeometryElement) &&
!allowedContainers.has(node.tagName.toLowerCase()),
)
const shapes = descendants.filter((node) => node instanceof SVGGeometryElement)
const placed = []
const ref = (() => {
try {
const m = el.getScreenCTM()
return m && inv ? inv.multiply(m) : null
} catch (e) {
return null
}
})()
let supported = !!unit && unit.baseVal === 1 && binaryAlphaMask && !unsupportedNode && !!ref
for (const shape of shapes) {
const cs = getComputedStyle(shape)
if (cs.display === 'none' || cs.visibility === 'hidden') continue
if (kind === 'clip' && cs.clipRule !== cs.fillRule) supported = false
let ancestor = shape
let opaque = true
while (ancestor && ancestor !== def) {
const style = getComputedStyle(ancestor)
const opacity = parseFloat(style.opacity)
if (kind === 'clip' && style.clipPath !== 'none') supported = false
if (
(Number.isFinite(opacity) && opacity !== 1) ||
style.filter !== 'none' ||
style.clipPath !== 'none' ||
style.maskImage !== 'none'
)
opaque = false
ancestor = ancestor.parentNode
}
const fillOpacity = parseFloat(cs.fillOpacity)
const strokeOpacity = parseFloat(cs.strokeOpacity)
const fillState = opaquePaint(cs.fill, fillOpacity)
const strokeState = opaquePaint(cs.stroke, strokeOpacity)
const fill = fillState === true
const stroke = strokeState === true
if (kind === 'mask' && (!opaque || fillState === null || strokeState === null))
supported = false
try {
const m = shape.getScreenCTM()
if (!m || !inv || !ref) {
supported = false
continue
}
const inverse = ref.multiply(inv.multiply(m)).inverse()
if (
![inverse.a, inverse.b, inverse.c, inverse.d, inverse.e, inverse.f].every(
Number.isFinite,
)
) {
supported = false
continue
}
placed.push({
shape,
inverse,
fill: kind === 'clip' || fill,
stroke: kind === 'mask' && stroke,
})
} catch (e) {
supported = false
}
}
if (supported) {
checker = ([x, y]) =>
placed.some(({ shape, inverse, fill, stroke }) => {
const point = new DOMPoint(
inverse.a * x + inverse.c * y + inverse.e,
inverse.b * x + inverse.d * y + inverse.f,
)
return (fill && shape.isPointInFill(point)) || (stroke && shape.isPointInStroke(point))
})
}
}
cached[kind] = checker
constraintCache.set(el, cached)
return checker
}
const visibleFractionOf = (el, bbox, contour, matrix) => {
if (!contour || !contour.length) return null
const constraints = []
for (let node = el; node && node.nodeType === 1; node = node.parentNode) {
const cs = getComputedStyle(node)
for (const [kind, reference] of [
['clip', cs.clipPath],
['mask', cs.maskImage],
]) {
if (!reference || reference === 'none') continue
const checker = constraintOf(node, kind, reference)
if (!checker) return null
constraints.push(checker)
}
}
if (!constraints.length) return 1
const samples = paintedSamples(el, bbox, contour, matrix)
if (!samples || !samples.length) return null
return r(
samples.filter((point) => constraints.every((checker) => checker(point))).length /
samples.length,
)
}
const rows = []
let order = 0
const walk = (el, parentPath) => {
const tag = el.tagName.toLowerCase()
if (!paints(el)) return
const sameTag =
parentPath === null
? []
: Array.from(el.parentNode.children).filter((c) => c.tagName.toLowerCase() === tag)
const idx = sameTag.indexOf(el)
const seg = parentPath === null ? tag : `${tag}[${idx}]`
const path = parentPath === null ? seg : `${parentPath}/${seg}`
let ctm = null
let rootMatrix = null
try {
const m = el.getScreenCTM()
if (m && inv) {
const l = inv.multiply(m)
rootMatrix = l
ctm = [r(l.a), r(l.b), r(l.c), r(l.d), r(l.e), r(l.f)]
}
} catch (e) {
ctm = null
}
// CSS transforms are recorded separately from the transform attribute.
let own = [1, 0, 0, 1, 0, 0]
try {
const c = el.transform.baseVal.consolidate()
if (c)
own = [
r(c.matrix.a),
r(c.matrix.b),
r(c.matrix.c),
r(c.matrix.d),
r(c.matrix.e),
r(c.matrix.f),
]
} catch (e) {
own = null
}
let bbox = null
try {
const b = el.getBBox()
bbox = [r(b.x), r(b.y), r(b.width), r(b.height)]
} catch (e) {
bbox = null
}
let length = null
let ends = null
let localContour = null
try {
if (typeof el.getTotalLength === 'function') {
// Cached geometry excludes transforms, which are applied afterward.
const sig = reuseOutline ? outlineSignature(el, tag) : null
const cached = sig === null ? null : outlineCache[path]
if (cached && cached.sig === sig && cached.contour) {
length = cached.length
ends = cached.ends
localContour = cached.contour
} else {
length = r(el.getTotalLength())
const a = el.getPointAtLength(0)
const b = el.getPointAtLength(length)
ends = [
[r(a.x), r(a.y)],
[r(b.x), r(b.y)],
]
localContour = sampleOutline(el, length, ends)
if (sig !== null) outlineCache[path] = { sig, length, ends, contour: localContour }
}
}
} catch (e) {
length = null
ends = null
localContour = null
}
const contour = placePoints(localContour, rootMatrix)
const strokeWidth = effectiveStrokeWidth(el, rootMatrix)
const attrs = {}
for (const a of el.attributes) attrs[a.name] = a.value
const full = styleOf(el)
let style = full
if (baseline) {
const base = baseline[path] || {}
style = {}
for (const k in full) if (full[k] !== base[k]) style[k] = full[k]
}
rows.push({
path,
tag,
parent: parentPath,
order: order++,
ctm,
own,
bbox,
length,
ends,
contour,
stroke_width: strokeWidth,
visible_fraction: visibleFractionOf(el, bbox, contour, rootMatrix),
clip_box: chainTo(el, clipOf),
mask_box: chainTo(el, maskOf),
resource_inputs: resourceInputsOf(el),
attrs,
style,
})
for (const child of el.children) walk(child, path)
}
walk(root, null)
const vb = root.getAttribute('viewBox')
return {
rows,
canvas: {
viewBox: vb
? vb
.trim()
.split(/[\s,]+/)
.map(Number)
: null,
width: root.getAttribute('width'),
height: root.getAttribute('height'),
},
}
}