Skip to content

Commit

Permalink
feat(data.labels): Intent to ship data.labels.backgroundColors
Browse files Browse the repository at this point in the history
Implementation for new data.labels.backgroundColors option

Fix #1954
  • Loading branch information
netil committed Jun 7, 2021
1 parent bd02d72 commit e0b2fed
Show file tree
Hide file tree
Showing 9 changed files with 162 additions and 4 deletions.
6 changes: 5 additions & 1 deletion demo/demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -1927,7 +1927,7 @@ var demos = {
];
}
},
"DataFromURL": {
DataFromURL: {
options: {
data: {
url: "./data/test.csv",
Expand Down Expand Up @@ -2262,6 +2262,7 @@ var demos = {
],
type: "bar",
labels: {
backgroundColors: "yellow",
colors: "red"
}
}
Expand All @@ -2276,6 +2277,9 @@ var demos = {
],
type: "line",
labels: {
backgroundColors: {
data1: "rgba(0, 0, 0, 0.2)"
},
colors: {
data1: "fuchsia",
data2: "blue"
Expand Down
5 changes: 4 additions & 1 deletion src/ChartInternal/ChartInternal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ export default class ChartInternal {
// Define defs
const hasColorPatterns = (isFunction(config.color_tiles) && $$.patterns);

if (hasAxis || hasColorPatterns) {
if (hasAxis || hasColorPatterns || config.data_labels_backgroundColors) {
$el.defs = $el.svg.append("defs");

if (hasAxis) {
Expand All @@ -342,6 +342,9 @@ export default class ChartInternal {
});
}

// Append data backgound color filter definition
$$.generateDataLabelBackgroundColorFilter();

// set color patterns
if (hasColorPatterns) {
$$.patterns.forEach(p => $el.defs.append(() => p.node));
Expand Down
9 changes: 9 additions & 0 deletions src/ChartInternal/data/IData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,12 @@ export interface IData {
id_org: string;
values: IDataRow[];
}

export interface IArcData {
data: IData;
index: number;
padAngle: number;
startAngle: number;
endAngle: number;
value: number;
}
32 changes: 32 additions & 0 deletions src/ChartInternal/internals/color.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,38 @@ export default {
} : null;
},

/**
* Append data backgound color filter definition
* @private
*/
generateDataLabelBackgroundColorFilter(): void {
const $$ = this;
const {$el, config, state} = $$;
const backgroundColors = config.data_labels_backgroundColors;

if (backgroundColors) {
let ids: string[] = [];

if (isString(backgroundColors)) {
ids.push("");
} else if (isObject(backgroundColors)) {
ids = Object.keys(backgroundColors);
}

ids.forEach(v => {
const id = `${state.datetimeId}-labels-bg-${v}`;

$el.defs.append("filter")
.attr("x", "0")
.attr("y", "0")
.attr("width", "1")
.attr("height", "1")
.attr("id", id)
.html(`<feFlood flood-color="${v === "" ? backgroundColors : backgroundColors[v]}" /><feComposite in="SourceGraphic"/>`);
});
}
},

/**
* Set the data over color.
* When is out, will restate in its previous color value
Expand Down
29 changes: 27 additions & 2 deletions src/ChartInternal/internals/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import {
import {KEY} from "../../module/Cache";
import CLASS from "../../config/classes";
import {capitalize, getBoundingRect, getRandom, isFunction, isNumber, isObject, isString, getTranslation, setTextValue} from "../../module/util";
import {IDataRow, IArcData} from "../data/IData";
import {AxisType} from "../../../types/types";


export default {
opacityForText(d): null | "0" {
const $$ = this;
Expand Down Expand Up @@ -63,7 +63,7 @@ export default {
*/
updateText(durationForExit): void {
const $$ = this;
const {config, $el} = $$;
const {$el, config} = $$;
const classText = $$.getClass("text", "index");

const text = $el.main.selectAll(`.${CLASS.texts}`)
Expand Down Expand Up @@ -148,6 +148,30 @@ export default {
return color || defaultColor;
},

/**
* Update data label text background color
* @param {object} d Data object
* @returns {string|null}
* @private
*/
updateTextBacgroundColor(d: IDataRow | IArcData): string | null {
const $$ = this;
const {$el, config} = $$;
const backgroundColor = config.data_labels_backgroundColors;
let color: string = "";

if (isString(backgroundColor) || isObject(backgroundColor)) {
const id = isString(backgroundColor) ? "" : ("id" in d ? d.id : d.data.id);
const filter = $el.defs.select(["filter[id*='labels-bg-", "']"].join(id));

if (filter.size()) {
color = `url(#${filter.attr("id")})`;
}
}

return color || null;
},

/**
* Redraw chartText
* @param {Function} x Positioning function for x
Expand All @@ -163,6 +187,7 @@ export default {

$$.$el.text
.style("fill", $$.updateTextColor.bind($$))
.attr("filter", $$.updateTextBacgroundColor.bind($$))
.style("fill-opacity", forFlow ? 0 : $$.opacityForText.bind($$))
.each(function(d, i) {
// do not apply transition for newly added text elements
Expand Down
1 change: 1 addition & 0 deletions src/ChartInternal/shape/arc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ export default {
if ($$.shouldShowArcLabel()) {
selection
.style("fill", $$.updateTextColor.bind($$))
.attr("filter", $$.updateTextBacgroundColor.bind($$))
.each(function(d) {
const node = d3Select(this);
const updated = $$.updateAngle(d);
Expand Down
11 changes: 11 additions & 0 deletions src/config/Options/data/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ export default {
* - `i` is the index of the data point where the label is shown.
* - `j` is the sub index of the data point where the label is shown.<br><br>
* Formatter function can be defined for each data by specifying as an object and D3 formatter function can be set (ex. d3.format('$'))
* @property {string|object} [data.labels.backgroundColor] Set label text background colors.
* @property {string|object|Function} [data.labels.colors] Set label text colors.
* @property {object} [data.labels.position] Set each dataset position, relative the original.
* @property {number} [data.labels.position.x=0] x coordinate position, relative the original.
Expand Down Expand Up @@ -337,6 +338,15 @@ export default {
* // align text to center of the 'bar' shape (works only for 'bar' type)
* centered: true,
*
* // apply backgound color for label texts
* backgroundColors: "red",
*
* // set differenct backround colors per dataset
* backgroundColors: {
* data1: "green",
* data2: "yellow"
* }
*
* // apply for all label texts
* colors: "red",
*
Expand Down Expand Up @@ -376,6 +386,7 @@ export default {
colors?: string|{[key: string]: string};
position?: {[key: string]: number}|{[key: string]: {x?: number; y?: number;}}
}> {},
data_labels_backgroundColors: <string|{[key: string]: string}|undefined> undefined,
data_labels_colors: <string|object|Function|undefined> undefined,
data_labels_position: {},

Expand Down
68 changes: 68 additions & 0 deletions test/internals/data-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1839,6 +1839,74 @@ describe("DATA", () => {
expect(ctx.every(v => v === chart)).to.be.true;
});
});

describe("labels.backgroundColors", () => {
let ctx = [];

before(() => {
args = {
data: {
columns: [
["data1", 30, 200, 100],
["data2", 430, 300, 500]
],
labels: {
backgroundColors: "red"
},
type: "line"
}
}
});

const checkFilter = () => {
const {$el} = chart.internal;
const filter = $el.defs.select("filter[id*='labels-bg']");
const filterId = filter.attr("id");

expect(
filter.select("feFlood").attr("flood-color")
).to.be.equal(args.data.labels.backgroundColors);

$el.text.each(function(d) {
expect(this.getAttribute("filter").indexOf(filterId) > -1).to.be.ok;
});
};

it("should set filter definition and text nodes for line type", () => {
checkFilter();
});

it("set options data.type='pie'", () => {
args.data.type = "pie";
});

it("should set filter definition and text nodes for pie type", () => {
checkFilter();
});

it("set options data.type='pie'", () => {
args.data.type = "line";
args.data.labels.backgroundColors = {
data1: "red"
};
});

it("should set filter definition and text nodes for line type", () => {
const {$el} = chart.internal;
const filter = $el.defs.select("filter[id*='labels-bg-data1']");
const filterId = filter.attr("id");

expect(filter.size()).to.be.equal(1);

$el.text.each(function(d) {
if (d.id === "data1") {
expect(this.getAttribute("filter").indexOf(filterId) > -1).to.be.ok;
} else {
expect(this.getAttribute("filter")).to.be.null;
}
});
});
});
});

describe("inner functions", () => {
Expand Down
5 changes: 5 additions & 0 deletions types/options.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1470,6 +1470,11 @@ export interface Data {
*/
centered?: boolean;

/**
* Set label text background colors.
*/
backgroundColors?: string | { [key: string]: string };

/**
* Set label text colors.
*/
Expand Down

0 comments on commit e0b2fed

Please sign in to comment.