Merged
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
2 changes: 2 additions & 0 deletions src/components/fx/hover.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -971,13 +971,15 @@ function createHoverText(hoverData, opts, gd) {
}

// hovertemplate
var d3locale = gd._fullLayout._d3locale;
var hovertemplate = d.hovertemplate || false;
var hovertemplateLabels = d.hovertemplateLabels || d;
var eventData = d.eventData[0] || {};
if(hovertemplate) {
text = Lib.hovertemplateString(
hovertemplate,
hovertemplateLabels,
d3locale,
eventData,
{meta: fullLayout.meta}
);
Expand Down
19 changes: 13 additions & 6 deletions src/lib/index.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1031,25 +1031,26 @@ var maximumNumberOfHoverTemplateWarnings = 10;
* or fallback to associated labels.
*
* Examples:
* Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
* Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
*
* @param {obj} d3 locale
* @param {string} input string containing %{...:...} template strings
* @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
* @param {obj} data objects containing substitution values
*
* @return {string} templated string
*/
lib.hovertemplateString = function(string, labels) {
lib.hovertemplateString = function(string, labels, d3locale) {
var args = arguments;
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};

return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
var obj, value, i;
for(i = 2; i < args.length; i++) {
for(i = 3; i < args.length; i++) {
obj = args[i];
if(obj.hasOwnProperty(key)) {
value = obj[key];
Expand All@@ -1076,7 +1077,13 @@ lib.hovertemplateString = function(string, labels) {
}

if(format) {
value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
var fmt;
if(d3locale) {
fmt = d3locale.numberFormat;
} else {
fmt = d3.format;
}
value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
} else {
if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
}
Expand Down
2 changes: 1 addition & 1 deletion test/image/mocks/sankey_link_concentration.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,7 +63,7 @@
}
],

"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:%0.2f}<br><b>flow.concentration</b>: %{flow.concentration:%0.2f}<br><b>flow.value</b>: %{flow.value}"
"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:0.2%}<br><b>flow.concentration</b>: %{flow.concentration:0.2%}<br><b>flow.value</b>: %{flow.value}"
}

}],
Expand Down
47 changes: 46 additions & 1 deletion test/jasmine/tests/hover_label_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1688,12 +1688,18 @@ describe('hover info', function() {
});

describe('hovertemplate', function() {
var mockCopy = Lib.extendDeep({}, mock);
var mockCopy;

beforeEach(function(done) {
mockCopy = Lib.extendDeep({}, mock);
Plotly.plot(createGraphDiv(), mockCopy.data, mockCopy.layout).then(done);
});

afterEach(function() {
Plotly.purge('graph');
destroyGraphDiv();
});

it('should format labels according to a template string', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '%{y:$.2f}<extra>trace 0</extra>')
Expand All@@ -1717,6 +1723,45 @@ describe('hover info', function() {
.then(done);
});

it('should format labels according to a template string and locale', function(done) {
var gd = document.getElementById('graph');
mockCopy.layout.separators = undefined;
Plotly.newPlot(gd, mockCopy.data, mockCopy.layout, {
locale: 'fr-eu',
locales: {
'fr-eu': {
format: {
currency: ['€', ''],
decimal: ',',
thousands: ' ',
grouping: [3]
}
}
}
})
.then(function() {
Plotly.restyle(gd, 'hovertemplate', '%{y:$010,.2f}<extra>trace 0</extra>');
})
.then(function() {
Fx.hover('graph', evt, 'xy');

var hoverTrace = gd._hoverdata[0];

expect(hoverTrace.curveNumber).toEqual(0);
expect(hoverTrace.pointNumber).toEqual(17);
expect(hoverTrace.x).toEqual(0.388);
expect(hoverTrace.y).toEqual(1);

assertHoverLabelContent({
nums: '€000 001,00',
name: 'trace 0',
axis: '0,388'
});
})
.catch(failTest)
.then(done);
});

it('should format secondary label with extra tag', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '<extra>trace 20 %{y:$.2f}</extra>')
Expand Down
28 changes: 15 additions & 13 deletions test/jasmine/tests/lib_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2181,52 +2181,54 @@ describe('Test lib.js:', function() {
});

describe('hovertemplateString', function() {
var locale = false;
it('evaluates attributes', function() {
expect(Lib.hovertemplateString('foo %{bar}', {}, {bar: 'baz'})).toEqual('foo baz');
expect(Lib.hovertemplateString('foo %{bar}', {}, locale, {bar: 'baz'})).toEqual('foo baz');
});

it('evaluates attributes with a dot in their name', function() {
expect(Lib.hovertemplateString('%{marker.size}', {}, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
expect(Lib.hovertemplateString('%{marker.size}', {}, locale, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
});

it('evaluates nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, locale, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
});

it('evaluates array nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, locale, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
});

it('subtitutes multiple matches', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
});

it('replaces missing matches with template string', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 1})).toEqual('foo 1 %{trace}');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 1})).toEqual('foo 1 %{trace}');
});

it('uses the value from the first object with the specified key', function() {
var obj1 = {a: 'first'};
var obj2 = {a: 'second', foo: {bar: 'bar'}};

// Simple key
expect(Lib.hovertemplateString('foo %{a}', {}, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, obj2, obj1)).toEqual('foo second');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj2, obj1)).toEqual('foo second');

// Nested Keys
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, obj1, obj2)).toEqual('foo bar');
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, locale, obj1, obj2)).toEqual('foo bar');

// Nested keys with 0
expect(Lib.hovertemplateString('y: %{y}', {}, {y: 0}, {y: 1})).toEqual('y: 0');
expect(Lib.hovertemplateString('y: %{y}', {}, locale, {y: 0}, {y: 1})).toEqual('y: 0');
});

it('formats value using d3 mini-language', function() {
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, {b: 43})).toEqual('b: 43.00');
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, locale, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('a: %{a:0.2%}', {}, locale, {a: 0.123})).toEqual('a: 12.30%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, locale, {b: 43})).toEqual('b: 43.00');
});

it('looks for default label if no format is provided', function() {
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, {y: 0.123})).toEqual('y: 0.1');
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, locale, {y: 0.123})).toEqual('y: 0.1');
});

