Skip to content

Commit

Permalink
fix(legend): Fix legend title to show data.names if set
Browse files Browse the repository at this point in the history
Make legend title to use data.names values if specified.

Fix #3662
  • Loading branch information
netil committed Feb 28, 2024
1 parent b8a2944 commit e8fa131
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/ChartInternal/internals/legend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,14 @@ function getLegendColor(id: string): string {
/**
* Get formatted text value
* @param {string} id Legend text id
* @param {boolean} formatted Whether or not to format the text
* @returns {string} Formatted legend text
*/
function getFormattedText<T = string>(id: T): T {
function getFormattedText<T = string>(id: T, formatted = true): T {
const {config} = this;
let text = config.data_names[id] ?? id;

if (isFunction(config.legend_format)) {
if (formatted && isFunction(config.legend_format)) {
text = config.legend_format(text);
}

Expand Down Expand Up @@ -589,12 +590,12 @@ export default {
if (config.legend_tooltip) {
legend.selectAll("title")
.data(targetIdz)
.text(id => id);
.text(id => getFormattedText.bind($$)(id, false));
}

const texts = legend.selectAll("text")
.data(targetIdz)
.text(getFormattedText.bind($$)) // MEMO: needed for update
.text(id => getFormattedText.bind($$)(id)) // MEMO: needed for update
.each(function(id, i) {
updatePositions(this, id, i);
});
Expand Down Expand Up @@ -749,7 +750,7 @@ export default {
}

l.append("text")
.text(getFormattedText.bind($$))
.text(id => getFormattedText.bind($$)(id))
.each(function(id, i) {
updatePositions(this, id, i);
})
Expand Down
27 changes: 27 additions & 0 deletions test/internals/legend-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -939,5 +939,32 @@ describe("LEGEND", () => {

expect(dataIds).to.be.deep.equal(legendTitle);
});

it("set options: data.names", () => {
args = {
data: {
names: {
"data1": "Detailed Name",
"data2": "Name Detailed"
},
columns: [
["data1", 71.4],
["data2", 10],
],
type: "gauge"
},
legend: {
format: id => id.substr(0, 2) + "...",
tooltip: true
}
}
});

it("should legend title show data.names values.", () => {
const legendTitle = chart.$.legend.selectAll("title").nodes().map(v => v.textContent);
const dataNames = Object.values(chart.data.names());

expect(legendTitle).to.be.deep.equal(dataNames);
});
});
});

0 comments on commit e8fa131

Please sign in to comment.