Skip to content

Add possibility to include a data attribute to text element. #1841

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/marks/text.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
6 changes: 5 additions & 1 deletion src/marks/text.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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)
Expand All @@ -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();
}
Expand Down