it('warns user up to 10 times if a variable cannot be found', function() {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
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
2 changes: 2 additions & 0 deletions src/components/fx/hover.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -971,13 +971,15 @@ function createHoverText(hoverData, opts, gd) {
}

// hovertemplate
var d3locale = gd._fullLayout._d3locale;
var hovertemplate = d.hovertemplate || false;
var hovertemplateLabels = d.hovertemplateLabels || d;
var eventData = d.eventData[0] || {};
if(hovertemplate) {
text = Lib.hovertemplateString(
hovertemplate,
hovertemplateLabels,
d3locale,
eventData,
{meta: fullLayout.meta}
);
Expand Down
19 changes: 13 additions & 6 deletions src/lib/index.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1031,25 +1031,26 @@ var maximumNumberOfHoverTemplateWarnings = 10;
* or fallback to associated labels.
*
* Examples:
* Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
* Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
*
* @param {obj} d3 locale
* @param {string} input string containing %{...:...} template strings
* @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
* @param {obj} data objects containing substitution values
*
* @return {string} templated string
*/
lib.hovertemplateString = function(string, labels) {
lib.hovertemplateString = function(string, labels, d3locale) {
var args = arguments;
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};

return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
var obj, value, i;
for(i = 2; i < args.length; i++) {
for(i = 3; i < args.length; i++) {
obj = args[i];
if(obj.hasOwnProperty(key)) {
value = obj[key];
Expand All@@ -1076,7 +1077,13 @@ lib.hovertemplateString = function(string, labels) {
}

if(format) {
value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
var fmt;
if(d3locale) {
fmt = d3locale.numberFormat;
} else {
fmt = d3.format;
}
value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
} else {
if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
}
Expand Down
2 changes: 1 addition & 1 deletion test/image/mocks/sankey_link_concentration.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,7 +63,7 @@
}
],

"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:%0.2f}<br><b>flow.concentration</b>: %{flow.concentration:%0.2f}<br><b>flow.value</b>: %{flow.value}"
"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:0.2%}<br><b>flow.concentration</b>: %{flow.concentration:0.2%}<br><b>flow.value</b>: %{flow.value}"
}

}],
Expand Down
47 changes: 46 additions & 1 deletion test/jasmine/tests/hover_label_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1688,12 +1688,18 @@ describe('hover info', function() {
});

describe('hovertemplate', function() {
var mockCopy = Lib.extendDeep({}, mock);
var mockCopy;

beforeEach(function(done) {
mockCopy = Lib.extendDeep({}, mock);
Plotly.plot(createGraphDiv(), mockCopy.data, mockCopy.layout).then(done);
});

afterEach(function() {
Plotly.purge('graph');
destroyGraphDiv();
});

it('should format labels according to a template string', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '%{y:$.2f}<extra>trace 0</extra>')
Expand All@@ -1717,6 +1723,45 @@ describe('hover info', function() {
.then(done);
});

it('should format labels according to a template string and locale', function(done) {
var gd = document.getElementById('graph');
mockCopy.layout.separators = undefined;
Plotly.newPlot(gd, mockCopy.data, mockCopy.layout, {
locale: 'fr-eu',
locales: {
'fr-eu': {
format: {
currency: ['€', ''],
decimal: ',',
thousands: ' ',
grouping: [3]
}
}
}
})
.then(function() {
Plotly.restyle(gd, 'hovertemplate', '%{y:$010,.2f}<extra>trace 0</extra>');
})
.then(function() {
Fx.hover('graph', evt, 'xy');

var hoverTrace = gd._hoverdata[0];

expect(hoverTrace.curveNumber).toEqual(0);
expect(hoverTrace.pointNumber).toEqual(17);
expect(hoverTrace.x).toEqual(0.388);
expect(hoverTrace.y).toEqual(1);

assertHoverLabelContent({
nums: '€000 001,00',
name: 'trace 0',
axis: '0,388'
});
})
.catch(failTest)
.then(done);
});

it('should format secondary label with extra tag', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '<extra>trace 20 %{y:$.2f}</extra>')
Expand Down
28 changes: 15 additions & 13 deletions test/jasmine/tests/lib_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2181,52 +2181,54 @@ describe('Test lib.js:', function() {
});

describe('hovertemplateString', function() {
var locale = false;
it('evaluates attributes', function() {
expect(Lib.hovertemplateString('foo %{bar}', {}, {bar: 'baz'})).toEqual('foo baz');
expect(Lib.hovertemplateString('foo %{bar}', {}, locale, {bar: 'baz'})).toEqual('foo baz');
});

it('evaluates attributes with a dot in their name', function() {
expect(Lib.hovertemplateString('%{marker.size}', {}, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
expect(Lib.hovertemplateString('%{marker.size}', {}, locale, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
});

it('evaluates nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, locale, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
});

it('evaluates array nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, locale, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
});

it('subtitutes multiple matches', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
});

it('replaces missing matches with template string', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 1})).toEqual('foo 1 %{trace}');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 1})).toEqual('foo 1 %{trace}');
});

it('uses the value from the first object with the specified key', function() {
var obj1 = {a: 'first'};
var obj2 = {a: 'second', foo: {bar: 'bar'}};

// Simple key
expect(Lib.hovertemplateString('foo %{a}', {}, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, obj2, obj1)).toEqual('foo second');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj2, obj1)).toEqual('foo second');

// Nested Keys
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, obj1, obj2)).toEqual('foo bar');
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, locale, obj1, obj2)).toEqual('foo bar');

// Nested keys with 0
expect(Lib.hovertemplateString('y: %{y}', {}, {y: 0}, {y: 1})).toEqual('y: 0');
expect(Lib.hovertemplateString('y: %{y}', {}, locale, {y: 0}, {y: 1})).toEqual('y: 0');
});

it('formats value using d3 mini-language', function() {
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, {b: 43})).toEqual('b: 43.00');
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, locale, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('a: %{a:0.2%}', {}, locale, {a: 0.123})).toEqual('a: 12.30%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, locale, {b: 43})).toEqual('b: 43.00');
});

it('looks for default label if no format is provided', function() {
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, {y: 0.123})).toEqual('y: 0.1');
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, locale, {y: 0.123})).toEqual('y: 0.1');
});

