From d76a085ad34a80d8b0483343d38d35737b4aea9a Mon Sep 17 00:00:00 2001 From: skanaar Date: Sat, 14 Dec 2024 08:57:15 +0100 Subject: [PATCH] add data-compartment attribute to svg output --- src/GraphicsSvg.ts | 9 +++++++-- src/renderer.ts | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/GraphicsSvg.ts b/src/GraphicsSvg.ts index b6087ed..8751eaa 100644 --- a/src/GraphicsSvg.ts +++ b/src/GraphicsSvg.ts @@ -102,7 +102,7 @@ export function GraphicsSvg(document?: HTMLDocument): ISvgGraphics { return this.parent } serialize(): string { - const data = getDefined(this.group(), (e) => e.data) ?? {} + const data = getAncestorData(this.group()) ?? {} const attrs = toAttrString({ ...this.attr, ...data }) const content = this.children.map((o) => o.serialize()).join('\n') if (this.text && this.children.length === 0) @@ -116,6 +116,11 @@ export function GraphicsSvg(document?: HTMLDocument): ISvgGraphics { } } + function getAncestorData(group: GroupElement | undefined): Record | undefined { + if (!group) return syntheticRoot.data + return { ...getAncestorData(group.parent), ...group.data } + } + function getDefined( group: GroupElement | undefined, getter: (e: GroupElement) => T | undefined @@ -129,7 +134,7 @@ export function GraphicsSvg(document?: HTMLDocument): ISvgGraphics { super('g', {}, parent) } elideEmpty = true - data: Record + data: Record | undefined group() { return this } diff --git a/src/renderer.ts b/src/renderer.ts index 64a3ecc..2c8b0d1 100644 --- a/src/renderer.ts +++ b/src/renderer.ts @@ -58,6 +58,7 @@ export function render(graphics: Graphics, config: Config, compartment: Layouted g.save() g.setData('name', node.id) + g.setData('compartment', undefined) g.save() g.fillStyle(style.fill || config.fill[level] || last(config.fill)) @@ -73,9 +74,11 @@ export function render(graphics: Graphics, config: Config, compartment: Layouted } g.restore() + let partIndex = 0 for (let part of node.parts) { const textStyle = part === node.parts[0] ? style.title : style.body g.save() + g.setData('compartment', String(partIndex)) g.translate(x + part.x!, y + part.y!) g.setFont( config.font, @@ -84,6 +87,7 @@ export function render(graphics: Graphics, config: Config, compartment: Layouted textStyle.italic ? 'italic' : 'normal' ) renderCompartment(part, style.stroke, textStyle, level + 1) + partIndex++ g.restore() }