From 7de3aa9f867733eab5f24366f0fca649607ee400 Mon Sep 17 00:00:00 2001 From: John Pettersson <> Date: Tue, 29 Aug 2023 21:58:26 +0200 Subject: [PATCH] Add possibility to include a data attribute to text element. --- src/marks/text.d.ts | 7 +++++++ src/marks/text.js | 6 +++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/marks/text.d.ts b/src/marks/text.d.ts index 8ad171cfbb..0378b00054 100644 --- a/src/marks/text.d.ts +++ b/src/marks/text.d.ts @@ -151,6 +151,13 @@ export interface TextOptions extends MarkOptions, TextStyles { * interpreted as a channel. */ rotate?: ChannelValue; + + /** + * Add a data attribute to the text node, which could be used for targeting with CSS. + * If a string is provided the data attribute key will be "data-text", + * for more control provide an array with the attribute name and value, e.g. ["data-name", "my-text"]. + */ + dataAttr?: string | [`data-${string}`, string]; } /** Options for the textX mark. */ diff --git a/src/marks/text.js b/src/marks/text.js index c7feb36bfe..dfb565d23f 100644 --- a/src/marks/text.js +++ b/src/marks/text.js @@ -56,7 +56,8 @@ export class Text extends Mark { fontStyle, fontVariant, fontWeight, - rotate + rotate, + dataAttr } = options; const [vrotate, crotate] = maybeNumberChannel(rotate, 0); const [vfontSize, cfontSize] = maybeFontSizeChannel(fontSize); @@ -88,11 +89,13 @@ export class Text extends Mark { if (!(this.lineWidth >= 0)) throw new Error(`invalid lineWidth: ${lineWidth}`); this.splitLines = splitter(this); this.clipLine = clipper(this); + this.dataAttr = dataAttr; } render(index, scales, channels, dimensions, context) { const {x, y} = scales; const {x: X, y: Y, rotate: R, text: T, title: TL, fontSize: FS} = channels; const {rotate} = this; + const [dataAttrKey, dataAttrValue] = Array.isArray(this.dataAttr) ? this.dataAttr : ["data-text", this.dataAttr]; const [cx, cy] = applyFrameAnchor(this, dimensions); return create("svg:g", context) .call(applyIndirectStyles, this, dimensions, context) @@ -114,6 +117,7 @@ export class Text extends Mark { ) .call(applyAttr, "font-size", FS && ((i) => FS[i])) .call(applyChannelStyles, this, channels) + .call(applyAttr, dataAttrKey, dataAttrValue) ) .node(); }