it('warns user up to 10 times if a variable cannot be found', function() {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
2 changes: 2 additions & 0 deletions src/components/fx/hover.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -971,13 +971,15 @@ function createHoverText(hoverData, opts, gd) {
}

// hovertemplate
var d3locale = gd._fullLayout._d3locale;
var hovertemplate = d.hovertemplate || false;
var hovertemplateLabels = d.hovertemplateLabels || d;
var eventData = d.eventData[0] || {};
if(hovertemplate) {
text = Lib.hovertemplateString(
hovertemplate,
hovertemplateLabels,
d3locale,
eventData,
{meta: fullLayout.meta}
);
Expand Down
19 changes: 13 additions & 6 deletions src/lib/index.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1031,25 +1031,26 @@ var maximumNumberOfHoverTemplateWarnings = 10;
* or fallback to associated labels.
*
* Examples:
* Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
* Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
*
* @param {obj} d3 locale
* @param {string} input string containing %{...:...} template strings
* @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
* @param {obj} data objects containing substitution values
*
* @return {string} templated string
*/
lib.hovertemplateString = function(string, labels) {
lib.hovertemplateString = function(string, labels, d3locale) {
var args = arguments;
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};

return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
var obj, value, i;
for(i = 2; i < args.length; i++) {
for(i = 3; i < args.length; i++) {
obj = args[i];
if(obj.hasOwnProperty(key)) {
value = obj[key];
Expand All@@ -1076,7 +1077,13 @@ lib.hovertemplateString = function(string, labels) {
}

if(format) {
value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
var fmt;
if(d3locale) {
fmt = d3locale.numberFormat;
} else {
fmt = d3.format;
}
value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
} else {
if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
}
Expand Down
2 changes: 1 addition & 1 deletion test/image/mocks/sankey_link_concentration.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,7 +63,7 @@
}
],

"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:%0.2f}<br><b>flow.concentration</b>: %{flow.concentration:%0.2f}<br><b>flow.value</b>: %{flow.value}"
"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:0.2%}<br><b>flow.concentration</b>: %{flow.concentration:0.2%}<br><b>flow.value</b>: %{flow.value}"
}

}],
Expand Down
47 changes: 46 additions & 1 deletion test/jasmine/tests/hover_label_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1688,12 +1688,18 @@ describe('hover info', function() {
});

describe('hovertemplate', function() {
var mockCopy = Lib.extendDeep({}, mock);
var mockCopy;

beforeEach(function(done) {
mockCopy = Lib.extendDeep({}, mock);
Plotly.plot(createGraphDiv(), mockCopy.data, mockCopy.layout).then(done);
});

afterEach(function() {
Plotly.purge('graph');
destroyGraphDiv();
});

it('should format labels according to a template string', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '%{y:$.2f}<extra>trace 0</extra>')
Expand All@@ -1717,6 +1723,45 @@ describe('hover info', function() {
.then(done);
});

it('should format labels according to a template string and locale', function(done) {
var gd = document.getElementById('graph');
mockCopy.layout.separators = undefined;
Plotly.newPlot(gd, mockCopy.data, mockCopy.layout, {
locale: 'fr-eu',
locales: {
'fr-eu': {
format: {
currency: ['€', ''],
decimal: ',',
thousands: ' ',
grouping: [3]
}
}
}
})
.then(function() {
Plotly.restyle(gd, 'hovertemplate', '%{y:$010,.2f}<extra>trace 0</extra>');
})
.then(function() {
Fx.hover('graph', evt, 'xy');

var hoverTrace = gd._hoverdata[0];

expect(hoverTrace.curveNumber).toEqual(0);
expect(hoverTrace.pointNumber).toEqual(17);
expect(hoverTrace.x).toEqual(0.388);
expect(hoverTrace.y).toEqual(1);

assertHoverLabelContent({
nums: '€000 001,00',
name: 'trace 0',
axis: '0,388'
});
})
.catch(failTest)
.then(done);
});

it('should format secondary label with extra tag', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '<extra>trace 20 %{y:$.2f}</extra>')
Expand Down
28 changes: 15 additions & 13 deletions test/jasmine/tests/lib_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2181,52 +2181,54 @@ describe('Test lib.js:', function() {
});

describe('hovertemplateString', function() {
var locale = false;
it('evaluates attributes', function() {
expect(Lib.hovertemplateString('foo %{bar}', {}, {bar: 'baz'})).toEqual('foo baz');
expect(Lib.hovertemplateString('foo %{bar}', {}, locale, {bar: 'baz'})).toEqual('foo baz');
});

it('evaluates attributes with a dot in their name', function() {
expect(Lib.hovertemplateString('%{marker.size}', {}, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
expect(Lib.hovertemplateString('%{marker.size}', {}, locale, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
});

it('evaluates nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, locale, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
});

it('evaluates array nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, locale, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
});

it('subtitutes multiple matches', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
});

it('replaces missing matches with template string', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 1})).toEqual('foo 1 %{trace}');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 1})).toEqual('foo 1 %{trace}');
});

it('uses the value from the first object with the specified key', function() {
var obj1 = {a: 'first'};
var obj2 = {a: 'second', foo: {bar: 'bar'}};

// Simple key
expect(Lib.hovertemplateString('foo %{a}', {}, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, obj2, obj1)).toEqual('foo second');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj2, obj1)).toEqual('foo second');

// Nested Keys
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, obj1, obj2)).toEqual('foo bar');
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, locale, obj1, obj2)).toEqual('foo bar');

// Nested keys with 0
expect(Lib.hovertemplateString('y: %{y}', {}, {y: 0}, {y: 1})).toEqual('y: 0');
expect(Lib.hovertemplateString('y: %{y}', {}, locale, {y: 0}, {y: 1})).toEqual('y: 0');
});

it('formats value using d3 mini-language', function() {
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, {b: 43})).toEqual('b: 43.00');
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, locale, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('a: %{a:0.2%}', {}, locale, {a: 0.123})).toEqual('a: 12.30%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, locale, {b: 43})).toEqual('b: 43.00');
});

it('looks for default label if no format is provided', function() {
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, {y: 0.123})).toEqual('y: 0.1');
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, locale, {y: 0.123})).toEqual('y: 0.1');
});

