app_mapbuilder/svgmap/svg-node.js
2022-04-22 18:34:31 +05:00

70 lines
2.0 KiB
JavaScript

class SvgNode {
constructor(tag, attrs, items) {
this.tag = tag
this.attrs = attrs || {}
this.items = items || []
}
append(...items){
this.items.push(...items)
return this
}
set_attr(attr, value) {
this.attrs[attr] = value
return this
}
set_attrs(attrs) {
this.attrs = { ...this.attrs, ...attrs }
return this
}
add_style(style) {
this.style = { ...this.style || {}, ...style }
return this
}
clear_style() {
this.style = null
return this
}
move(x, y) {
if (this.transform)
this.transform = { x: this.transform.x + x, y: this.transform.y + y }
else
this.transform = { x, y }
return this
}
get(attr) {
}
_render_node(node) {
// console.log(typeof node)
// if (typeof node == 'undefined') return ''
if (typeof node == 'string') return node
else if (typeof node == 'object' && node.tag) return node.render()
else if (Array.isArray(node)) return node.map(this._render_node).join('')
else return ''
}
render() {
let attrs = Object.keys(this.attrs).filter(x => this.attrs[x]).map(x => ` ${x}="${this.attrs[x]}"`).join('')
// console.log(this.style ? Object.keys(this.style).map(x => `${x}:${this.style[x]}`) : '')
let style = this.style ? ' style="' + Object.keys(this.style).map(x => `${x}:${this.style[x]}`).join('; ') + '"' : ''
let transfrom = this.transform ? ` transform="translate(${this.transform.x},${this.transform.y})"` : ''
let items = this.items ? this.items.map(x => this._render_node(x)).join('') : ''
// console.log('this.items', this.items, items)
if (this.tag)
return `<${this.tag}${attrs}${style}${transfrom}>${items}</${this.tag}>`
else
return items
}
}
module.exports = SvgNode
module.exports.default = module.exports;