Sum of Orders by Team and FromStep, as a sunburst
How does the Sum of Orders split by Team, and then by FromStep?
Twenty-two hand-offs between the twelve steps of an order fulfilment process, from order received to delivered, each with the team that owns the step it starts from and the number of orders that took that path. Backorders, cancellations, rework and returns loop back or leave the main line, so it is a real process rather than a straight chain. A from-step, a to-step and a team make a flowchart with a swimlane per team.
Order Fulfilment Process Flow: 22 rows, 4 columns. Download the CSV
| FromStep | ToStep | Team | Sum of Orders |
|---|---|---|---|
| Order received | Stock check | Receiving | 8150 |
| Order received | Backorder | Receiving | 280 |
| Order received | Cancelled | Receiving | 170 |
| Stock check | Pick | Receiving | 8080 |
| Stock check | Backorder | Receiving | 690 |
| Stock check | Cancelled | Receiving | 80 |
| Backorder | Stock check | Receiving | 700 |
| Backorder | Pick | Receiving | 260 |
| Backorder | Cancelled | Receiving | 130 |
| Pick | Pack | Warehouse | 8180 |

How to read it
Read from the center outward: each arc's angle is its share, and an outer arc belongs to the arc inside it. Warehouse takes the largest inner arc, 41%.
The chart's code (50 KB of JavaScript, D3)
It carries its own copies of these helpers: llmText, llmFrameTween, llmRangeBrush, llmSlider, llmNumberEntry, llmSegmented, llmPredictor, llmResponseCurves, llmTerritories, llmCutoff, llmContrast, llmSurvival, llmModelFormat, llmSubgroups, llmSegments, llmGlyphs, llmBreadcrumb, llmKeyframes, llmScrubber, llmValueColumn, llmValueRamp, llmFitLabel, llmThinLabels, llmFitAxisTicks, llmSymlog, llmClipOutliers, llmGeoZoom, llmGeoPointNotes, llmMapLabels, llmGeoMarks, llmPlaceUnit, llmWorldFit, llmRegionFit, llmFlowKey, llmFlowArcs, llmFrameFill, llmTooltip, llmSwarm, llmKde, llmOrbit3d, llmBoundedScale, llmBivariate, llmLegendLayout, llmPager, llmTableFrame, llmGrid, llmUtcDays, llmPeriodGrid, llmTileGrid, llmMermaid, llmDecomp, llmTopN, llmFlipDeck, llmFilterScope, llmDisplayName, llmThemeColors, llmWordCloud.
// bic:keyboard-marks
// English whatever the chart's language. A helper now asks for each one here and declares `// @requires llmText`:
d3.llmText = function (key, english, vars, count) {
var fill = function (s, vv) {
vv = vv || vars;
return String(s).replace(/\{([a-z][a-z0-9_]*)\}/g, function (m, k) {
return vv && Object.prototype.hasOwnProperty.call(vv, k) ? String(vv[k]) : m;
});
};
var en = fill(english);
var host = d3.llmText.host;
if (typeof host === 'function') {
try { var h = host(key, english, vars, count); if (typeof h === 'string' && h !== en && h !== english) return h; } catch (e) {}
}
var cat = d3.llmText._cat, lang = d3.llmText._lang;
if (cat && lang && Object.prototype.hasOwnProperty.call(cat, key)) {
var v = cat[key];
if (v && typeof v === 'object') {
var form = 'other';
try { form = new Intl.PluralRules(lang).select(typeof count === 'number' ? count : 0); } catch (e) {}
v = v[form] != null ? v[form] : v.other != null ? v.other : v.many;
}
var tv = vars;
if (vars && typeof vars.grain === 'string' && Object.prototype.hasOwnProperty.call(cat, 'd3.grain.' + vars.grain)
&& typeof cat['d3.grain.' + vars.grain] === 'string' && cat['d3.grain.' + vars.grain]) {
tv = {};
for (var vk in vars) if (Object.prototype.hasOwnProperty.call(vars, vk)) tv[vk] = vars[vk];
tv.grain = cat['d3.grain.' + vars.grain];
}
if (typeof v === 'string' && v) {
var t = fill(v, tv), left = String(t).match(/\{[a-z][a-z0-9_]*\}/g) || [];
if (left.every(function (x) { return en.indexOf(x) >= 0; })) return t;
}
}
return en;
};
d3.llmText._lang = null;
d3.llmText._cat = null;
d3.llmText.use = function (lang, catalog) {
d3.llmText._lang = lang || null; d3.llmText._cat = catalog || null;
d3.llmText.dates(lang);
};
d3.llmText.dates = function (lang) {
try {
var o = d3.llmText._d3orig;
if (!o) {
o = d3.llmText._d3orig = { timeFormat: d3.timeFormat, utcFormat: d3.utcFormat, timeParse: d3.timeParse,
utcParse: d3.utcParse, scaleTime: d3.scaleTime, scaleUtc: d3.scaleUtc };
}
var restore = function () { for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k) && o[k]) d3[k] = o[k]; };
var base = String(lang || '').toLowerCase().split(/[-_]/)[0];
if (!base || base === 'en' || typeof d3.timeFormatLocale !== 'function' || typeof Intl === 'undefined') { restore(); return; }
var mk = function (opts) { var x = { timeZone: 'UTC' }; for (var k in opts) x[k] = opts[k]; return new Intl.DateTimeFormat(lang, x); };
var months = [], shortMonths = [], days = [], shortDays = [], m, w;
var fM = mk({ month: 'long' }), fMs = mk({ month: 'short' }), fD = mk({ weekday: 'long' }), fDs = mk({ weekday: 'short' });
for (m = 0; m < 12; m++) { var dm = new Date(Date.UTC(2021, m, 15)); months.push(fM.format(dm)); shortMonths.push(fMs.format(dm)); }
for (w = 0; w < 7; w++) { var dw = new Date(Date.UTC(2021, 0, 3 + w)); days.push(fD.format(dw)); shortDays.push(fDs.format(dw)); } // 3 Jan 2021 is a Sunday
if (months[0] === 'January' && days[0] === 'Sunday') { restore(); return; } // no names for the language here: keep d3's
var L = d3.timeFormatLocale({ dateTime: '%x %X', date: '%Y-%m-%d', time: '%H:%M:%S', periods: ['AM', 'PM'],
days: days, shortDays: shortDays, months: months, shortMonths: shortMonths });
d3.timeFormat = L.format; d3.utcFormat = L.utcFormat; d3.timeParse = L.parse; d3.utcParse = L.utcParse;
var multi = function (utc) {
var F = utc ? L.utcFormat : L.format, P = utc ? 'utc' : 'time';
var iv = function (n) { return d3[P + n]; };
var fL = F('.%L'), fS = F(':%S'), fMi = F('%H:%M'), fH = F('%H:00'), fDy = F('%a %d'), fW = F('%b %d'), fMo = F('%B'), fY = F('%Y');
var wk = utc ? d3.utcSunday : d3.timeSunday;
return function (date) {
return (iv('Second')(date) < date ? fL : iv('Minute')(date) < date ? fS : iv('Hour')(date) < date ? fMi
: iv('Day')(date) < date ? fH : iv('Month')(date) < date ? (wk(date) < date ? fDy : fW)
: iv('Year')(date) < date ? fMo : fY)(date);
};
};
var wrap = function (make, utc) {
if (typeof make !== 'function') return make;
var dress = function (sc) {
var cp = sc.copy;
sc.tickFormat = function (count, spec) { return spec == null ? multi(utc) : (utc ? L.utcFormat : L.format)(spec); };
if (typeof cp === 'function') sc.copy = function () { return dress(cp.apply(sc, arguments)); };
return sc;
};
return function () { return dress(make.apply(this, arguments)); };
};
d3.scaleTime = wrap(o.scaleTime, false); d3.scaleUtc = wrap(o.scaleUtc, true);
} catch (e) {}
};
// @requires llmText
d3.llmBreadcrumb = function (svg, cfg) {
var TYPE_FLOOR = 10; // the minimum readable type, px
cfg = cfg || {};
var container = cfg.container, options = cfg.options || {}, root = cfg.root;
var noop = { focus: function () {}, up: function () {}, current: function () { return null; },
path: function () { return []; } };
if (!svg || !root || !container || typeof root.ancestors !== 'function') return noop;
var arcOf = typeof cfg.arcOf === 'function' ? cfg.arcOf : function () { return null; };
var onFocus = typeof cfg.onFocus === 'function' ? cfg.onFocus : function () {};
var key = cfg.stateKey || 'focusPath';
var settleMs = +cfg.settleMs >= 0 && cfg.settleMs !== null && cfg.settleMs !== '' ? +cfg.settleMs : 800;
var fs = Math.max(TYPE_FLOOR, +cfg.fontSize > 0 ? +cfg.fontSize
: Math.min(14, Math.min(options.width || 600, options.height || 400) / 55));
var fg = options.themeFg || '#252423';
var rootLabel = cfg.rootLabel != null ? String(cfg.rootLabel) : 'All';
var stripW = +cfg.width > 0 ? +cfg.width : Math.max(fs * 10, (options.width || 600) - fs * 2);
var hit = Math.max(20, Math.round(fs * 1.6));
var nameOf = function (d) { return d && d.data && d.data.name != null ? String(d.data.name) : ''; };
var labelsOf = function (node) { return node.ancestors().reverse().slice(1).map(nameOf); };
var cur = null, pending = null;
var g = svg.append('g').attr('class', 'llm-breadcrumb')
.attr('transform', 'translate(' + (+cfg.x || 0) + ',' + (+cfg.y || 0) + ')');
function resolve(labels) {
if (!Array.isArray(labels)) return root;
var n = root;
for (var i = 0; i < labels.length; i++) {
var want = labels[i];
if (typeof want !== 'string' && typeof want !== 'number') return root;
var kids = n.children || [], next = null;
for (var k = 0; k < kids.length; k++) { if (nameOf(kids[k]) === String(want)) { next = kids[k]; break; } }
if (!next) return root;
n = next;
}
return n;
}
function measure(textSel, txt) {
try {
var node = textSel.node();
if (node && typeof node.getComputedTextLength === 'function') {
var w = node.getComputedTextLength();
if (w > 0) return w;
}
} catch (e) { /* fall through to the estimate */ }
return String(txt).length * fs * 0.6;
}
function paint() {
g.selectAll('*').remove();
var chain = cur.ancestors().reverse(); // root first, the focus last
var sep = fs * 1.1;
var probe = g.append('text').attr('font-size', fs);
var widthOfText = function (txt) { probe.text(txt); return measure(probe, txt); };
var crumbW = function (txt) { return Math.max(hit, widthOfText(txt) + fs * 0.6); };
var mid = chain.slice(1, -1);
var hiddenDeepest = null;
var list = function () {
var out = [{ node: root, text: rootLabel }];
if (hiddenDeepest) out.push({ node: hiddenDeepest, text: '...' });
mid.forEach(function (n) { out.push({ node: n, text: nameOf(n) }); });
if (cur !== root) out.push({ node: cur, text: nameOf(cur) });
return out;
};
var total = function (items) {
var t = 0;
items.forEach(function (c, i) { t += crumbW(c.text); if (i < items.length - 1) t += sep; });
return t;
};
var shown = list();
while (mid.length && total(shown) > stripW) {
hiddenDeepest = mid.shift();
shown = list();
}
var lastItem = shown[shown.length - 1];
if (shown.length > 1 && total(shown) > stripW) {
var room = stripW - (total(shown) - crumbW(lastItem.text)) - fs * 0.6;
var full = lastItem.text, cut = full;
while (cut.length > 1 && widthOfText(cut + '...') > room) cut = cut.slice(0, -1);
lastItem.text = cut.length < full.length ? cut + '...' : full;
lastItem.title = full;
}
probe.remove();
var xx = 0;
shown.forEach(function (c, i) {
var last = i === shown.length - 1;
var crumb = g.append('g').attr('class', last ? 'llm-breadcrumb-crumb' : 'llm-breadcrumb-crumb lch-control')
.attr('aria-label', last ? null : d3.llmText('d3.breadcrumb.back_to', 'Back to {name}', { name: c.text })).attr('aria-disabled', last ? 'true' : null)
.attr('transform', 'translate(' + xx + ',0)')
.style('cursor', last ? 'default' : 'pointer');
var t = crumb.append('text').attr('y', 0).attr('font-size', fs)
.attr('font-weight', last ? 'bold' : 'normal').attr('fill', fg).text(c.text);
if (c.title) t.append('title').text(c.title);
var tw = crumbW(c.text);
crumb.insert('rect', 'text').attr('x', -fs * 0.3).attr('y', -hit + fs * 0.35)
.attr('width', tw).attr('height', hit).attr('fill', 'transparent').attr('pointer-events', 'all');
var target = last ? null : c.node;
crumb.on('click', function (e) {
if (e && e.stopPropagation) e.stopPropagation();
if (target) focus(target);
});
xx += tw;
if (!last) {
g.append('text').attr('x', xx + sep * 0.2).attr('y', 0).attr('font-size', fs).attr('fill', fg)
.attr('fill-opacity', 0.6).attr('pointer-events', 'none').text('>');
xx += sep;
}
});
}
function publish(node) {
var detail = node === root ? { clear: true, source: 'user' } : { mark: arcOf(node), source: 'user' };
if (!detail.clear && !detail.mark) return; // nothing the host could read rows from
try {
container.dispatchEvent(new CustomEvent('llm-xfilter-refresh', { bubbles: true, detail: detail }));
} catch (e) { /* a host with no event support still zooms */ }
}
function persistLater() {
if (typeof options.setUiState !== 'function') return;
if (pending) pending.stop();
pending = d3.timeout(function () {
pending = null;
var live = container.__lchUiLiveOpts === options && container.__lchUiLiveSeed === options.uiState
? container.__lchUiLive : null;
var base = live || (options.uiState && typeof options.uiState === 'object' ? options.uiState : {});
var next = {}, k;
for (k in base) if (Object.prototype.hasOwnProperty.call(base, k)) next[k] = base[k];
next[key] = labelsOf(cur);
container.__lchUiLive = next; container.__lchUiLiveOpts = options; container.__lchUiLiveSeed = options.uiState;
try { options.setUiState(next); } catch (e) { /* persistence is advisory, never fatal */ }
}, settleMs);
}
function focus(node, opts) {
opts = opts || {};
if (!node || typeof node.ancestors !== 'function') node = root;
if (node === cur && !opts.restored) return; // already the focus: nothing to say
var previous = cur, restored = !!opts.restored, doPublish = opts.publish !== false && !restored;
cur = node;
paint();
onFocus(node, { restored: restored, publish: doPublish, previous: previous });
if (doPublish) publish(node);
if (!restored) persistLater();
}
container.__llmXfClear = function () { if (cur !== root) focus(root); };
var ui = options.uiState && typeof options.uiState === 'object' ? options.uiState : {};
focus(resolve(ui[key]), { restored: true }); // the first paint: silent, no transition
return {
focus: function (node, opts) { focus(node, opts); },
up: function () { focus(cur && cur.parent ? cur.parent : root); },
current: function () { return cur; },
path: function () { return cur ? labelsOf(cur) : []; }
};
};
d3.llmFitLabel = function (sel, widthAccessor, opts) {
var TYPE_FLOOR = 10; // the minimum readable type, px: a string is fitted at no smaller size than a chart may draw it
if (widthAccessor != null && typeof widthAccessor === 'object' && !Array.isArray(widthAccessor)) {
var wobj = widthAccessor, wopts = {};
for (var wk in wobj) if (Object.prototype.hasOwnProperty.call(wobj, wk) && wk !== 'width' && wk !== 'room') wopts[wk] = wobj[wk];
if (opts != null && typeof opts === 'object') {
for (var wk2 in opts) if (Object.prototype.hasOwnProperty.call(opts, wk2)) wopts[wk2] = opts[wk2];
} else if (typeof opts === 'number' && opts > 0 && wopts.fontSize == null) {
wopts.fontSize = Math.max(TYPE_FLOOR, opts);
}
widthAccessor = wobj.width != null ? wobj.width : wobj.room;
opts = wopts;
}
if (typeof sel === 'string' || typeof sel === 'number') {
var so = (opts != null && typeof opts === 'object') ? opts
: ((arguments[3] != null && typeof arguments[3] === 'object') ? arguments[3] : {});
var sfs = Math.max(TYPE_FLOOR, (typeof opts === 'number' && opts > 0) ? opts : (+so.fontSize > 0 ? +so.fontSize : TYPE_FLOOR));
var sopts = {};
for (var sk in so) if (Object.prototype.hasOwnProperty.call(so, sk)) sopts[sk] = so[sk];
sopts.text = String(sel);
sopts.shrinkTo = null;
var holder = null, sn = null;
try {
if (typeof document !== 'undefined' && document && document.body && document.createElementNS) {
holder = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
holder.setAttribute('width', '0'); holder.setAttribute('height', '0');
holder.style.position = 'absolute'; holder.style.left = '-10000px'; holder.style.visibility = 'hidden';
sn = document.createElementNS('http://www.w3.org/2000/svg', 'text');
holder.appendChild(sn);
document.body.appendChild(holder);
}
} catch (e) { holder = null; sn = null; }
if (!sn) {
sn = { textContent: '', style: {}, fs: sfs,
getAttribute: function (a) { return a === 'font-size' ? String(sn.fs) : null; },
setAttribute: function (a, v) { if (a === 'font-size') sn.fs = +v; } };
}
var fitted;
try {
sn.setAttribute('font-size', String(sfs));
if (so.fontFamily) sn.setAttribute('font-family', String(so.fontFamily));
if (so.fontWeight) sn.setAttribute('font-weight', String(so.fontWeight));
d3.llmFitLabel({ each: function (fn) { fn.call(sn, null, 0); return this; } }, widthAccessor, sopts);
fitted = sn.textContent == null ? '' : String(sn.textContent);
} catch (e) { fitted = String(sel); }
try { if (holder && holder.parentNode) holder.parentNode.removeChild(holder); } catch (e) { /* detached */ }
return fitted;
}
opts = opts || {};
var pad = opts.pad == null ? 4 : opts.pad;
var minWidth = opts.minWidth == null ? 14 : opts.minWidth;
var ell = opts.ellipsis == null ? '\u2026' : opts.ellipsis;
var fallbackFs = opts.fontSize == null ? 10 : opts.fontSize;
var shrinkTo = opts.shrinkTo == null ? null : +opts.shrinkTo;
var overflow = opts.overflow === 'drop' ? 'drop' : 'truncate';
var sibs = Array.isArray(opts.distinctFrom) ? opts.distinctFrom : null;
if (!sel || typeof sel.each !== 'function') return sel;
var DIGIT = /[0-9\u0660-\u0669\u06F0-\u06F9\u0966-\u096F\u09E6-\u09EF\uFF10-\uFF19]/;
var JOIN = /[.,'\u00A0\u202F\u2019\u066B\u066C]/;
var GLUED = /[A-Za-z%\u2030]/;
var LEAD = /[+\-\u2212$\u20AC\u00A3\u00A5\u20B9]/;
function numberSafeCut(s, lo) {
if (!(lo > 0) || lo >= s.length) return lo;
var a = s.charAt(lo - 1), b = s.charAt(lo);
var splits = DIGIT.test(a)
? (DIGIT.test(b) || GLUED.test(b) || (JOIN.test(b) && DIGIT.test(s.charAt(lo + 1))))
: (lo >= 2 && JOIN.test(a) && DIGIT.test(s.charAt(lo - 2)) && DIGIT.test(b));
if (!splits) return lo;
var i = lo;
while (i > 0 && (DIGIT.test(s.charAt(i - 1))
|| (i >= 2 && JOIN.test(s.charAt(i - 1)) && DIGIT.test(s.charAt(i - 2))))) i--;
while (i > 0 && LEAD.test(s.charAt(i - 1))) i--;
while (i > 0 && /\s/.test(s.charAt(i - 1))) i--;
return i;
}
function fontSizeOf(node) {
try {
var a = parseFloat(node.getAttribute && node.getAttribute('font-size'));
if (a > 0) return a;
var s = node.style && node.style.fontSize ? parseFloat(node.style.fontSize) : NaN;
if (s > 0) return s;
} catch (e) { /* fall through */ }
return fallbackFs;
}
function setFontSize(node, fs) {
try { if (node.setAttribute) node.setAttribute('font-size', String(fs)); } catch (e) { /* detached */ }
}
function measure(node, txt) {
try {
if (typeof node.getComputedTextLength === 'function') {
var w = node.getComputedTextLength();
if (w > 0) return w;
}
} catch (e) { /* fall through */ }
return String(txt).length * fontSizeOf(node) * 0.6;
}
function ownerSvg(node) {
try {
if (node.ownerSVGElement) return node.ownerSVGElement;
for (var p = node.parentNode; p; p = p.parentNode) {
if (p.nodeName && String(p.nodeName).toLowerCase() === 'svg') return p;
}
} catch (e) { /* detached */ }
return null;
}
function shownText(node) {
var kids = node && node.childNodes;
if (!kids || !kids.length) return node.textContent == null ? '' : String(node.textContent);
var s = '';
for (var c = 0; c < kids.length; c++) {
var k = kids[c];
if (k.nodeType === 3) s += k.nodeValue;
else if (k.nodeType === 1 && String(k.nodeName).toLowerCase() !== 'title') s += shownText(k);
}
return s;
}
function setShown(node, s) {
var kids = node.childNodes, keep = [];
if (kids && kids.length) {
for (var c = 0; c < kids.length; c++) {
if (kids[c].nodeType === 1 && String(kids[c].nodeName).toLowerCase() === 'title') keep.push(kids[c]);
}
}
node.textContent = s;
for (var q = 0; q < keep.length; q++) node.appendChild(keep[q]);
}
function hiddenIn(node, svg) {
try {
for (var p = node, hop = 0; p && hop < 64; p = p.parentNode, hop++) {
if (p.getAttribute && (p.getAttribute('display') === 'none' || p.getAttribute('visibility') === 'hidden')) return true;
if (p.style && (p.style.display === 'none' || p.style.visibility === 'hidden')) return true;
if (p === svg) break;
}
} catch (e) { /* read as shown */ }
return false;
}
function fittedFrom(node) {
return node.__llmFitFrom != null ? node.__llmFitFrom : node.__llmFullLabel;
}
function live(svg, en) {
if (shownText(en.node) !== en.visible) return false;
if (fittedFrom(en.node) != null && String(fittedFrom(en.node)) !== en.full) return false;
try { if (typeof svg.contains === 'function' && !svg.contains(en.node)) return false; } catch (e) { /* keep */ }
return true;
}
function endsWithText(s, t) { return s.length >= t.length && s.slice(s.length - t.length) === t; }
function ending(en, others) {
var f = en.full, n = en.node, E = en.ell;
if (en.drop) return '';
var fits = function (s) { setShown(n, s); return measure(n, s) <= en.room; };
var t = -1;
for (var s = f.length - 1; s >= 1 && t < 0; s--) {
var tl = f.slice(s), alone = true;
for (var o = 0; o < others.length && alone; o++) if (endsWithText(others[o], tl)) alone = false;
if (alone) t = s;
}
if (t < 1) return '';
if (DIGIT.test(f.charAt(t)) && (DIGIT.test(f.charAt(t - 1)) || (t >= 2 && JOIN.test(f.charAt(t - 1)) && DIGIT.test(f.charAt(t - 2))))) {
while (t > 0 && (DIGIT.test(f.charAt(t - 1)) || (t >= 2 && JOIN.test(f.charAt(t - 1)) && DIGIT.test(f.charAt(t - 2))))) t--;
}
if (t < 1) return '';
var ws = t;
while (ws > 0 && !/\s/.test(f.charAt(ws - 1))) ws--;
if (ws > 0 && ws < t && fits(E + f.slice(ws))) t = ws;
else if (!fits(E + f.slice(t))) return '';
var tail = f.slice(t), lo = 0, hi = t - 1;
while (lo < hi) {
var mid = (lo + hi + 1) >> 1;
if (fits(f.slice(0, mid) + E + tail)) lo = mid; else hi = mid - 1;
}
var head = f.slice(0, numberSafeCut(f, lo)).replace(/\s+$/, '');
if (head.length < 2) head = '';
return head + E + tail;
}
function distinguish(group) {
var g, h, s, en, others;
for (g = 0; g < group.length; g++) {
en = group[g];
others = [];
for (h = 0; h < group.length; h++) if (group[h].full !== en.full) others.push(group[h].full);
try { s = ending(en, others); } catch (e) { s = ''; }
setShown(en.node, s);
en.visible = shownText(en.node);
}
for (g = 0; g < group.length; g++) {
for (h = g + 1; h < group.length; h++) {
var a = group[g], b = group[h];
if (a.visible && a.visible === b.visible && a.full !== b.full) {
setShown(a.node, ''); a.visible = '';
setShown(b.node, ''); b.visible = '';
}
}
}
}
function clashes(reg, svg, en) {
var group = [en], differ = false;
if (hiddenIn(en.node, svg)) return group;
for (var k = reg.length - 1; k >= 0; k--) {
var o = reg[k];
if (o === en || o.visible !== en.visible) continue;
if (!live(svg, o)) { reg.splice(k, 1); continue; }
if (hiddenIn(o.node, svg)) continue;
group.push(o);
if (o.full !== en.full) differ = true;
}
return differ ? group : [en];
}
function settle(node, room) {
var svg = ownerSvg(node);
if (!svg) return;
var reg = svg.__llmFitRegistry;
if (!Array.isArray(reg)) { reg = []; svg.__llmFitRegistry = reg; }
var k;
for (k = reg.length - 1; k >= 0; k--) if (reg[k].node === node) reg.splice(k, 1);
if (reg.length >= (reg.sweepAt || 256)) {
for (k = reg.length - 1; k >= 0; k--) if (!live(svg, reg[k])) reg.splice(k, 1);
reg.sweepAt = Math.max(256, reg.length * 2);
}
var vis = shownText(node);
if (!(room > 0) || !vis) return;
var me = { node: node, full: fittedFrom(node) == null ? vis : String(fittedFrom(node)),
visible: vis, room: room, ell: ell, drop: overflow === 'drop' };
reg.push(me);
var queue = [me];
for (var round = 0; queue.length && round < 32; round++) {
var en = queue.shift();
if (!en.visible) continue;
var group = clashes(reg, svg, en);
if (group.length < 2) continue;
distinguish(group);
for (var g = 0; g < group.length; g++) if (group[g].visible) queue.push(group[g]);
}
}
function fitOne(node, d, i) {
var full, alts = [];
if (opts.text != null) {
try {
full = typeof opts.text === 'function' ? opts.text.call(node, d, i) : opts.text;
} catch (e) { full = ''; }
if (Array.isArray(full)) { alts = full.slice(1); full = full[0]; }
full = full == null ? '' : String(full);
node.__llmFullLabel = full;
node.textContent = full; // authoritative: an EMPTY label must CLEAR the node,
if (!full) return; // never leave the previous frame's text standing
} else {
full = node.__llmFullLabel;
if (full == null) {
full = node.textContent == null ? '' : String(node.textContent);
node.__llmFullLabel = full;
}
if (!full) return;
}
node.__llmFitFrom = null;
var fo = opts.forms;
if (typeof fo === 'function') { try { fo = fo.call(node, d, i); } catch (e) { fo = null; } }
if (fo != null) alts = alts.concat(Array.isArray(fo) ? fo : [fo]);
var cands = [full];
for (var ci = 0; ci < alts.length; ci++) {
var alt = alts[ci] == null ? '' : String(alts[ci]);
if (alt && cands.indexOf(alt) < 0) cands.push(alt);
}
var room;
try {
room = typeof widthAccessor === 'function'
? widthAccessor.call(node, d, i)
: widthAccessor;
} catch (e) { room = 0; }
room = (room == null ? 0 : +room) - pad * 2;
if (!(room > 0) || room < minWidth) { node.textContent = ''; return room; }
if (shrinkTo != null) {
if (node.__llmFullFontSize == null) node.__llmFullFontSize = fontSizeOf(node);
setFontSize(node, node.__llmFullFontSize);
}
node.textContent = full;
var w = measure(node, full);
if (w <= room) return room; // fits whole - done
var c;
for (c = 1; c < cands.length; c++) {
node.textContent = cands[c];
if (measure(node, cands[c]) <= room) { node.__llmFitFrom = cands[c]; return room; }
}
if (shrinkTo != null && shrinkTo > 0) {
for (c = 0; c < cands.length; c++) {
setFontSize(node, node.__llmFullFontSize);
node.textContent = cands[c];
var cur = fontSizeOf(node), wc = measure(node, cands[c]);
if (!(cur > shrinkTo)) break;
var fs = Math.max(shrinkTo, Math.floor((cur * room / wc) * 2) / 2);
for (; fs >= shrinkTo; fs -= 0.5) {
setFontSize(node, fs);
if (measure(node, cands[c]) <= room) { if (c) node.__llmFitFrom = cands[c]; return room; }
}
setFontSize(node, shrinkTo);
if (measure(node, cands[c]) <= room) { if (c) node.__llmFitFrom = cands[c]; return room; }
}
}
if (cands.length > 1) { full = cands[cands.length - 1]; node.__llmFitFrom = full; }
node.textContent = full;
if (overflow === 'drop') { node.textContent = ''; return room; }
var lo = 0, hi = full.length;
while (lo < hi) {
var mid = (lo + hi + 1) >> 1;
node.textContent = full.slice(0, mid) + ell;
if (measure(node, node.textContent) <= room) lo = mid; else hi = mid - 1;
}
lo = numberSafeCut(full, lo);
if (sibs) {
var shared = 0;
for (var si = 0; si < sibs.length; si++) {
var o = sibs[si] == null ? '' : String(sibs[si]);
if (o === full) continue;
var k = 0;
while (k < o.length && k < full.length && o.charAt(k) === full.charAt(k)) k++;
if (k > shared) shared = k;
}
if (shared > 0 && lo <= shared) {
var a = 1, b = full.length;
while (a < b) {
var m = (a + b) >> 1;
node.textContent = ell + full.slice(m);
if (measure(node, node.textContent) <= room) b = m; else a = m + 1;
}
var inNum = function (i) {
return i > 0 && i < full.length && DIGIT.test(full.charAt(i))
&& (DIGIT.test(full.charAt(i - 1)) || (i >= 2 && JOIN.test(full.charAt(i - 1)) && DIGIT.test(full.charAt(i - 2))));
};
if (inNum(a)) {
var t0 = a;
while (t0 > 0 && (DIGIT.test(full.charAt(t0 - 1)) || (t0 >= 2 && JOIN.test(full.charAt(t0 - 1)) && DIGIT.test(full.charAt(t0 - 2))))) t0--;
node.textContent = ell + full.slice(t0);
a = measure(node, node.textContent) <= room ? t0 : full.length;
}
node.textContent = a < full.length ? ell + full.slice(a) : '';
return room;
}
}
node.textContent = lo > 0 ? full.slice(0, lo) + ell : '';
return room;
}
sel.each(function (d, i) {
var room = fitOne(this, d, i);
try { settle(this, room); } catch (e) { /* a failed sibling check leaves the fit as it stands */ }
});
return sel;
};
d3.llmTooltip = function (container, opts) {
opts = opts || {};
var gap = opts.gap == null ? 12 : opts.gap; // distance from the cursor
var edge = opts.edge == null ? 4 : opts.edge; // minimum distance from the container edge
var routed = false; // true while the HOST is showing our content
var lastContent = ''; // what to re-send if the host is driving
var lastEv = null; // where the cursor last was, for a re-fit
var host = (container && typeof container.node === 'function') ? container.node() : container;
var noop = { show: function () { return this; }, move: function () { return this; }, hide: function () { return this; },
html: function () { return this; }, text: function () { return this; }, node: null };
if (!host || !host.appendChild) return noop;
var mount = host;
if (mount.tagName && String(mount.tagName).toLowerCase() === 'svg' && mount.parentNode) {
mount = mount.parentNode;
}
if (!mount || !mount.appendChild) return noop;
try {
var pos = (typeof getComputedStyle === 'function') ? getComputedStyle(mount).position : '';
if (!pos || pos === 'static') mount.style.position = 'relative';
} catch (e) { /* jsdom / exec-gate: no layout engine, positioning is inert anyway */ }
var tip = mount.__llmTip;
if (!tip || tip.parentNode !== mount) {
tip = document.createElement('div');
tip.className = 'llm-tooltip';
tip.style.position = 'absolute';
tip.style.left = '0px';
tip.style.top = '0px';
tip.style.pointerEvents = 'none';
tip.style.visibility = 'hidden';
tip.style.zIndex = '20';
tip.style.boxSizing = 'border-box';
tip.style.whiteSpace = opts.wrap ? 'normal' : 'nowrap';
tip.style.background = 'rgba(255,255,255,0.97)';
tip.style.border = '1px solid rgba(0,0,0,0.28)';
tip.style.borderRadius = '4px';
tip.style.padding = '6px 9px';
tip.style.boxShadow = '0 2px 6px rgba(0,0,0,0.22)';
tip.style.color = '#222';
tip.style.fontSize = '12px';
mount.appendChild(tip);
mount.__llmTip = tip;
}
function hostTip() {
try {
var n = mount, guard = 0;
while (n && guard++ < 8) {
if (n.__lchHostTip && typeof n.__lchHostTip.show === 'function') return n.__lchHostTip;
n = n.parentNode;
}
} catch (e) { /* detached node / cross-document parent */ }
return null;
}
function metrics() {
var w = 0, h = 0, cw = 0, ch = 0;
try {
var r = mount.getBoundingClientRect();
cw = r.width; ch = r.height;
} catch (e) { /* fall through to the client* fallbacks */ }
if (!cw) cw = mount.clientWidth || 0;
if (!ch) ch = mount.clientHeight || 0;
w = tip.offsetWidth || 0;
h = tip.offsetHeight || 0;
return { w: w, h: h, cw: cw, ch: ch };
}
function local(ev) {
var x = 0, y = 0;
try {
var r = mount.getBoundingClientRect();
if (ev && ev.clientX != null) { x = ev.clientX - r.left; y = ev.clientY - r.top; }
} catch (e) {
if (ev && ev.clientX != null) { x = ev.clientX; y = ev.clientY; }
}
return { x: x, y: y };
}
function place(ev) {
var m = metrics();
if (!m.cw || !m.ch) return; // no layout to clamp against (exec gate)
var p = local(ev);
var left = p.x + gap;
if (left + m.w > m.cw - edge) left = p.x - gap - m.w;
if (left < edge) left = edge;
if (left + m.w > m.cw - edge) left = Math.max(edge, m.cw - m.w - edge);
var top = p.y + gap;
if (top + m.h > m.ch - edge) top = p.y - gap - m.h;
if (top < edge) top = edge;
if (top + m.h > m.ch - edge) top = Math.max(edge, m.ch - m.h - edge);
tip.style.left = Math.round(left) + 'px';
tip.style.top = Math.round(top) + 'px';
}
function looksLikeEvent(x) {
return !!x && typeof x === 'object' && !Array.isArray(x)
&& (typeof x.clientX === 'number' || typeof x.type === 'string' || ('target' in x));
}
function setContent(content, asText) {
if (Array.isArray(content)) content = content.map(function (x) { return x == null ? '' : String(x); }).join(asText ? ' ' : '<br/>');
lastContent = content == null ? '' : String(content);
if (!asText && typeof content === 'string' && content.indexOf('<') >= 0) tip.innerHTML = lastContent;
else tip.textContent = lastContent;
}
function setAndRefit(self, content, asText) {
setContent(content, asText);
if (routed) {
var hbSet = hostTip();
if (hbSet && hbSet.show(lastContent, lastEv) === true) return self;
routed = false; // the host let go: the tooltip is still on screen, so draw ours
return self.show(null, lastEv);
}
if (tip.style.visibility === 'visible') return self.show(null, lastEv);
return self;
}
return {
node: tip,
html: function (content) { return arguments.length ? setAndRefit(this, content, false) : lastContent; },
text: function (content) { return arguments.length ? setAndRefit(this, content, true) : (tip.textContent || ''); },
show: function (content, ev) {
if (looksLikeEvent(content) && !looksLikeEvent(ev)) { var swapped = content; content = ev; ev = swapped; }
if (ev) lastEv = ev;
if (content != null) setContent(content, false);
tip.style.maxWidth = 'none';
tip.style.visibility = 'visible'; // measurable BEFORE placing
var m = metrics();
if (m.ch && m.h + (2 * edge) > m.ch) {
var hbShow = hostTip();
if (hbShow && hbShow.show(lastContent, ev) === true) {
routed = true;
tip.style.visibility = 'hidden';
return this;
}
}
routed = false;
if (m.cw) tip.style.maxWidth = Math.max(80, m.cw - (2 * edge)) + 'px';
place(ev);
return this;
},
move: function (ev) {
if (ev) lastEv = ev;
if (routed) { var hbMove = hostTip(); if (hbMove) hbMove.move(ev); return this; }
if (tip.style.visibility === 'visible') place(ev);
return this;
},
hide: function () {
if (routed) { var hbHide = hostTip(); if (hbHide) hbHide.hide(); routed = false; }
tip.style.visibility = 'hidden';
return this;
}
};
};
d3.llmDisplayName = function (name) {
var s = name === null || name === undefined ? '' : String(name);
if (!s || /\s/.test(s)) return s.trim();
var t = s.replace(/[_]+/g, ' ');
if (/^[a-z0-9]+(?:-+[a-z0-9]+)+$/.test(t)) t = t.replace(/-+/g, ' ');
t = t.trim();
if (t !== s) return t.charAt(0).toUpperCase() + t.slice(1);
var parts = [];
var re = /[a-z][A-Z][a-z]+|[A-Z][a-z][A-Z](?![a-z])|[A-Z]+[0-9]+|[A-Z]+(?=[A-Z][a-z])|[A-Z]?[a-z]+|[A-Z]+|[0-9]+[A-Z](?![a-z0-9])|[0-9]+|[^A-Za-z0-9]+/g;
var m;
while ((m = re.exec(s)) !== null) {
if (m[0] === '') { re.lastIndex++; continue; }
parts.push(m[0]);
}
if (parts.length < 2 || parts.join('') !== s) return s;
var out = '';
for (var i = 0; i < parts.length; i++) {
var punct = /^[^A-Za-z0-9]+$/.test(parts[i]), prevPunct = i > 0 && /^[^A-Za-z0-9]+$/.test(parts[i - 1]);
out += i === 0 || punct || prevPunct ? parts[i] : ' ' + parts[i];
}
return out.trim();
};
d3.llmThemeColors = function (options) {
options = options || {};
var pick = function (v, d) { return (typeof v === 'string' && v && v !== 'transparent') ? v : d; };
var bg = pick(options.backgroundColor, pick(options.themeBg, '#ffffff'));
var fg = pick(options.themeFg, '#252423');
var hc = !!options.isHighContrast;
var pal = (options.palette && options.palette.length) ? options.palette.slice() : ['#4C78A8', '#F58518', '#54A24B', '#E45756', '#72B7B2', '#B279A2', '#FF9DA6', '#9D755D'];
var rgb = function (c) { var x = null; try { x = d3.rgb(c); } catch (e) { x = null; } return x && isFinite(x.r) ? x : d3.rgb(128, 128, 128); };
var lum = function (c) {
var r = rgb(c);
var f = function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
return 0.2126 * f(r.r) + 0.7152 * f(r.g) + 0.0722 * f(r.b);
};
var contrast = function (a, b) { var x = lum(a) + 0.05, y = lum(b) + 0.05; return x > y ? x / y : y / x; };
var legible = function (col, floor) {
floor = floor || 3;
var c = d3.lab(rgb(col));
var step = lum(bg) > 0.5 ? -3 : 3; // a light background darkens the hue, a dark one lightens it
for (var i = 0; i < 34 && contrast(c.formatHex(), bg) < floor; i++) c.l = Math.max(0, Math.min(100, c.l + step));
return c.formatHex();
};
var good = hc ? pick(options.themeAccent, fg) : legible('#2e7d32');
var bad = hc ? fg : legible('#c62828');
var slot = function (value, n) {
var h = 2166136261, text = String(value);
for (var i = 0; i < text.length; i++) { h ^= text.charCodeAt(i); h = Math.imul(h, 16777619) >>> 0; }
return h % n;
};
var deltaE2000 = function (x, y) {
var rad = Math.PI / 180, L1 = x.l, a1 = x.a, b1 = x.b, L2 = y.l, a2 = y.a, b2 = y.b;
var C1 = Math.sqrt(a1 * a1 + b1 * b1), C2 = Math.sqrt(a2 * a2 + b2 * b2), Cm = (C1 + C2) / 2;
var G = 0.5 * (1 - Math.sqrt(Math.pow(Cm, 7) / (Math.pow(Cm, 7) + Math.pow(25, 7))));
var a1p = (1 + G) * a1, a2p = (1 + G) * a2;
var C1p = Math.sqrt(a1p * a1p + b1 * b1), C2p = Math.sqrt(a2p * a2p + b2 * b2);
var hp = function (bb, ap) { if (bb === 0 && ap === 0) return 0; var hh = Math.atan2(bb, ap) / rad; return hh < 0 ? hh + 360 : hh; };
var h1p = hp(b1, a1p), h2p = hp(b2, a2p);
var dLp = L2 - L1, dCp = C2p - C1p, dhp = 0;
if (C1p * C2p !== 0) { dhp = h2p - h1p; if (dhp > 180) dhp -= 360; else if (dhp < -180) dhp += 360; }
var dHp = 2 * Math.sqrt(C1p * C2p) * Math.sin(dhp * rad / 2);
var Lm = (L1 + L2) / 2, Cmp = (C1p + C2p) / 2, hm = h1p + h2p;
if (C1p * C2p !== 0) { if (Math.abs(h1p - h2p) > 180) hm += (hm < 360 ? 360 : -360); hm /= 2; }
var T = 1 - 0.17 * Math.cos((hm - 30) * rad) + 0.24 * Math.cos(2 * hm * rad) + 0.32 * Math.cos((3 * hm + 6) * rad) - 0.2 * Math.cos((4 * hm - 63) * rad);
var dTh = 30 * Math.exp(-Math.pow((hm - 275) / 25, 2));
var Rc = 2 * Math.sqrt(Math.pow(Cmp, 7) / (Math.pow(Cmp, 7) + Math.pow(25, 7)));
var Sl = 1 + 0.015 * Math.pow(Lm - 50, 2) / Math.sqrt(20 + Math.pow(Lm - 50, 2)), Sc = 1 + 0.045 * Cmp, Sh = 1 + 0.015 * Cmp * T;
var Rt = -Math.sin(2 * dTh * rad) * Rc;
var tl = dLp / Sl, tc = dCp / Sc, th = dHp / Sh;
return Math.sqrt(tl * tl + tc * tc + th * th + Rt * tc * th);
};
var order = null, pool = null, near = null;
var growOrder = function (count) {
if (!order) {
order = pal.map(function (c) { return rgb(c).formatHex(); });
var taken = order.map(function (c) { return d3.lab(c); });
var seenHex = {};
order.forEach(function (c) { seenHex[c] = 1; });
pool = [];
pal.forEach(function (c) {
var h = d3.hcl(rgb(c));
if (!isFinite(h.h)) h.h = 0;
var chroma = Math.max(isFinite(h.c) ? h.c : 0, 35);
[h.l, 38, 52, 66].forEach(function (L) {
for (var k = 1; k < 18; k++) {
var cc = d3.hcl((h.h + k * 20) % 360, chroma, L);
while (!cc.displayable() && cc.c > 20) cc.c -= 5;
if (!cc.displayable()) continue;
var hl = d3.hsl(cc).l;
if (!(hl > 0.15 && hl < 0.85)) continue;
var hx = cc.formatHex();
if (seenHex[hx]) continue;
seenHex[hx] = 1;
pool.push({ hex: hx, lab: d3.lab(hx) });
}
});
});
near = pool.map(function (q) {
var m = Infinity;
for (var t = 0; t < taken.length; t++) m = Math.min(m, deltaE2000(q.lab, taken[t]));
return m;
});
}
while (order.length < count && pool.length) {
var best = 0;
for (var q = 1; q < pool.length; q++) if (near[q] > near[best]) best = q;
var picked = pool.splice(best, 1)[0];
near.splice(best, 1);
order.push(picked.hex);
for (var r2 = 0; r2 < pool.length; r2++) near[r2] = Math.min(near[r2], deltaE2000(pool[r2].lab, picked.lab));
}
for (var round = 1; order.length < count && round < 40; round++) {
for (var e = 0; e < pal.length && order.length < count; e++) {
var hc = d3.hsl(pal[e]);
if (!isFinite(hc.h)) hc.h = 0;
var step = Math.ceil(round / 2) * 0.12 * (round % 2 ? 1 : -1);
hc.l = Math.max(0.12, Math.min(0.88, hc.l + step));
hc.h = (hc.h + round * 7) % 360;
var cx = hc.formatHex();
if (order.indexOf(cx) < 0) order.push(cx);
}
}
};
var extended = function (count) {
if (pal.length >= count) return pal.slice();
growOrder(count);
return pal.slice().concat(order.slice(pal.length, count));
};
var memory = function () {
var m = d3.__lchCategorySlots;
if (!m || !Array.isArray(m.groups)) { m = { groups: [] }; try { d3.__lchCategorySlots = m; } catch (e) { /* a frozen d3: no memory */ } }
return m;
};
var categories = function (values) {
var seen = {}, list = [];
(values || []).forEach(function (v) { var k = v === null || v === undefined ? '' : String(v); if (!seen[k]) { seen[k] = 1; list.push(k); } });
list.sort();
var mem = memory(), group = null, best = 0;
mem.groups.forEach(function (g) {
var shared = 0;
list.forEach(function (k) { if (Object.prototype.hasOwnProperty.call(g.slots, k)) shared++; });
if (shared > best) { best = shared; group = g; }
});
if (!group) {
group = { slots: {}, used: {}, size: 0 };
mem.groups.push(group);
if (mem.groups.length > 32) mem.groups.shift();
}
var fresh = list.filter(function (k) { return !Object.prototype.hasOwnProperty.call(group.slots, k); });
var total = group.size + fresh.length;
var cols = extended(Math.max(list.length, total));
var n = cols.length;
fresh.forEach(function (k) {
if (group.size >= 2000) return; // a category this long is not a palette's job: past it, a value is placed but not remembered
var i = 0;
while (group.used[i] && i < n) i++;
group.used[i] = 1;
group.slots[k] = i;
group.size++;
});
var map = {};
list.forEach(function (k) {
var i = Object.prototype.hasOwnProperty.call(group.slots, k) ? group.slots[k] : slot(k, n);
if (i >= cols.length) cols = extended(i + 1);
map[k] = cols[i % cols.length];
});
return function (v) {
var k = v === null || v === undefined ? '' : String(v);
return map[k] || cols[slot(k, n)];
};
};
return { bg: bg, fg: fg, good: good, bad: bad, categories: categories, legible: function (c) { return legible(c); }, contrast: contrast, palette: pal };
};
function render(container, data, options) {
const TYPE_FLOOR = 10;
var W = options.width, H = options.height;
var FS = Math.max(TYPE_FLOOR, Math.min(14, Math.min(W, H) / 55));
var LABEL_FS = Math.max(TYPE_FLOOR, FS * 0.9), VALUE_FS = Math.max(TYPE_FLOOR, FS * 0.85), CAP_FS = Math.max(TYPE_FLOOR, FS * 0.8);
var fg = options.themeFg || 'currentColor';
var bg = options.themeBg || '#ffffff';
var loc = options.cultureCode || 'en-US';
var nf = new Intl.NumberFormat(loc, { maximumFractionDigits: 1, notation: 'compact' });
var pct = new Intl.NumberFormat(loc, { style: 'percent', maximumFractionDigits: 0 });
function stop(reason) {
container.replaceChildren();
var t = d3.select(container).append('svg').attr('width', W).attr('height', H)
.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle')
.attr('font-size', FS).attr('fill', fg);
d3.llmFitLabel(t, W - 12, { pad: 0,
text: reason || (typeof options.noDataText === 'string' && options.noDataText) || 'No data to display' });
}
var cols = data.columns || [], rows = data.rows || [];
var idxOf = function (n) { return cols.findIndex(function (c) { return c.name === n; }); };
var ciTeam = idxOf('Team'), ciFrom = idxOf('FromStep'), ciVal = idxOf('Sum of Orders');
if (ciTeam < 0) throw new Error('INVALID:column "Team" not found');
if (ciFrom < 0) throw new Error('INVALID:column "FromStep" not found');
if (ciVal < 0) throw new Error('INVALID:column "Sum of Orders" not found');
var ciRow = idxOf('__rowIdx__');
var levels = [ciTeam, ciFrom];
var labelOf = function (v) { return (v === null || v === undefined || v === '') ? '(blank)' : String(v); };
var rowId = function (r, i) { return ciRow >= 0 ? r[ciRow] : i; };
var tree = { name: 'All', children: [], ids: [], ord: 0 };
var negative = false, ordN = 0;
rows.forEach(function (r, i) {
var node = tree;
node.ids.push(rowId(r, i));
for (var li = 0; li < levels.length; li++) {
var name = labelOf(r[levels[li]]);
node.byName = node.byName || new Map();
var next = node.byName.get(name);
if (!next) { next = { name: name, children: [], ids: [], v: 0, ord: ordN++ }; node.byName.set(name, next); node.children.push(next); }
next.ids.push(rowId(r, i));
node = next;
}
var raw = r[ciVal];
if (raw !== null && raw !== undefined && raw !== '' && isFinite(+raw)) { if (+raw < 0) negative = true; node.v += +raw; }
});
if (negative) { stop('Sunburst chart cannot size a segment by a negative value. Filter out the negative rows.'); return; }
var root = d3.hierarchy(tree, function (d) { return d.children && d.children.length ? d.children : null; })
.sum(function (d) { return d.children && d.children.length ? 0 : (d.v || 0); })
.sort(function (a, b) { return a.depth === 1 ? b.value - a.value : a.data.ord - b.data.ord; });
if (!rows.length || !(root.value > 0)) { stop(); return; }
container.replaceChildren();
var svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
var DEPTH = Math.min(3, root.height);
var crumbH = Math.max(FS * 1.7, 20);
var stripY = crumbH;
var stripH = crumbH + FS * 0.9 + 6, capH = FS * 3.8;
var plotH = Math.max(FS * 8, H - stripH - capH);
var plotW = Math.max(FS * 8, W - FS * 2);
var R = Math.min(plotW, plotH) / 2;
var ringR = R / (DEPTH + 1);
var cx = W / 2, cy = stripH + plotH / 2;
d3.partition().size([2 * Math.PI, root.height + 1])(root);
root.each(function (d) {
d.current = { x0: d.x0, x1: d.x1, y0: d.y0, y1: d.y1 };
d.rowIdx = d.data.ids.join(',');
});
function arcVisible(d) { return d.y1 <= DEPTH + 1 && d.y0 >= 1 && d.x1 > d.x0; }
function rimY(y) { return Math.min(y, DEPTH + 1); }
function labelVisible(d) { return arcVisible(d) && (d.x1 - d.x0) * ((d.y0 + d.y1) / 2) * ringR > FS * 1.15; }
var LABEL_H = LABEL_FS * 1.25;
function radialRoom(s) { return (s.y1 - s.y0) * ringR - FS * 0.6; }
function arcRoom(s) {
var r0 = s.y0 * ringR, r1 = s.y1 * ringR, rm = (r0 + r1) / 2, half = (s.x1 - s.x0) / 2;
if (r1 - r0 < LABEL_H || !(half > 0)) return 0;
var ring = r1 * r1 - Math.pow(rm + LABEL_H / 2, 2);
var chord = ring > 0 ? 2 * Math.sqrt(ring) : 0;
var span = half >= Math.PI / 2 - 0.02 ? Infinity : 2 * (rm - LABEL_H / 2) * Math.tan(half - 0.02);
return Math.min(chord, span) - FS * 0.6;
}
function labelTransform(s, orient) {
var a = (s.x0 + s.x1) / 2 * 180 / Math.PI, rr = (rimY(s.y0) + rimY(s.y1)) / 2 * ringR;
if (orient === 'arc') return 'rotate(' + a + ') translate(0,' + (-rr) + ')' + (a > 90 && a < 270 ? ' rotate(180)' : '');
return 'rotate(' + (a - 90) + ') translate(' + rr + ',0) rotate(' + (a < 180 ? 0 : 180) + ')';
}
var topOf = function (d) { var t = d; while (t.depth > 1) t = t.parent; return t; };
var branchColour = d3.llmThemeColors(options).categories(tree.children.map(function (c) { return c.name; }));
var maxShare = new Map();
root.leaves().forEach(function (l) {
var s = l.parent && l.parent.value ? l.value / l.parent.value : 1;
maxShare.set(l.parent, Math.max(maxShare.get(l.parent) || 0, s));
});
// Leaves: team hue, tinted by share of team orders (normalized to the team's largest share)
function fillOf(d) {
var base = branchColour(topOf(d).data.name);
if (d.depth <= 1 || d.children) return d3.color(base) ? d3.color(base).formatHex() : base;
var s = d.parent && d.parent.value ? d.value / d.parent.value : 1;
var t = s / (maxShare.get(d.parent) || 1);
return d3.interpolateLab(d3.interpolateLab(base, bg)(0.55), base)(Math.max(0, Math.min(1, t)));
}
var restOpacity = function (d) { return d.children ? 0.6 : 0.85; };
function textOn(d) {
var f = d3.rgb(fillOf(d)), b = d3.rgb(bg), a = restOpacity(d);
var mix = function (x, y) { return (a * x + (1 - a) * y) / 255; };
var lum = function (v) { return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
var L = 0.2126 * lum(mix(f.r, b.r)) + 0.7152 * lum(mix(f.g, b.g)) + 0.0722 * lum(mix(f.b, b.b));
return L > 0.36 ? '#1b1b1b' : '#ffffff';
}
var arc = d3.arc()
.startAngle(function (d) { return d.x0; }).endAngle(function (d) { return d.x1; })
.padAngle(function (d) { return Math.min((d.x1 - d.x0) / 2, 0.005); }).padRadius(R)
.innerRadius(function (d) { return rimY(d.y0) * ringR; })
.outerRadius(function (d) { return Math.max(rimY(d.y0) * ringR, rimY(d.y1) * ringR - 1); });
var g = svg.append('g').attr('transform', 'translate(' + cx + ',' + cy + ')');
var tip = options.allowTooltips === false ? null : d3.llmTooltip(container);
var tipHtml = function (d) {
var pathTxt = d.ancestors().reverse().slice(1).map(function (a) { return a.data.name; }).join(' > ');
var share = d.parent && d.parent.value ? ' (' + pct.format(d.value / d.parent.value) + ' of ' + d.parent.data.name + ')' : '';
return '<b>' + pathTxt + '</b><br>' + nf.format(d.value) + share + '<br>' + d.data.ids.length + ' rows';
};
var nodes = root.descendants().slice(1);
var path = g.append('g').selectAll('path').data(nodes).join('path')
.attr('class', 'd3-axis-filter')
.attr('data-row-idx', function (d) { return d.rowIdx; })
.attr('fill', fillOf)
.attr('fill-opacity', function (d) { return arcVisible(d.current) ? restOpacity(d) : 0; })
.style('visibility', function (d) { return arcVisible(d.current) ? 'visible' : 'hidden'; })
.style('cursor', 'pointer')
.attr('d', function (d) { return arc(d.current); })
.on('click', function (e, d) { bc.focus(d); })
.on('mouseover', function (e, d) { d3.select(this).attr('fill-opacity', 1); if (tip) tip.show(tipHtml(d), e); })
.on('mousemove', function (e) { if (tip) tip.move(e); })
.on('mouseout', function (e, d) {
d3.select(this).attr('fill-opacity', arcVisible(d.current) ? restOpacity(d) : 0);
if (tip) tip.hide();
});
var label = g.append('g').attr('pointer-events', 'none').attr('text-anchor', 'middle')
.selectAll('text').data(nodes).join('text')
.attr('dy', '0.35em').attr('font-size', LABEL_FS).attr('fill', textOn)
.text(function (d) { return d.data.name; });
label.each(function (d) {
var w = 0;
try { w = this.getComputedTextLength(); } catch (e) { w = 0; }
d.nameW = w > 0 ? w : String(d.data.name).length * LABEL_FS * 0.6;
});
function layoutLabels(key) {
label.each(function (d) {
var s = d[key], rr = radialRoom(s);
d.orient = (d.nameW + 8 <= rr || arcRoom(s) <= rr) ? 'radial' : 'arc';
});
d3.llmFitLabel(label.filter(function (d) { return labelVisible(d[key]); }),
function (d) { var s = d[key]; return d.orient === 'arc' ? arcRoom(s) : radialRoom(s); },
{ text: function (d) { return d.data.name; } });
}
layoutLabels('current');
label.attr('fill-opacity', function (d) { return +labelVisible(d.current); })
.attr('transform', function (d) { return labelTransform(d.current, d.orient); });
g.append('circle').attr('class', 'lch-control').attr('aria-label', d3.llmText('d3.sunburst.up_one_level', 'Up one level'))
.attr('r', ringR).attr('fill', 'none').attr('pointer-events', 'all')
.style('cursor', 'pointer').on('click', function () { bc.up(); });
var cName = g.append('text').attr('text-anchor', 'middle').attr('dy', '-0.25em')
.attr('font-size', FS * 1.05).attr('font-weight', 'bold').attr('fill', fg).attr('pointer-events', 'none');
var cVal = g.append('text').attr('text-anchor', 'middle').attr('dy', '1.1em')
.attr('font-size', VALUE_FS).attr('fill', fg).attr('fill-opacity', 0.8).attr('pointer-events', 'none');
function centreText(p) {
d3.llmFitLabel(cName, ringR * 1.7, { pad: 0, text: p.data.name });
var forms = [nf.format(p.value) + ' across ' + p.data.ids.length + ' rows', nf.format(p.value)];
for (var i = 0; i < forms.length; i++) {
d3.llmFitLabel(cVal, ringR * 1.7, { pad: 0, text: forms[i], overflow: 'drop' });
if (cVal.text()) break;
}
}
var zoomToken = 0;
function zoomTo(p, animate) {
root.each(function (d) {
d.target = {
x0: Math.max(0, Math.min(1, (d.x0 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
x1: Math.max(0, Math.min(1, (d.x1 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
y0: Math.max(0, d.y0 - p.depth),
y1: Math.max(0, d.y1 - p.depth)
};
});
centreText(p);
if (!animate) {
root.each(function (d) { d.current = d.target; });
path.attr('d', function (d) { return arc(d.current); })
.attr('fill-opacity', function (d) { return arcVisible(d.current) ? restOpacity(d) : 0; })
.style('visibility', function (d) { return arcVisible(d.current) ? 'visible' : 'hidden'; });
layoutLabels('current');
label.attr('transform', function (d) { return labelTransform(d.current, d.orient); })
.attr('fill-opacity', function (d) { return +labelVisible(d.current); });
return;
}
layoutLabels('target');
var token = ++zoomToken;
path.style('visibility', function (d) {
return (+this.getAttribute('fill-opacity') > 0 || arcVisible(d.target)) ? 'visible' : 'hidden';
});
var t = svg.transition().duration(750);
path.transition(t)
.tween('data', function (d) { var i = d3.interpolate(d.current, d.target); return function (k) { d.current = i(k); }; })
.filter(function (d) { return +this.getAttribute('fill-opacity') || arcVisible(d.target); })
.attr('fill-opacity', function (d) { return arcVisible(d.target) ? restOpacity(d) : 0; })
.attrTween('d', function (d) { return function () { return arc(d.current); }; })
.on('end', function (d) { if (token === zoomToken && !arcVisible(d.target)) this.style.visibility = 'hidden'; });
label.filter(function (d) { return +this.getAttribute('fill-opacity') || labelVisible(d.target); })
.transition(t)
.attr('fill-opacity', function (d) { return +labelVisible(d.target); })
.attrTween('transform', function (d) { return function () { return labelTransform(d.current, d.orient); }; });
}
var arcByNode = new Map();
path.each(function (d) { arcByNode.set(d, this); });
var bc = d3.llmBreadcrumb(svg, {
container: container, options: options, root: root, fontSize: FS,
x: FS, y: stripY, width: W - FS * 2,
arcOf: function (node) { return arcByNode.get(node) || null; },
onFocus: function (node, meta) { zoomTo(node, !meta.restored); }
});
var unitName = d3.llmDisplayName(cols[ciVal].name);
var capText = 'Click a segment to zoom in and filter to it; click the center to zoom out - ' + unitName
+ '; segment tint = share of team';
var cap = svg.append('text').attr('x', W / 2).attr('y', stripH + plotH + CAP_FS * 1.4)
.attr('text-anchor', 'middle').attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.75);
d3.llmFitLabel(cap, W - FS * 2, { pad: 0, text: capText });
if (cap.text() !== capText) cap.append('title').text(capText);
var capText2 = 'Summed across all ' + d3.llmDisplayName('ToStep');
var cap2 = svg.append('text').attr('x', W / 2).attr('y', stripH + plotH + CAP_FS * 1.4 + CAP_FS * 1.4)
.attr('text-anchor', 'middle').attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.75);
d3.llmFitLabel(cap2, W - FS * 2, { pad: 0, text: capText2 });
}
Keep going
This chart was made by RegiaBI from the data above. Get it for Power BI or see pricing.
New articles in your inbox
Drop your email and we'll tell you when we publish something new. No spam — unsubscribe anytime.