it('warns user up to 10 times if a variable cannot be found', function() {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
2 changes: 2 additions & 0 deletions src/components/fx/hover.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -971,13 +971,15 @@ function createHoverText(hoverData, opts, gd) {
}

// hovertemplate
var d3locale = gd._fullLayout._d3locale;
var hovertemplate = d.hovertemplate || false;
var hovertemplateLabels = d.hovertemplateLabels || d;
var eventData = d.eventData[0] || {};
if(hovertemplate) {
text = Lib.hovertemplateString(
hovertemplate,
hovertemplateLabels,
d3locale,
eventData,
{meta: fullLayout.meta}
);
Expand Down
19 changes: 13 additions & 6 deletions src/lib/index.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1031,25 +1031,26 @@ var maximumNumberOfHoverTemplateWarnings = 10;
* or fallback to associated labels.
*
* Examples:
* Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
* Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
*
* @param {obj} d3 locale
* @param {string} input string containing %{...:...} template strings
* @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
* @param {obj} data objects containing substitution values
*
* @return {string} templated string
*/
lib.hovertemplateString = function(string, labels) {
lib.hovertemplateString = function(string, labels, d3locale) {
var args = arguments;
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};

return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
var obj, value, i;
for(i = 2; i < args.length; i++) {
for(i = 3; i < args.length; i++) {
obj = args[i];
if(obj.hasOwnProperty(key)) {
value = obj[key];
Expand All@@ -1076,7 +1077,13 @@ lib.hovertemplateString = function(string, labels) {
}

if(format) {
value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
var fmt;
if(d3locale) {
fmt = d3locale.numberFormat;
} else {
fmt = d3.format;
}
value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
} else {
if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
}
Expand Down
2 changes: 1 addition & 1 deletion test/image/mocks/sankey_link_concentration.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,7 +63,7 @@
}
],

"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:%0.2f}<br><b>flow.concentration</b>: %{flow.concentration:%0.2f}<br><b>flow.value</b>: %{flow.value}"
"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:0.2%}<br><b>flow.concentration</b>: %{flow.concentration:0.2%}<br><b>flow.value</b>: %{flow.value}"
}

}],
Expand Down
47 changes: 46 additions & 1 deletion test/jasmine/tests/hover_label_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1688,12 +1688,18 @@ describe('hover info', function() {
});

describe('hovertemplate', function() {
var mockCopy = Lib.extendDeep({}, mock);
var mockCopy;

beforeEach(function(done) {
mockCopy = Lib.extendDeep({}, mock);
Plotly.plot(createGraphDiv(), mockCopy.data, mockCopy.layout).then(done);
});

afterEach(function() {
Plotly.purge('graph');
destroyGraphDiv();
});

it('should format labels according to a template string', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '%{y:$.2f}<extra>trace 0</extra>')
Expand All@@ -1717,6 +1723,45 @@ describe('hover info', function() {
.then(done);
});

it('should format labels according to a template string and locale', function(done) {
var gd = document.getElementById('graph');
mockCopy.layout.separators = undefined;
Plotly.newPlot(gd, mockCopy.data, mockCopy.layout, {
locale: 'fr-eu',
locales: {
'fr-eu': {
format: {
currency: ['€', ''],
decimal: ',',
thousands: ' ',
grouping: [3]
}
}
}
})
.then(function() {
Plotly.restyle(gd, 'hovertemplate', '%{y:$010,.2f}<extra>trace 0</extra>');
})
.then(function() {
Fx.hover('graph', evt, 'xy');

var hoverTrace = gd._hoverdata[0];

expect(hoverTrace.curveNumber).toEqual(0);
expect(hoverTrace.pointNumber).toEqual(17);
expect(hoverTrace.x).toEqual(0.388);
expect(hoverTrace.y).toEqual(1);

assertHoverLabelContent({
nums: '€000 001,00',
name: 'trace 0',
axis: '0,388'
});
})
.catch(failTest)
.then(done);
});

it('should format secondary label with extra tag', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '<extra>trace 20 %{y:$.2f}</extra>')
Expand Down
28 changes: 15 additions & 13 deletions test/jasmine/tests/lib_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2181,52 +2181,54 @@ describe('Test lib.js:', function() {
});

describe('hovertemplateString', function() {
var locale = false;
it('evaluates attributes', function() {
expect(Lib.hovertemplateString('foo %{bar}', {}, {bar: 'baz'})).toEqual('foo baz');
expect(Lib.hovertemplateString('foo %{bar}', {}, locale, {bar: 'baz'})).toEqual('foo baz');
});

it('evaluates attributes with a dot in their name', function() {
expect(Lib.hovertemplateString('%{marker.size}', {}, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
expect(Lib.hovertemplateString('%{marker.size}', {}, locale, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
});

it('evaluates nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, locale, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
});

it('evaluates array nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, locale, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
});

it('subtitutes multiple matches', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
});

it('replaces missing matches with template string', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 1})).toEqual('foo 1 %{trace}');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 1})).toEqual('foo 1 %{trace}');
});

it('uses the value from the first object with the specified key', function() {
var obj1 = {a: 'first'};
var obj2 = {a: 'second', foo: {bar: 'bar'}};

// Simple key
expect(Lib.hovertemplateString('foo %{a}', {}, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, obj2, obj1)).toEqual('foo second');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj2, obj1)).toEqual('foo second');

// Nested Keys
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, obj1, obj2)).toEqual('foo bar');
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, locale, obj1, obj2)).toEqual('foo bar');

// Nested keys with 0
expect(Lib.hovertemplateString('y: %{y}', {}, {y: 0}, {y: 1})).toEqual('y: 0');
expect(Lib.hovertemplateString('y: %{y}', {}, locale, {y: 0}, {y: 1})).toEqual('y: 0');
});

it('formats value using d3 mini-language', function() {
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, {b: 43})).toEqual('b: 43.00');
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, locale, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('a: %{a:0.2%}', {}, locale, {a: 0.123})).toEqual('a: 12.30%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, locale, {b: 43})).toEqual('b: 43.00');
});

it('looks for default label if no format is provided', function() {
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, {y: 0.123})).toEqual('y: 0.1');
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, locale, {y: 0.123})).toEqual('y: 0.1');
});

