diff --git a/draftlogs/7888_add.md b/draftlogs/7888_add.md new file mode 100644 index 00000000000..9331a636f4c --- /dev/null +++ b/draftlogs/7888_add.md @@ -0,0 +1,4 @@ +- Add Sankey trace link labels [[#7888](https://github.com/plotly/plotly.js/pull/7888)] + - `link.textinfo` shows `label` and/or `value` directly on each link, opt-in and off by default + - `link.texttemplate` allows full custom formatting, with `%{label}`, `%{value}`, `%{valueLabel}`, `%{source.label}`, `%{target.label}`, `%{customdata}` and `%{meta}` as available variables, resolved using the layout locale + - `link.texttemplatefallback` and `link.textfont` control the fallback text for missing template variables and the label font, falling back to the corresponding trace-level attributes when unset; the label value is formatted with the trace-level `valueformat`/`valuesuffix` \ No newline at end of file diff --git a/src/traces/sankey/attributes.js b/src/traces/sankey/attributes.js index 60c5fefbbbb..5953d160c4e 100644 --- a/src/traces/sankey/attributes.js +++ b/src/traces/sankey/attributes.js @@ -5,7 +5,7 @@ var baseAttrs = require('../../plots/attributes'); var colorAttrs = require('../../components/color/attributes'); var fxAttrs = require('../../components/fx/attributes'); var domainAttrs = require('../../plots/domain').attributes; -const { hovertemplateAttrs, templatefallbackAttrs } = require('../../plots/template_attributes'); +const { hovertemplateAttrs, texttemplateAttrs, templatefallbackAttrs } = require('../../plots/template_attributes'); var colorAttributes = require('../../components/colorscale/attributes'); var templatedArray = require('../../plot_api/plot_template').templatedArray; var descriptionOnlyNumbers = require('../../plots/cartesian/axis_format_attributes').descriptionOnlyNumbers; @@ -220,6 +220,31 @@ var attrs = (module.exports = overrideAll( dflt: [], description: 'The shown name of the link.' }, + textinfo: { + valType: 'flaglist', + flags: ['label', 'value'], + extras: ['none'], + dflt: 'none', + description: [ + 'Determines which trace information appears permanently on the links.', + 'Any combination of *label* and *value* joined with a *+* OR *none*.' + ].join(' ') + }, + texttemplate: texttemplateAttrs({editType: 'calc'}, { + description: [ + '*%{label}: %{valueLabel}* renders the link label and its formatted', + 'value; `valueLabel` is the value formatted with `valueformat`/`valuesuffix`.', + 'When set per link, an empty entry makes that link fall back to `textinfo`', + 'rather than leaving it unlabeled; to label only some of the links,', + 'set `textinfo` to *none* and give a template to those links alone.' + ].join(' '), + keys: ['label', 'value', 'valueLabel', 'source', 'target', 'customdata', 'meta'] + }), + texttemplatefallback: templatefallbackAttrs(), + textfont: fontAttrs({ + autoShadowDflt: true, + description: 'Sets the font for the permanent link labels.' + }), color: { valType: 'color', arrayOk: true, diff --git a/src/traces/sankey/constants.ts b/src/traces/sankey/constants.ts index 94116c31072..aa984e0b4ef 100644 --- a/src/traces/sankey/constants.ts +++ b/src/traces/sankey/constants.ts @@ -11,6 +11,8 @@ export const cn = { sankey: 'sankey', sankeyLinks: 'sankey-links', sankeyLink: 'sankey-link', + sankeyLinkLabelSet: 'sankey-link-label-set', + sankeyLinkLabel: 'sankey-link-label', sankeyNodeSet: 'sankey-node-set', sankeyNode: 'sankey-node', nodeRect: 'node-rect', diff --git a/src/traces/sankey/defaults.js b/src/traces/sankey/defaults.js index 785e843267a..942ff796ee9 100644 --- a/src/traces/sankey/defaults.js +++ b/src/traces/sankey/defaults.js @@ -106,6 +106,13 @@ module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout Lib.coerceFont(coerce, 'textfont', layout.font, { autoShadowDflt: true }); + const linkTextInfo = coerceLink('textinfo'); + const linkTextTemplate = coerceLink('texttemplate'); + if(linkTextInfo !== 'none' || linkTextTemplate) { + Lib.coerceFont(coerceLink, 'textfont', traceOut.textfont, { autoShadowDflt: true }); + if(linkTextTemplate) coerceLink('texttemplatefallback'); + } + // Ensure _length is defined traceOut._length = null; }; diff --git a/src/traces/sankey/render.js b/src/traces/sankey/render.js index a62ad4555ac..902e278735d 100644 --- a/src/traces/sankey/render.js +++ b/src/traces/sankey/render.js @@ -356,6 +356,17 @@ function linkModel(d, l, i) { }; } +// The link paths and their permanent labels are two joins over the same links, +// so the models are built once per draw and shared between both selections. +function linkModels(d) { + if(!d._linkModels) { + d._linkModels = d.graph.links + .filter((l) => l.value) + .map((l, i) => linkModel(d, l, i)); + } + return d._linkModels; +} + function createCircularClosedPathString(link, arrowLen) { // Using coordinates computed by d3-sankey-circular var pathString = ''; @@ -560,6 +571,96 @@ function linkPath() { return path; } +// Builds the permanent-label string for a link from textinfo / texttemplate. +// Returns null when the feature is opted out, so that traces which do not use it +// do no per-link work at all. +function linkTextGetter(gd, trace) { + const linkAttr = trace.link; + const textinfo = linkAttr.textinfo; + const texttemplate = linkAttr.texttemplate; + const flags = (textinfo && textinfo !== 'none') ? textinfo.split('+') : []; + const hasTemplate = Array.isArray(texttemplate) ? texttemplate.length > 0 : !!texttemplate; + if(!flags.length && !hasTemplate) return null; + + // the formatter depends on the trace only, so build it once per draw + const formatValue = Lib.numberFormat(trace.valueformat); + const vSuf = trace.valuesuffix; + const locale = gd._fullLayout._d3locale; + + return (l, i) => { + const valueLabel = `${formatValue(l.value)}${vSuf}`; + + const tt = Array.isArray(texttemplate) ? texttemplate[i] : texttemplate; + if(tt) { + return Lib.texttemplateString({ + template: tt, + labels: {valueLabel: valueLabel}, + data: [{ + label: l.label, + value: l.value, + valueLabel: valueLabel, + source: l.source, + target: l.target, + customdata: l.customdata + }, trace._meta], + locale: locale, + fallback: linkAttr.texttemplatefallback + }); + } + + if(!flags.length) return ''; + const parts = []; + if(flags.indexOf('label') !== -1 && l.label) parts.push(l.label); + if(flags.indexOf('value') !== -1) parts.push(valueLabel); + return parts.join('
'); + }; +} + +// Counter-transform that cancels the group matrix applied in sankeyTransform, so +// the label glyphs always read left-to-right and upright. For every combination +// the product (group matrix x this) is the identity: +// h + forward : matrix( 1 0 0 1) -> '' +// h + reversed: matrix(-1 0 0 1) -> scale(-1,1) +// v + forward : matrix( 0 1 1 0) -> scale(-1,1) rotate(90) +// v + reversed: matrix( 0 -1 1 0) -> rotate(90) +// Shared by the node labels and the permanent link labels. +function uprightTransform(d) { + if(d.horizontal) return d.reversed ? 'scale(-1,1)' : ''; + return d.reversed ? strRotate(90) : `scale(-1,1)${strRotate(90)}`; +} + +// Positions a permanent link label at the link midpoint (layout frame) and keeps +// the glyphs upright. The midpoint stays in the layout frame: the enclosing +// `.sankey` group already carries the orientation/direction transform, so the +// coordinates themselves must not be mirrored here. The trailing translate runs +// in the already uprighted frame and is therefore a plain screen-space shift: it +// centres the whole text block on the anchor instead of its first baseline, +// using the same block metric as the node labels. +function linkLabelTransform(d) { + const l = d.link; + let midX, midY; + if(l.circular) { + // same anchor as the hover label (see hoverCenterPosition in plot.js) + midX = (l.circularPathData.leftInnerExtent + l.circularPathData.rightInnerExtent) / 2; + midY = l.circularPathData.verticalFullExtent; + } else { + // Anchor at the middle of the arrow body: when arrows are shown, the + // head occupies the end of the link at the target side, so it is + // excluded from the span. The clamping matches linkPath() exactly + // (arrow head capped at half the straight span), so the anchor always + // agrees with the drawn path, including on drag frames where the + // layout moves after the link models were built. + const maxArrowLength = Math.abs((l.target.x0 - l.source.x1) / 2); + const arrowLen = Math.min(d.linkArrowLength, maxArrowLength); + midX = (l.source.x1 + l.target.x0 - arrowLen) / 2; + midY = (l.y0 + l.y1) / 2; + } + const blockShift = l.trace.link.textfont.size * + (CAP_SHIFT - ((d.linkLabelLines || 1) - 1) * LINE_SPACING) / 2; + + return `${strTranslate(midX, midY)}${uprightTransform(d.parent)}${strTranslate(0, blockShift)}`; +} + function nodeModel(d, n) { var zoneThicknessPad = c.nodePadAcross; var zoneLengthPad = d.nodePad / 2; @@ -629,9 +730,11 @@ function updateNodeShapes(sankeyNode) { sankeyNode.call(updateNodePositions); } -function updateShapes(sankeyNode, sankeyLink) { +function updateShapes(sankeyNode, sankeyLink, sankeyLinkLabel) { sankeyNode.call(updateNodeShapes); sankeyLink.attr('d', linkPath()); + // empty selection when the permanent labels are not opted in + sankeyLinkLabel.attr('transform', linkLabelTransform); } function sizeNode(rect) { @@ -694,7 +797,7 @@ function attachPointerEvents(selection, sankey, eventSet) { }); } -function attachDragHandler(sankeyNode, sankeyLink, callbacks, gd) { +function attachDragHandler(sankeyNode, sankeyLink, sankeyLinkLabel, callbacks, gd) { var dragBehavior = d3.behavior.drag() .origin(function(d) { return { @@ -723,7 +826,7 @@ function attachDragHandler(sankeyNode, sankeyLink, callbacks, gd) { } else { // make a forceLayout if needed attachForce(sankeyNode, forceKey, d, gd); } - startForce(sankeyNode, sankeyLink, d, forceKey, gd); + startForce(sankeyNode, sankeyLink, sankeyLinkLabel, d, forceKey, gd); } }) @@ -749,7 +852,7 @@ function attachDragHandler(sankeyNode, sankeyLink, callbacks, gd) { saveCurrentDragPosition(d.node); if(d.arrangement !== 'snap') { d.sankey.update(d.graph); - updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink); + updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink, sankeyLinkLabel); } }) @@ -785,7 +888,7 @@ function attachForce(sankeyNode, forceKey, d, gd) { .stop(); } -function startForce(sankeyNode, sankeyLink, d, forceKey, gd) { +function startForce(sankeyNode, sankeyLink, sankeyLinkLabel, d, forceKey, gd) { window.requestAnimationFrame(function faster() { var i; for(i = 0; i < c.forceTicksPerFrame; i++) { @@ -796,7 +899,7 @@ function startForce(sankeyNode, sankeyLink, d, forceKey, gd) { switchToSankeyFormat(nodes); d.sankey.update(d.graph); - updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink); + updateShapes(sankeyNode.filter(sameLayer(d)), sankeyLink, sankeyLinkLabel); if(d.forceLayouts[forceKey].alpha() > 0) { window.requestAnimationFrame(faster); @@ -969,12 +1072,7 @@ module.exports = function(gd, svg, calcData, layout, callbacks) { .style('fill', 'none'); var sankeyLink = sankeyLinks.selectAll('.' + c.cn.sankeyLink) - .data(function(d) { - var links = d.graph.links; - return links - .filter(function(l) {return l.value;}) - .map(linkModel.bind(null, d)); - }, keyFun); + .data(linkModels, keyFun); sankeyLink .enter().append('path') @@ -1001,6 +1099,56 @@ module.exports = function(gd, svg, calcData, layout, callbacks) { .style('opacity', 0) .remove(); + // Own group, appended between the links and the nodes: entering link paths + // of a later draw must not end up on top of already rendered labels. + const sankeyLinkLabelSet = sankey.selectAll(`.${c.cn.sankeyLinkLabelSet}`) + .data(repeat, keyFun); + + sankeyLinkLabelSet.enter() + .append('g') + .classed(c.cn.sankeyLinkLabelSet, true) + .style('pointer-events', 'none'); + + const sankeyLinkLabel = sankeyLinkLabelSet.selectAll(`.${c.cn.sankeyLinkLabel}`) + .data((d) => { + const getText = linkTextGetter(gd, d.trace); + if(!getText) return []; + const out = []; + linkModels(d).forEach((m) => { + // pointNumber indexes the input arrays, so it is the one an + // arrayOk texttemplate has to be looked up with + const txt = getText(m.link, m.pointNumber); + if(!txt) return; + m.linkLabelText = txt; + out.push(m); + }); + return out; + }, keyFun); + + sankeyLinkLabel.enter() + .append('text') + .classed(c.cn.sankeyLinkLabel, true) + .attr('text-anchor', 'middle'); + + sankeyLinkLabel + .attr('data-notex', 1) + .text((d) => d.linkLabelText) + .each(function(d) { + const e = d3.select(this); + Drawing.font(e, d.link.trace.link.textfont); + svgTextUtils.convertToTspans(e, gd); + // cached for linkLabelTransform, which is re-applied on every drag + // frame and must not query the DOM there + d.linkLabelLines = svgTextUtils.lineCount(e); + }) + .attr('transform', linkLabelTransform); + + sankeyLinkLabel.exit() + .transition() + .ease(c.ease).duration(c.duration) + .style('opacity', 0) + .remove(); + var sankeyNodeSet = sankey.selectAll('.' + c.cn.sankeyNodeSet) .data(repeat, keyFun); @@ -1033,7 +1181,7 @@ module.exports = function(gd, svg, calcData, layout, callbacks) { sankeyNode .call(attachPointerEvents, sankey, callbacks.nodeEvents) - .call(attachDragHandler, sankeyLink, callbacks, gd); // has to be here as it binds sankeyLink + .call(attachDragHandler, sankeyLink, sankeyLinkLabel, callbacks, gd); // has to be here as it binds sankeyLink sankeyNode .transition() @@ -1109,8 +1257,7 @@ module.exports = function(gd, svg, calcData, layout, callbacks) { var posY = d.reversed ? (d.visibleWidth + blockHeight) / 2 : (d.visibleWidth - blockHeight) / 2; - var flipV = d.reversed ? strRotate(90) : ('scale(-1,1)' + strRotate(90)); - return strTranslate(posY, pad) + flipV; + return strTranslate(posY, pad) + uprightTransform(d); } // horizontal: center along the node length, place just past the thickness edge. @@ -1121,7 +1268,7 @@ module.exports = function(gd, svg, calcData, layout, callbacks) { } else { posX += d.visibleWidth; } - return strTranslate(posX, posY) + (d.reversed ? 'scale(-1,1)' : ''); + return strTranslate(posX, posY) + uprightTransform(d); }); nodeLabel diff --git a/src/types/generated/schema.d.ts b/src/types/generated/schema.d.ts index 853b8c815f9..1ae9e7353e0 100644 --- a/src/types/generated/schema.d.ts +++ b/src/types/generated/schema.d.ts @@ -7014,6 +7014,20 @@ export interface SankeyData { * @default [] */ target?: Datum[] | Datum[][] | TypedArray; + /** Sets the font for the permanent link labels. */ + textfont?: Font; + /** + * Determines which trace information appears permanently on the links. Any combination of *label* and *value* joined with a *+* OR *none*. + * @default 'none' + */ + textinfo?: 'label' | 'value' | 'none' | (string & {}); + /** Template string used for rendering the information text that appears on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `label`, `value`, `valueLabel`, `source`, `target`, `customdata` and `meta`. */ + texttemplate?: string | string[]; + /** + * Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. + * @default '-' + */ + texttemplatefallback?: any; /** * A numeric value representing the flow volume value. * @default [] diff --git a/test/image/baselines/sankey_circular.png b/test/image/baselines/sankey_circular.png index 035057a261e..157ee504fde 100644 Binary files a/test/image/baselines/sankey_circular.png and b/test/image/baselines/sankey_circular.png differ diff --git a/test/image/baselines/sankey_circular_reversed.png b/test/image/baselines/sankey_circular_reversed.png index 94afbc7ca67..2bfcc44d55f 100644 Binary files a/test/image/baselines/sankey_circular_reversed.png and b/test/image/baselines/sankey_circular_reversed.png differ diff --git a/test/image/baselines/sankey_circular_vertical.png b/test/image/baselines/sankey_circular_vertical.png index e95ca469797..16edf466dd9 100644 Binary files a/test/image/baselines/sankey_circular_vertical.png and b/test/image/baselines/sankey_circular_vertical.png differ diff --git a/test/image/baselines/sankey_circular_vertical_reversed.png b/test/image/baselines/sankey_circular_vertical_reversed.png index 00062332681..15f910524dd 100644 Binary files a/test/image/baselines/sankey_circular_vertical_reversed.png and b/test/image/baselines/sankey_circular_vertical_reversed.png differ diff --git a/test/image/baselines/sankey_circular_with_arrows.png b/test/image/baselines/sankey_circular_with_arrows.png index 0b6bda3a22f..4f1d37306de 100644 Binary files a/test/image/baselines/sankey_circular_with_arrows.png and b/test/image/baselines/sankey_circular_with_arrows.png differ diff --git a/test/image/baselines/sankey_circular_with_arrows_reversed.png b/test/image/baselines/sankey_circular_with_arrows_reversed.png index 1908bdaf674..aed2391f7fd 100644 Binary files a/test/image/baselines/sankey_circular_with_arrows_reversed.png and b/test/image/baselines/sankey_circular_with_arrows_reversed.png differ diff --git a/test/image/baselines/sankey_circular_with_arrows_vertical.png b/test/image/baselines/sankey_circular_with_arrows_vertical.png index 5e5f35c372e..37f86f4b638 100644 Binary files a/test/image/baselines/sankey_circular_with_arrows_vertical.png and b/test/image/baselines/sankey_circular_with_arrows_vertical.png differ diff --git a/test/image/baselines/sankey_circular_with_arrows_vertical_reversed.png b/test/image/baselines/sankey_circular_with_arrows_vertical_reversed.png index 5a5ef73738e..383d9814df8 100644 Binary files a/test/image/baselines/sankey_circular_with_arrows_vertical_reversed.png and b/test/image/baselines/sankey_circular_with_arrows_vertical_reversed.png differ diff --git a/test/image/mocks/sankey_circular.json b/test/image/mocks/sankey_circular.json index 1bfb2acda35..bde6c9ab2d5 100644 --- a/test/image/mocks/sankey_circular.json +++ b/test/image/mocks/sankey_circular.json @@ -7,6 +7,7 @@ "label": ["0", "1", "2", "3", "4", "5", "6"] }, "link": { + "textinfo": "value", "source": [0, 0, 1, 2, 5, 4, 3], "target": [5, 3, 4, 3, 0, 2, 2], "value": [1, 2, 1, 1, 1, 1, 1] diff --git a/test/image/mocks/sankey_circular_reversed.json b/test/image/mocks/sankey_circular_reversed.json index 570d667b7f6..a5ef8285903 100644 --- a/test/image/mocks/sankey_circular_reversed.json +++ b/test/image/mocks/sankey_circular_reversed.json @@ -8,6 +8,7 @@ "label": ["0", "1", "2", "3", "4", "5", "6"] }, "link": { + "textinfo": "value", "source": [0, 0, 1, 2, 5, 4, 3], "target": [5, 3, 4, 3, 0, 2, 2], "value": [1, 2, 1, 1, 1, 1, 1] diff --git a/test/image/mocks/sankey_circular_vertical.json b/test/image/mocks/sankey_circular_vertical.json index ad7992c4e3b..bf84acdb705 100644 --- a/test/image/mocks/sankey_circular_vertical.json +++ b/test/image/mocks/sankey_circular_vertical.json @@ -8,6 +8,7 @@ "label": ["0", "1", "2", "3", "4", "5", "6"] }, "link": { + "textinfo": "value", "source": [0, 0, 1, 2, 5, 4, 3], "target": [5, 3, 4, 3, 0, 2, 2], "value": [1, 2, 1, 1, 1, 1, 1] diff --git a/test/image/mocks/sankey_circular_vertical_reversed.json b/test/image/mocks/sankey_circular_vertical_reversed.json index bdb8821b138..43af7103daa 100644 --- a/test/image/mocks/sankey_circular_vertical_reversed.json +++ b/test/image/mocks/sankey_circular_vertical_reversed.json @@ -9,6 +9,7 @@ "label": ["0", "1", "2", "3", "4", "5", "6"] }, "link": { + "textinfo": "value", "source": [0, 0, 1, 2, 5, 4, 3], "target": [5, 3, 4, 3, 0, 2, 2], "value": [1, 2, 1, 1, 1, 1, 1] diff --git a/test/image/mocks/sankey_circular_with_arrows.json b/test/image/mocks/sankey_circular_with_arrows.json index a105703ead9..6b9db4f973a 100644 --- a/test/image/mocks/sankey_circular_with_arrows.json +++ b/test/image/mocks/sankey_circular_with_arrows.json @@ -8,6 +8,7 @@ }, "link": { "arrowlen": 20, + "textinfo": "value", "source": [0, 0, 1, 2, 5, 4, 3], "target": [5, 3, 4, 3, 0, 2, 2], "value": [1, 2, 1, 1, 1, 1, 1] diff --git a/test/image/mocks/sankey_circular_with_arrows_reversed.json b/test/image/mocks/sankey_circular_with_arrows_reversed.json index 0550cc7b896..2f1ce4e411c 100644 --- a/test/image/mocks/sankey_circular_with_arrows_reversed.json +++ b/test/image/mocks/sankey_circular_with_arrows_reversed.json @@ -9,6 +9,7 @@ }, "link": { "arrowlen": 20, + "textinfo": "value", "source": [0, 0, 1, 2, 5, 4, 3], "target": [5, 3, 4, 3, 0, 2, 2], "value": [1, 2, 1, 1, 1, 1, 1] diff --git a/test/image/mocks/sankey_circular_with_arrows_vertical.json b/test/image/mocks/sankey_circular_with_arrows_vertical.json index 1f5672db7f6..8fb970a74fe 100644 --- a/test/image/mocks/sankey_circular_with_arrows_vertical.json +++ b/test/image/mocks/sankey_circular_with_arrows_vertical.json @@ -9,6 +9,7 @@ }, "link": { "arrowlen": 20, + "textinfo": "value", "source": [0, 0, 1, 2, 5, 4, 3], "target": [5, 3, 4, 3, 0, 2, 2], "value": [1, 2, 1, 1, 1, 1, 1] diff --git a/test/image/mocks/sankey_circular_with_arrows_vertical_reversed.json b/test/image/mocks/sankey_circular_with_arrows_vertical_reversed.json index 5effb07edb6..f8521edf5c3 100644 --- a/test/image/mocks/sankey_circular_with_arrows_vertical_reversed.json +++ b/test/image/mocks/sankey_circular_with_arrows_vertical_reversed.json @@ -10,6 +10,7 @@ }, "link": { "arrowlen": 20, + "textinfo": "value", "source": [0, 0, 1, 2, 5, 4, 3], "target": [5, 3, 4, 3, 0, 2, 2], "value": [1, 2, 1, 1, 1, 1, 1] diff --git a/test/jasmine/tests/sankey_test.js b/test/jasmine/tests/sankey_test.js index 5e3598002cc..061264375b7 100644 --- a/test/jasmine/tests/sankey_test.js +++ b/test/jasmine/tests/sankey_test.js @@ -158,6 +158,62 @@ describe('sankey tests', function () { .toBe(attributes.direction.dflt, 'invalid direction falls back to default'); }); + it('coerces the permanent link label values', () => { + const off = _supply({}); + + expect(off.link.textinfo) + .toBe(attributes.link.textinfo.dflt, 'link labels are off by default'); + expect(off.link.texttemplate) + .toBe(attributes.link.texttemplate.dflt, 'empty texttemplate by default'); + + // The feature is opt-in: while it is off nothing downstream of it is + // coerced, so an untouched trace keeps exactly the fullData it had before. + expect(off.link.textfont).toBe(undefined, 'textfont not coerced while off'); + expect(off.link.texttemplatefallback) + .toBe(undefined, 'texttemplatefallback not coerced while off'); + + ['label', 'value', 'label+value'].forEach((ti) => { + expect(_supply({link: {textinfo: ti}}).link.textinfo) + .toBe(ti, `${ti} is a valid textinfo`); + }); + expect(_supply({link: {textinfo: 'source+target'}}).link.textinfo) + .toBe(attributes.link.textinfo.dflt, 'invalid textinfo falls back to default'); + + expect(_supply({link: {texttemplate: '%{valueLabel}'}}).link.textfont) + .not.toBe(undefined, 'texttemplate alone also opts in'); + + // texttemplatefallback only matters once a template can actually + // reference a missing variable, so textinfo alone must not pull it + // in - only texttemplate does, and an explicit value wins over the + // attribute default. + expect(_supply({link: {textinfo: 'value'}}).link.texttemplatefallback) + .toBe(undefined, 'textinfo alone does not coerce texttemplatefallback'); + expect(_supply({link: {texttemplate: '%{valueLabel}'}}).link.texttemplatefallback) + .toBe(attributes.link.texttemplatefallback.dflt, 'texttemplate opts texttemplatefallback in'); + expect(_supply({link: {texttemplate: '%{nope}', texttemplatefallback: 'n/a'}}).link.texttemplatefallback) + .toBe('n/a', 'an explicit texttemplatefallback wins'); + }); + + it('coerces the permanent link label font from the trace level font', () => { + const layout = {font: {family: 'Arial', size: 11}}; + const traceIn = { + link: {textinfo: 'value'} + }; + + const inherited = _supplyWithLayout(traceIn, layout); + expect(inherited.link.textfont.family).toBe('Arial', 'inherits trace textfont'); + + const explicit = _supplyWithLayout( + Lib.extendDeep({}, traceIn, { + link: { + textfont: {family: 'Georgia'} + } + }), + layout + ); + expect(explicit.link.textfont.family).toBe('Georgia', 'link textfont wins'); + }); + it("'Sankey' layout dependent specification should have proper types", function () { var fullTrace = _supplyWithLayout( {}, @@ -1823,6 +1879,292 @@ describe('sankey tests', function () { }); }); + describe('permanent link labels', () => { + let gd; + + // A link that exists in every variant of the energy mock and is neither + // circular nor the first one in the list. + const SOURCE = 'Thermal generation'; + const TARGET = 'Losses'; + + beforeEach(() => { + gd = createGraphDiv(); + }); + + afterEach(() => { + Plotly.purge(gd); + destroyGraphDiv(); + }); + + // Screen-space bounding rect for a link, identified by its source and + // target labels (same idea as the helper in the hover label suite). + function rectForLink(sourceLabel, targetLabel) { + let rect; + d3SelectAll('.sankey-link').each(function(d) { + if(d.link.source.label === sourceLabel && d.link.target.label === targetLabel) { + rect = this.getBoundingClientRect(); + } + }); + if(!rect) throw new Error(`link not found: ${sourceLabel} -> ${targetLabel}`); + + return rect; + } + + function rectForLinkLabel(sourceLabel, targetLabel) { + let rect; + d3SelectAll('.sankey-link-label').each(function(d) { + if(d.link.source.label === sourceLabel && d.link.target.label === targetLabel) { + rect = this.getBoundingClientRect(); + } + }); + if(!rect) throw new Error(`link label not found: ${sourceLabel} -> ${targetLabel}`); + + return rect; + } + + function plotWith(patch) { + const fig = Lib.extendDeep({}, mock); + Lib.extendDeep(fig.data[0], patch); + return Plotly.newPlot(gd, fig); + } + + it('only renders link labels when they are opted in', (done) => { + plotWith({}) + .then(() => { + expect(d3SelectAll('.sankey-link-label').size()) + .toBe(0, 'no labels by default'); + + return Plotly.restyle(gd, 'link.textinfo', 'value'); + }) + .then(() => { + // Labels and link paths are built from the same filtered + // `graph.links` list, so the counts have to agree. + expect(d3SelectAll('.sankey-link-label').size()) + .toBe(d3SelectAll('.sankey-link').size(), 'one label per drawn link'); + + return Plotly.restyle(gd, 'link.textinfo', 'none'); + }) + .then(delay(600)) + .then(() => { + // No leftover empty nodes - they would still show up + // in the SVG/PNG export. The wait lets the exit transition + // (same duration as the link fade-out) finish. + expect(d3SelectAll('.sankey-link-label').size()) + .toBe(0, 'labels removed again'); + }) + .then(done, done.fail); + }); + + it('formats the label text from textinfo and texttemplate', (done) => { + function textFor(sourceLabel, targetLabel) { + let txt; + d3SelectAll('.sankey-link-label').each(function(d) { + if(d.link.source.label === sourceLabel && d.link.target.label === targetLabel) { + txt = d3Select(this).text(); + } + }); + return txt; + } + + plotWith({valueformat: '.0f', valuesuffix: 'TWh', link: {textinfo: 'value'}}) + .then(() => { + expect(textFor(SOURCE, TARGET)) + .toBe('787TWh', 'value formatted with the trace level format'); + + // source/target are the full node objects, so the template + // addresses their label property (same pattern as the hover + // template). + return Plotly.restyle( + gd, 'link.texttemplate', '%{source.label}/%{target.label}: %{valueLabel}'); + }) + .then(() => { + expect(textFor(SOURCE, TARGET)) + .toBe(`${SOURCE}/${TARGET}: 787TWh`, 'texttemplate overrides textinfo'); + + // An empty entry in an arrayOk texttemplate falls back to + // textinfo for that link alone - it does not hide the label. + // Leaving a single link unlabeled is only possible with + // textinfo 'none'. Pure string logic, so it is asserted here + // rather than in an image baseline. + const fd = gd._fullData[0]; + const srcIdx = fd.node.label.indexOf(SOURCE); + const tgtIdx = fd.node.label.indexOf(TARGET); + const perLink = fd.link.value.map((_, i) => { + return (fd.link.source[i] === srcIdx && fd.link.target[i] === tgtIdx) ? + '' : 'templated'; + }); + + return Plotly.restyle(gd, {'link.texttemplate': [perLink]}); + }) + .then(() => { + expect(textFor(SOURCE, TARGET)) + .toBe('787TWh', 'empty template entry falls back to textinfo'); + expect(textFor('Solid', 'Industry')) + .toBe('templated', 'other links still use the template'); + }) + .then(done, done.fail); + }); + + it('formats with the layout locale and resolves meta and the fallback', (done) => { + const fig = Lib.extendDeep({}, mock); + fig.layout.separators = ',.'; + Lib.extendDeep(fig.data[0], { + meta: ['GWh'], + link: { + texttemplate: '%{value:,.2f} %{meta[0]} %{notAVariable}', + texttemplatefallback: 'n/a' + } + }); + + Plotly.newPlot(gd, fig) + .then(() => { + const texts = []; + d3SelectAll('.sankey-link-label').each(function() { + texts.push(d3Select(this).text()); + }); + + expect(texts.length).toBeGreaterThan(0, 'labels were drawn'); + texts.forEach((t) => { + // ',.' swaps the decimal and thousands separators, which + // only reaches d3-format if _d3locale is handed to + // Lib.texttemplateString. %{meta[0]} likewise only + // resolves if trace._meta is part of its data array, and + // an unknown variable has to hit the fallback rather than + // rendering the string 'undefined'. + expect(t).toMatch(/^[\d.]+,\d{2} GWh n\/a$/); + }); + }) + .then(done, done.fail); + }); + + it('keeps link labels upright and centred per orientation and direction', (done) => { + function assertUprightAndCentred(msg) { + // The labels live inside the .sankey group and therefore inherit the + // matrix from sankeyTransform. uprightTransform has to cancel it exactly, + // so the glyphs' own screen matrix is the identity - without that the + // text renders mirrored (reversed) or rotated (vertical). + const ctm = d3Select('.sankey-link-label').node().getScreenCTM(); + expect(ctm.a).toBeCloseTo(1, 3, `${msg}: no x mirroring`); + expect(ctm.b).toBeCloseTo(0, 3, `${msg}: no rotation/skew`); + expect(ctm.c).toBeCloseTo(0, 3, `${msg}: no rotation/skew`); + expect(ctm.d).toBeCloseTo(1, 3, `${msg}: no y mirroring`); + + // ... while the anchor still sits on the midpoint of its own link. + // linkLabelTransform deliberately does *not* mirror the coordinates + // (the group transform already does); a label that stayed glued to + // the un-mirrored anchor would break this invariant. + const link = rectForLink(SOURCE, TARGET); + const label = rectForLinkLabel(SOURCE, TARGET); + expect(label.left + label.width / 2) + .toBeCloseTo(link.left + link.width / 2, -1, `${msg}: centred in x`); + expect(label.top + label.height / 2) + .toBeCloseTo(link.top + link.height / 2, -1, `${msg}: centred in y`); + } + + function plotOriented(orientation, direction) { + return plotWith({ + orientation: orientation, + direction: direction, + link: {textinfo: 'value'} + }).then(() => { + // Guard against a vacuously passing test: the assertions above are + // only meaningful if the group transform really was applied. + expect(d3Select('.sankey').attr('transform')) + .toContain(expectedMatrix[`${orientation}-${direction}`]); + assertUprightAndCentred(`${orientation} + ${direction}`); + }); + } + + const expectedMatrix = { + 'h-forward': 'matrix(1 0 0 1 0 0)', + 'h-reversed': 'matrix(-1 0 0 1 0 0)', + 'v-forward': 'matrix(0 1 1 0 0 0)', + 'v-reversed': 'matrix(0 -1 1 0 0 0)' + }; + + plotOriented('h', 'forward') + .then(() => plotOriented('h', 'reversed')) + .then(() => plotOriented('v', 'forward')) + .then(() => plotOriented('v', 'reversed')) + .then(done, done.fail); + }); + + it('centres link labels on the arrow body when arrows are shown', (done) => { + const arrowLen = 40; + + // The drawn path ends where the head starts, but the head itself + // still reaches the target, so the link's bounding box covers the + // full span - the label has to sit half a (clamped) head length + // left of its centre. + plotWith({link: {textinfo: 'value', arrowlen: arrowLen}}) + .then(() => { + let model; + d3SelectAll('.sankey-link').each((d) => { + if(d.link.source.label === SOURCE && d.link.target.label === TARGET) { + model = d; + } + }); + if(!model) throw new Error(`link not found: ${SOURCE} -> ${TARGET}`); + + const clampedLen = Math.min( + arrowLen, + Math.abs((model.link.target.x0 - model.link.source.x1) / 2) + ); + const link = rectForLink(SOURCE, TARGET); + const label = rectForLinkLabel(SOURCE, TARGET); + expect(label.left + label.width / 2) + .toBeCloseTo(link.left + link.width / 2 - clampedLen / 2, -1, + 'label centred on the arrow body, not the full span'); + }) + .then(done, done.fail); + }); + + it('moves the link labels along when a node is dragged', (done) => { + const nodeId = 4; // node with label 'Solid' + let before; + + plotWith({arrangement: 'freeform', link: {textinfo: 'value'}}) + .then(() => { + before = rectForLinkLabel('Solid', 'Industry'); + + const node = document.getElementsByClassName('sankey-node').item(nodeId); + return drag({node: node, dpos: [0, 100], nsteps: 10, timeDelay: 0}); + }) + .then(() => { + // updateShapes re-applies linkLabelTransform on every drag frame, + // so the label has to travel with the link it belongs to. + const after = rectForLinkLabel('Solid', 'Industry'); + expect(after.top).toBeGreaterThan(before.top + 20, 'label followed the drag'); + + const link = rectForLink('Solid', 'Industry'); + expect(after.top + after.height / 2) + .toBeCloseTo(link.top + link.height / 2, -1, 'still centred on its link'); + }) + .then(done, done.fail); + }); + + it('keeps the link labels on their links while a snap layout settles', (done) => { + const nodeId = 4; // node with label 'Solid' + + // Unlike freeform, snap keeps ticking a force simulation after the + // drop; startForce calls updateShapes on every tick, so the labels + // have to stay glued to their links through that as well, not just + // through the drag itself. + plotWith({arrangement: 'snap', link: {textinfo: 'value'}}) + .then(() => { + const node = document.getElementsByClassName('sankey-node').item(nodeId); + return drag({node: node, dpos: [0, 100], nsteps: 10, timeDelay: 2000}); + }) + .then(() => { + const link = rectForLink('Solid', 'Industry'); + const label = rectForLinkLabel('Solid', 'Industry'); + expect(label.top + label.height / 2) + .toBeCloseTo(link.top + link.height / 2, -1, 'still centred on its link once settled'); + }) + .then(done, done.fail); + }); + }); + describe('Test drag interactions', function () { ['freeform', 'perpendicular', 'snap'].forEach(function (arrangement) { describe('for arrangement ' + arrangement + ':', function () { diff --git a/test/plot-schema.json b/test/plot-schema.json index 7ab1ae48d50..30c9a8dad6d 100644 --- a/test/plot-schema.json +++ b/test/plot-schema.json @@ -52182,6 +52182,121 @@ "editType": "calc", "valType": "data_array" }, + "textfont": { + "color": { + "editType": "calc", + "valType": "color" + }, + "description": "Sets the font for the permanent link labels.", + "editType": "calc", + "family": { + "description": "HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available.", + "editType": "calc", + "noBlank": true, + "strict": true, + "valType": "string" + }, + "lineposition": { + "description": "Sets the kind of decoration line(s) with text, such as an *under*, *over* or *through* as well as combinations e.g. *under+over*, etc.", + "dflt": "none", + "editType": "calc", + "extras": [ + "none" + ], + "flags": [ + "under", + "over", + "through" + ], + "valType": "flaglist" + }, + "role": "object", + "shadow": { + "description": "Sets the shape and color of the shadow behind text. *auto* places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options.", + "dflt": "auto", + "editType": "calc", + "valType": "string" + }, + "size": { + "editType": "calc", + "min": 1, + "valType": "number" + }, + "style": { + "description": "Sets whether a font should be styled with a normal or italic face from its family.", + "dflt": "normal", + "editType": "calc", + "valType": "enumerated", + "values": [ + "normal", + "italic" + ] + }, + "textcase": { + "description": "Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized.", + "dflt": "normal", + "editType": "calc", + "valType": "enumerated", + "values": [ + "normal", + "word caps", + "upper", + "lower" + ] + }, + "variant": { + "description": "Sets the variant of the font.", + "dflt": "normal", + "editType": "calc", + "valType": "enumerated", + "values": [ + "normal", + "small-caps", + "all-small-caps", + "all-petite-caps", + "petite-caps", + "unicase" + ] + }, + "weight": { + "description": "Sets the weight (or boldness) of the font.", + "dflt": "normal", + "editType": "calc", + "extras": [ + "normal", + "bold" + ], + "max": 1000, + "min": 1, + "valType": "integer" + } + }, + "textinfo": { + "description": "Determines which trace information appears permanently on the links. Any combination of *label* and *value* joined with a *+* OR *none*.", + "dflt": "none", + "editType": "calc", + "extras": [ + "none" + ], + "flags": [ + "label", + "value" + ], + "valType": "flaglist" + }, + "texttemplate": { + "arrayOk": true, + "description": "Template string used for rendering the information text that appears on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example \"y: %{y}\". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example \"Price: %{y:$.2f}\". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example \"Day: %{2019-01-01|%A}\". https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of \"data: %{x}, %{y}\" will result in a value of \"data: 1, %{y}\" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `label`, `value`, `valueLabel`, `source`, `target`, `customdata` and `meta`.", + "dflt": "", + "editType": "calc", + "valType": "string" + }, + "texttemplatefallback": { + "description": "Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed.", + "dflt": "-", + "editType": "calc", + "valType": "any" + }, "value": { "description": "A numeric value representing the flow volume value.", "dflt": [],