it('warns user up to 10 times if a variable cannot be found', function() {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
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
2 changes: 2 additions & 0 deletions src/components/fx/hover.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -971,13 +971,15 @@ function createHoverText(hoverData, opts, gd) {
}

// hovertemplate
var d3locale = gd._fullLayout._d3locale;
var hovertemplate = d.hovertemplate || false;
var hovertemplateLabels = d.hovertemplateLabels || d;
var eventData = d.eventData[0] || {};
if(hovertemplate) {
text = Lib.hovertemplateString(
hovertemplate,
hovertemplateLabels,
d3locale,
eventData,
{meta: fullLayout.meta}
);
Expand Down
19 changes: 13 additions & 6 deletions src/lib/index.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1031,25 +1031,26 @@ var maximumNumberOfHoverTemplateWarnings = 10;
* or fallback to associated labels.
*
* Examples:
* Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
* Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
*
* @param {obj} d3 locale
* @param {string} input string containing %{...:...} template strings
* @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
* @param {obj} data objects containing substitution values
*
* @return {string} templated string
*/
lib.hovertemplateString = function(string, labels) {
lib.hovertemplateString = function(string, labels, d3locale) {
var args = arguments;
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};

return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
var obj, value, i;
for(i = 2; i < args.length; i++) {
for(i = 3; i < args.length; i++) {
obj = args[i];
if(obj.hasOwnProperty(key)) {
value = obj[key];
Expand All@@ -1076,7 +1077,13 @@ lib.hovertemplateString = function(string, labels) {
}

if(format) {
value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
var fmt;
if(d3locale) {
fmt = d3locale.numberFormat;
} else {
fmt = d3.format;
}
value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
} else {
if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
}
Expand Down
2 changes: 1 addition & 1 deletion test/image/mocks/sankey_link_concentration.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,7 +63,7 @@
}
],

"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:%0.2f}<br><b>flow.concentration</b>: %{flow.concentration:%0.2f}<br><b>flow.value</b>: %{flow.value}"
"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:0.2%}<br><b>flow.concentration</b>: %{flow.concentration:0.2%}<br><b>flow.value</b>: %{flow.value}"
}

}],
Expand Down
47 changes: 46 additions & 1 deletion test/jasmine/tests/hover_label_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1688,12 +1688,18 @@ describe('hover info', function() {
});

describe('hovertemplate', function() {
var mockCopy = Lib.extendDeep({}, mock);
var mockCopy;

beforeEach(function(done) {
mockCopy = Lib.extendDeep({}, mock);
Plotly.plot(createGraphDiv(), mockCopy.data, mockCopy.layout).then(done);
});

afterEach(function() {
Plotly.purge('graph');
destroyGraphDiv();
});

it('should format labels according to a template string', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '%{y:$.2f}<extra>trace 0</extra>')
Expand All@@ -1717,6 +1723,45 @@ describe('hover info', function() {
.then(done);
});

it('should format labels according to a template string and locale', function(done) {
var gd = document.getElementById('graph');
mockCopy.layout.separators = undefined;
Plotly.newPlot(gd, mockCopy.data, mockCopy.layout, {
locale: 'fr-eu',
locales: {
'fr-eu': {
format: {
currency: ['€', ''],
decimal: ',',
thousands: ' ',
grouping: [3]
}
}
}
})
.then(function() {
Plotly.restyle(gd, 'hovertemplate', '%{y:$010,.2f}<extra>trace 0</extra>');
})
.then(function() {
Fx.hover('graph', evt, 'xy');

var hoverTrace = gd._hoverdata[0];

expect(hoverTrace.curveNumber).toEqual(0);
expect(hoverTrace.pointNumber).toEqual(17);
expect(hoverTrace.x).toEqual(0.388);
expect(hoverTrace.y).toEqual(1);

assertHoverLabelContent({
nums: '€000 001,00',
name: 'trace 0',
axis: '0,388'
});
})
.catch(failTest)
.then(done);
});

it('should format secondary label with extra tag', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '<extra>trace 20 %{y:$.2f}</extra>')
Expand Down
28 changes: 15 additions & 13 deletions test/jasmine/tests/lib_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2181,52 +2181,54 @@ describe('Test lib.js:', function() {
});

describe('hovertemplateString', function() {
var locale = false;
it('evaluates attributes', function() {
expect(Lib.hovertemplateString('foo %{bar}', {}, {bar: 'baz'})).toEqual('foo baz');
expect(Lib.hovertemplateString('foo %{bar}', {}, locale, {bar: 'baz'})).toEqual('foo baz');
});

it('evaluates attributes with a dot in their name', function() {
expect(Lib.hovertemplateString('%{marker.size}', {}, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
expect(Lib.hovertemplateString('%{marker.size}', {}, locale, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
});

it('evaluates nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, locale, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
});

it('evaluates array nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, locale, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
});

it('subtitutes multiple matches', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
});

it('replaces missing matches with template string', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 1})).toEqual('foo 1 %{trace}');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 1})).toEqual('foo 1 %{trace}');
});

it('uses the value from the first object with the specified key', function() {
var obj1 = {a: 'first'};
var obj2 = {a: 'second', foo: {bar: 'bar'}};

// Simple key
expect(Lib.hovertemplateString('foo %{a}', {}, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, obj2, obj1)).toEqual('foo second');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj2, obj1)).toEqual('foo second');

// Nested Keys
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, obj1, obj2)).toEqual('foo bar');
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, locale, obj1, obj2)).toEqual('foo bar');

// Nested keys with 0
expect(Lib.hovertemplateString('y: %{y}', {}, {y: 0}, {y: 1})).toEqual('y: 0');
expect(Lib.hovertemplateString('y: %{y}', {}, locale, {y: 0}, {y: 1})).toEqual('y: 0');
});

it('formats value using d3 mini-language', function() {
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, {b: 43})).toEqual('b: 43.00');
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, locale, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('a: %{a:0.2%}', {}, locale, {a: 0.123})).toEqual('a: 12.30%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, locale, {b: 43})).toEqual('b: 43.00');
});

it('looks for default label if no format is provided', function() {
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, {y: 0.123})).toEqual('y: 0.1');
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, locale, {y: 0.123})).toEqual('y: 0.1');
});

it('warns user up to 10 times if a variable cannot be found', function() {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
2 changes: 2 additions & 0 deletions src/components/fx/hover.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -971,13 +971,15 @@ function createHoverText(hoverData, opts, gd) {
}

// hovertemplate
var d3locale = gd._fullLayout._d3locale;
var hovertemplate = d.hovertemplate || false;
var hovertemplateLabels = d.hovertemplateLabels || d;
var eventData = d.eventData[0] || {};
if(hovertemplate) {
text = Lib.hovertemplateString(
hovertemplate,
hovertemplateLabels,
d3locale,
eventData,
{meta: fullLayout.meta}
);
Expand Down
19 changes: 13 additions & 6 deletions src/lib/index.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1031,25 +1031,26 @@ var maximumNumberOfHoverTemplateWarnings = 10;
* or fallback to associated labels.
*
* Examples:
* Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
* Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
*
* @param {obj} d3 locale
* @param {string} input string containing %{...:...} template strings
* @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
* @param {obj} data objects containing substitution values
*
* @return {string} templated string
*/
lib.hovertemplateString = function(string, labels) {
lib.hovertemplateString = function(string, labels, d3locale) {
var args = arguments;
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};

return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
var obj, value, i;
for(i = 2; i < args.length; i++) {
for(i = 3; i < args.length; i++) {
obj = args[i];
if(obj.hasOwnProperty(key)) {
value = obj[key];
Expand All@@ -1076,7 +1077,13 @@ lib.hovertemplateString = function(string, labels) {
}

if(format) {
value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
var fmt;
if(d3locale) {
fmt = d3locale.numberFormat;
} else {
fmt = d3.format;
}
value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
} else {
if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
}
Expand Down
2 changes: 1 addition & 1 deletion test/image/mocks/sankey_link_concentration.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,7 +63,7 @@
}
],

"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:%0.2f}<br><b>flow.concentration</b>: %{flow.concentration:%0.2f}<br><b>flow.value</b>: %{flow.value}"
"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:0.2%}<br><b>flow.concentration</b>: %{flow.concentration:0.2%}<br><b>flow.value</b>: %{flow.value}"
}

}],
Expand Down
47 changes: 46 additions & 1 deletion test/jasmine/tests/hover_label_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1688,12 +1688,18 @@ describe('hover info', function() {
});

describe('hovertemplate', function() {
var mockCopy = Lib.extendDeep({}, mock);
var mockCopy;

beforeEach(function(done) {
mockCopy = Lib.extendDeep({}, mock);
Plotly.plot(createGraphDiv(), mockCopy.data, mockCopy.layout).then(done);
});

afterEach(function() {
Plotly.purge('graph');
destroyGraphDiv();
});

it('should format labels according to a template string', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '%{y:$.2f}<extra>trace 0</extra>')
Expand All@@ -1717,6 +1723,45 @@ describe('hover info', function() {
.then(done);
});

it('should format labels according to a template string and locale', function(done) {
var gd = document.getElementById('graph');
mockCopy.layout.separators = undefined;
Plotly.newPlot(gd, mockCopy.data, mockCopy.layout, {
locale: 'fr-eu',
locales: {
'fr-eu': {
format: {
currency: ['€', ''],
decimal: ',',
thousands: ' ',
grouping: [3]
}
}
}
})
.then(function() {
Plotly.restyle(gd, 'hovertemplate', '%{y:$010,.2f}<extra>trace 0</extra>');
})
.then(function() {
Fx.hover('graph', evt, 'xy');

var hoverTrace = gd._hoverdata[0];

expect(hoverTrace.curveNumber).toEqual(0);
expect(hoverTrace.pointNumber).toEqual(17);
expect(hoverTrace.x).toEqual(0.388);
expect(hoverTrace.y).toEqual(1);

assertHoverLabelContent({
nums: '€000 001,00',
name: 'trace 0',
axis: '0,388'
});
})
.catch(failTest)
.then(done);
});

it('should format secondary label with extra tag', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '<extra>trace 20 %{y:$.2f}</extra>')
Expand Down
28 changes: 15 additions & 13 deletions test/jasmine/tests/lib_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2181,52 +2181,54 @@ describe('Test lib.js:', function() {
});

describe('hovertemplateString', function() {
var locale = false;
it('evaluates attributes', function() {
expect(Lib.hovertemplateString('foo %{bar}', {}, {bar: 'baz'})).toEqual('foo baz');
expect(Lib.hovertemplateString('foo %{bar}', {}, locale, {bar: 'baz'})).toEqual('foo baz');
});

it('evaluates attributes with a dot in their name', function() {
expect(Lib.hovertemplateString('%{marker.size}', {}, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
expect(Lib.hovertemplateString('%{marker.size}', {}, locale, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
});

it('evaluates nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, locale, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
});

it('evaluates array nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, locale, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
});

it('subtitutes multiple matches', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
});

it('replaces missing matches with template string', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 1})).toEqual('foo 1 %{trace}');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 1})).toEqual('foo 1 %{trace}');
});

it('uses the value from the first object with the specified key', function() {
var obj1 = {a: 'first'};
var obj2 = {a: 'second', foo: {bar: 'bar'}};

// Simple key
expect(Lib.hovertemplateString('foo %{a}', {}, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, obj2, obj1)).toEqual('foo second');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj2, obj1)).toEqual('foo second');

// Nested Keys
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, obj1, obj2)).toEqual('foo bar');
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, locale, obj1, obj2)).toEqual('foo bar');

// Nested keys with 0
expect(Lib.hovertemplateString('y: %{y}', {}, {y: 0}, {y: 1})).toEqual('y: 0');
expect(Lib.hovertemplateString('y: %{y}', {}, locale, {y: 0}, {y: 1})).toEqual('y: 0');
});

it('formats value using d3 mini-language', function() {
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, {b: 43})).toEqual('b: 43.00');
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, locale, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('a: %{a:0.2%}', {}, locale, {a: 0.123})).toEqual('a: 12.30%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, locale, {b: 43})).toEqual('b: 43.00');
});

it('looks for default label if no format is provided', function() {
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, {y: 0.123})).toEqual('y: 0.1');
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, locale, {y: 0.123})).toEqual('y: 0.1');
});

it('warns user up to 10 times if a variable cannot be found', function() {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
2 changes: 2 additions & 0 deletions src/components/fx/hover.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -971,13 +971,15 @@ function createHoverText(hoverData, opts, gd) {
}

// hovertemplate
var d3locale = gd._fullLayout._d3locale;
var hovertemplate = d.hovertemplate || false;
var hovertemplateLabels = d.hovertemplateLabels || d;
var eventData = d.eventData[0] || {};
if(hovertemplate) {
text = Lib.hovertemplateString(
hovertemplate,
hovertemplateLabels,
d3locale,
eventData,
{meta: fullLayout.meta}
);
Expand Down
19 changes: 13 additions & 6 deletions src/lib/index.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1031,25 +1031,26 @@ var maximumNumberOfHoverTemplateWarnings = 10;
* or fallback to associated labels.
*
* Examples:
* Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
* Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
*
* @param {obj} d3 locale
* @param {string} input string containing %{...:...} template strings
* @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
* @param {obj} data objects containing substitution values
*
* @return {string} templated string
*/
lib.hovertemplateString = function(string, labels) {
lib.hovertemplateString = function(string, labels, d3locale) {
var args = arguments;
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};

return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
var obj, value, i;
for(i = 2; i < args.length; i++) {
for(i = 3; i < args.length; i++) {
obj = args[i];
if(obj.hasOwnProperty(key)) {
value = obj[key];
Expand All@@ -1076,7 +1077,13 @@ lib.hovertemplateString = function(string, labels) {
}

if(format) {
value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
var fmt;
if(d3locale) {
fmt = d3locale.numberFormat;
} else {
fmt = d3.format;
}
value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
} else {
if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
}
Expand Down
2 changes: 1 addition & 1 deletion test/image/mocks/sankey_link_concentration.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,7 +63,7 @@
}
],

"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:%0.2f}<br><b>flow.concentration</b>: %{flow.concentration:%0.2f}<br><b>flow.value</b>: %{flow.value}"
"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:0.2%}<br><b>flow.concentration</b>: %{flow.concentration:0.2%}<br><b>flow.value</b>: %{flow.value}"
}

}],
Expand Down
47 changes: 46 additions & 1 deletion test/jasmine/tests/hover_label_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1688,12 +1688,18 @@ describe('hover info', function() {
});

describe('hovertemplate', function() {
var mockCopy = Lib.extendDeep({}, mock);
var mockCopy;

beforeEach(function(done) {
mockCopy = Lib.extendDeep({}, mock);
Plotly.plot(createGraphDiv(), mockCopy.data, mockCopy.layout).then(done);
});

afterEach(function() {
Plotly.purge('graph');
destroyGraphDiv();
});

it('should format labels according to a template string', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '%{y:$.2f}<extra>trace 0</extra>')
Expand All@@ -1717,6 +1723,45 @@ describe('hover info', function() {
.then(done);
});

it('should format labels according to a template string and locale', function(done) {
var gd = document.getElementById('graph');
mockCopy.layout.separators = undefined;
Plotly.newPlot(gd, mockCopy.data, mockCopy.layout, {
locale: 'fr-eu',
locales: {
'fr-eu': {
format: {
currency: ['€', ''],
decimal: ',',
thousands: ' ',
grouping: [3]
}
}
}
})
.then(function() {
Plotly.restyle(gd, 'hovertemplate', '%{y:$010,.2f}<extra>trace 0</extra>');
})
.then(function() {
Fx.hover('graph', evt, 'xy');

var hoverTrace = gd._hoverdata[0];

expect(hoverTrace.curveNumber).toEqual(0);
expect(hoverTrace.pointNumber).toEqual(17);
expect(hoverTrace.x).toEqual(0.388);
expect(hoverTrace.y).toEqual(1);

assertHoverLabelContent({
nums: '€000 001,00',
name: 'trace 0',
axis: '0,388'
});
})
.catch(failTest)
.then(done);
});

it('should format secondary label with extra tag', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '<extra>trace 20 %{y:$.2f}</extra>')
Expand Down
28 changes: 15 additions & 13 deletions test/jasmine/tests/lib_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2181,52 +2181,54 @@ describe('Test lib.js:', function() {
});

describe('hovertemplateString', function() {
var locale = false;
it('evaluates attributes', function() {
expect(Lib.hovertemplateString('foo %{bar}', {}, {bar: 'baz'})).toEqual('foo baz');
expect(Lib.hovertemplateString('foo %{bar}', {}, locale, {bar: 'baz'})).toEqual('foo baz');
});

it('evaluates attributes with a dot in their name', function() {
expect(Lib.hovertemplateString('%{marker.size}', {}, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
expect(Lib.hovertemplateString('%{marker.size}', {}, locale, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
});

it('evaluates nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, locale, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
});

it('evaluates array nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, locale, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
});

it('subtitutes multiple matches', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
});

it('replaces missing matches with template string', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 1})).toEqual('foo 1 %{trace}');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 1})).toEqual('foo 1 %{trace}');
});

it('uses the value from the first object with the specified key', function() {
var obj1 = {a: 'first'};
var obj2 = {a: 'second', foo: {bar: 'bar'}};

// Simple key
expect(Lib.hovertemplateString('foo %{a}', {}, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, obj2, obj1)).toEqual('foo second');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj2, obj1)).toEqual('foo second');

// Nested Keys
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, obj1, obj2)).toEqual('foo bar');
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, locale, obj1, obj2)).toEqual('foo bar');

// Nested keys with 0
expect(Lib.hovertemplateString('y: %{y}', {}, {y: 0}, {y: 1})).toEqual('y: 0');
expect(Lib.hovertemplateString('y: %{y}', {}, locale, {y: 0}, {y: 1})).toEqual('y: 0');
});

it('formats value using d3 mini-language', function() {
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, {b: 43})).toEqual('b: 43.00');
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, locale, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('a: %{a:0.2%}', {}, locale, {a: 0.123})).toEqual('a: 12.30%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, locale, {b: 43})).toEqual('b: 43.00');
});

it('looks for default label if no format is provided', function() {
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, {y: 0.123})).toEqual('y: 0.1');
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, locale, {y: 0.123})).toEqual('y: 0.1');
});

it('warns user up to 10 times if a variable cannot be found', function() {
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
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
2 changes: 2 additions & 0 deletions src/components/fx/hover.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -971,13 +971,15 @@ function createHoverText(hoverData, opts, gd) {
}

// hovertemplate
var d3locale = gd._fullLayout._d3locale;
var hovertemplate = d.hovertemplate || false;
var hovertemplateLabels = d.hovertemplateLabels || d;
var eventData = d.eventData[0] || {};
if(hovertemplate) {
text = Lib.hovertemplateString(
hovertemplate,
hovertemplateLabels,
d3locale,
eventData,
{meta: fullLayout.meta}
);
Expand Down
19 changes: 13 additions & 6 deletions src/lib/index.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1031,25 +1031,26 @@ var maximumNumberOfHoverTemplateWarnings = 10;
* or fallback to associated labels.
*
* Examples:
* Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
* Lib.hovertemplateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
* Lib.hovertemplateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
* Lib.hovertemplateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
*
* @param {obj} d3 locale
* @param {string} input string containing %{...:...} template strings
* @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
* @param {obj} data objects containing substitution values
*
* @return {string} templated string
*/
lib.hovertemplateString = function(string, labels) {
lib.hovertemplateString = function(string, labels, d3locale) {
var args = arguments;
// Not all that useful, but cache nestedProperty instantiation
// just in case it speeds things up *slightly*:
var getterCache = {};

return string.replace(lib.TEMPLATE_STRING_REGEX, function(match, key, format) {
var obj, value, i;
for(i = 2; i < args.length; i++) {
for(i = 3; i < args.length; i++) {
obj = args[i];
if(obj.hasOwnProperty(key)) {
value = obj[key];
Expand All@@ -1076,7 +1077,13 @@ lib.hovertemplateString = function(string, labels) {
}

if(format) {
value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
var fmt;
if(d3locale) {
fmt = d3locale.numberFormat;
} else {
fmt = d3.format;
}
value = fmt(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
} else {
if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
}
Expand Down
2 changes: 1 addition & 1 deletion test/image/mocks/sankey_link_concentration.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,7 +63,7 @@
}
],

"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:%0.2f}<br><b>flow.concentration</b>: %{flow.concentration:%0.2f}<br><b>flow.value</b>: %{flow.value}"
"hovertemplate": "%{label}<br><b>flow.labelConcentration</b>: %{flow.labelConcentration:0.2%}<br><b>flow.concentration</b>: %{flow.concentration:0.2%}<br><b>flow.value</b>: %{flow.value}"
}

}],
Expand Down
47 changes: 46 additions & 1 deletion test/jasmine/tests/hover_label_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -1688,12 +1688,18 @@ describe('hover info', function() {
});

describe('hovertemplate', function() {
var mockCopy = Lib.extendDeep({}, mock);
var mockCopy;

beforeEach(function(done) {
mockCopy = Lib.extendDeep({}, mock);
Plotly.plot(createGraphDiv(), mockCopy.data, mockCopy.layout).then(done);
});

afterEach(function() {
Plotly.purge('graph');
destroyGraphDiv();
});

it('should format labels according to a template string', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '%{y:$.2f}<extra>trace 0</extra>')
Expand All@@ -1717,6 +1723,45 @@ describe('hover info', function() {
.then(done);
});

it('should format labels according to a template string and locale', function(done) {
var gd = document.getElementById('graph');
mockCopy.layout.separators = undefined;
Plotly.newPlot(gd, mockCopy.data, mockCopy.layout, {
locale: 'fr-eu',
locales: {
'fr-eu': {
format: {
currency: ['€', ''],
decimal: ',',
thousands: ' ',
grouping: [3]
}
}
}
})
.then(function() {
Plotly.restyle(gd, 'hovertemplate', '%{y:$010,.2f}<extra>trace 0</extra>');
})
.then(function() {
Fx.hover('graph', evt, 'xy');

var hoverTrace = gd._hoverdata[0];

expect(hoverTrace.curveNumber).toEqual(0);
expect(hoverTrace.pointNumber).toEqual(17);
expect(hoverTrace.x).toEqual(0.388);
expect(hoverTrace.y).toEqual(1);

assertHoverLabelContent({
nums: '€000 001,00',
name: 'trace 0',
axis: '0,388'
});
})
.catch(failTest)
.then(done);
});

it('should format secondary label with extra tag', function(done) {
var gd = document.getElementById('graph');
Plotly.restyle(gd, 'hovertemplate', '<extra>trace 20 %{y:$.2f}</extra>')
Expand Down
28 changes: 15 additions & 13 deletions test/jasmine/tests/lib_test.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2181,52 +2181,54 @@ describe('Test lib.js:', function() {
});

describe('hovertemplateString', function() {
var locale = false;
it('evaluates attributes', function() {
expect(Lib.hovertemplateString('foo %{bar}', {}, {bar: 'baz'})).toEqual('foo baz');
expect(Lib.hovertemplateString('foo %{bar}', {}, locale, {bar: 'baz'})).toEqual('foo baz');
});

it('evaluates attributes with a dot in their name', function() {
expect(Lib.hovertemplateString('%{marker.size}', {}, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
expect(Lib.hovertemplateString('%{marker.size}', {}, locale, {'marker.size': 12}, {marker: {size: 14}})).toEqual('12');
});

it('evaluates nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar.baz}', {}, locale, {bar: {baz: 'asdf'}})).toEqual('foo asdf');
});

it('evaluates array nested properties', function() {
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
expect(Lib.hovertemplateString('foo %{bar[0].baz}', {}, locale, {bar: [{baz: 'asdf'}]})).toEqual('foo asdf');
});

it('subtitutes multiple matches', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 'asdf', trace: 'jkl;'})).toEqual('foo asdf jkl;');
});

it('replaces missing matches with template string', function() {
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, {group: 1})).toEqual('foo 1 %{trace}');
expect(Lib.hovertemplateString('foo %{group} %{trace}', {}, locale, {group: 1})).toEqual('foo 1 %{trace}');
});

it('uses the value from the first object with the specified key', function() {
var obj1 = {a: 'first'};
var obj2 = {a: 'second', foo: {bar: 'bar'}};

// Simple key
expect(Lib.hovertemplateString('foo %{a}', {}, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, obj2, obj1)).toEqual('foo second');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj1, obj2)).toEqual('foo first');
expect(Lib.hovertemplateString('foo %{a}', {}, locale, obj2, obj1)).toEqual('foo second');

// Nested Keys
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, obj1, obj2)).toEqual('foo bar');
expect(Lib.hovertemplateString('foo %{foo.bar}', {}, locale, obj1, obj2)).toEqual('foo bar');

// Nested keys with 0
expect(Lib.hovertemplateString('y: %{y}', {}, {y: 0}, {y: 1})).toEqual('y: 0');
expect(Lib.hovertemplateString('y: %{y}', {}, locale, {y: 0}, {y: 1})).toEqual('y: 0');
});

it('formats value using d3 mini-language', function() {
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, {b: 43})).toEqual('b: 43.00');
expect(Lib.hovertemplateString('a: %{a:.0%}', {}, locale, {a: 0.123})).toEqual('a: 12%');
expect(Lib.hovertemplateString('a: %{a:0.2%}', {}, locale, {a: 0.123})).toEqual('a: 12.30%');
expect(Lib.hovertemplateString('b: %{b:2.2f}', {}, locale, {b: 43})).toEqual('b: 43.00');
});

it('looks for default label if no format is provided', function() {
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, {y: 0.123})).toEqual('y: 0.1');
expect(Lib.hovertemplateString('y: %{y}', {yLabel: '0.1'}, locale, {y: 0.123})).toEqual('y: 0.1');
});

it('warns user up to 10 times if a variable cannot be found', function() {
Expand Down