Sum of Steps: a projection you set

Where would Sum of Steps end up if it kept growing at a rate you choose?

Daily wearable-device activity for a cohort of users: step counts, calories burned, average heart rate and sleep hours, with weekday and per-user grain. A rich mix of a date, a category (user), and several measures — good for time-series, per-category comparison, and tabular scorecards.

Fitness Tracker — Daily Steps, Sleep & Heart Rate: 5430 rows, 7 columns. Download the CSV

The first 10 rows
DateUserIDWeekdaySum of StepsSum of CaloriesBurnedAvgHeartRateSleepHours
2025-01-01U001Wed10071428687.7
2025-01-02U001Thu4474197808.1
2025-01-03U001Fri11527556806.9
2025-01-04U001Sat15062693856.4
2025-01-05U001Sun10226536966.9
2025-01-06U001Mon10164516806.5
2025-01-07U001Tue9765552828.6
2025-01-08U001Wed7720406966.1
2025-01-09U001Thu5680245889.4
2025-01-10U001Fri6647356786.6
A what-if projection of the "Fitness Tracker — Daily Steps, Sleep & Heart Rate" dataset: Sum of Steps by Date, Jan 1, 2025 to Jun 30, 2025, with a projection you control.
A what-if projection of the "Fitness Tracker — Daily Steps, Sleep & Heart Rate" dataset: Sum of Steps by Date, Jan 1, 2025 to Jun 30, 2025, with a projection you control.

How to read it

The line is the data as it happened, through Jun 30, 2025. Drag the growth rate and the horizon, and the dashed projection and the end value move with them; the starting rate is the one the data shows, so reset brings you back to it.

The chart's code (71 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.llmSlider = function (svg, cfg) {
var TYPE_FLOOR = 10;   // the minimum readable type, px
cfg = cfg || {};
var options = cfg.options || {}, container = cfg.container;
var key = cfg.key || 'value';
var onChange = typeof cfg.onChange === 'function' ? cfg.onChange : function () {};
var snaps = cfg.snapValues, dom = cfg.domain;
var isSnap = Array.isArray(snaps) && snaps.length > 1;
var noop = { value: function () { return null; }, set: function () {}, reset: function () {}, g: null,
bounds: function () { return { left: 0, right: 0 }; } };
var numericOk = dom && dom.length === 2 && isFinite(+dom[0]) && isFinite(+dom[1]) && +dom[1] > +dom[0];
var handleOnly = cfg.handleOnly === true && !isSnap && typeof cfg.position === 'function';
if (!svg || (!isSnap && !numericOk) || (cfg.handleOnly === true && !handleOnly)) {
return cfg.handleOnly === true ? { value: noop.value, set: noop.set, reset: noop.reset, g: null, bounds: noop.bounds,
domain: function () { return this; }, refresh: function () { return this; } } : noop;
}
var isDate = isSnap && snaps[0] instanceof Date;
var fg = options.themeFg || '#252423', accent = options.themeAccent || fg;
var x = cfg.x != null ? cfg.x : 0, y = cfg.y != null ? cfg.y : 0, w = cfg.width != null ? cfg.width : 120;
var step = isSnap ? 1 : (+cfg.step > 0 ? +cfg.step : (dom[1] - dom[0]) / 100);
var continuous = handleOnly && !(+cfg.step > 0);   // a handle-only dot with no step keeps the value it is given
var fmt = typeof cfg.format === 'function' ? cfg.format
: function (v) { return isDate ? new Date(+v).toISOString().slice(0, 10) : String(v); };
var fsz = Math.max(TYPE_FLOOR, +cfg.fontSize > 0 ? +cfg.fontSize
: Math.min(14, Math.min(options.width || 600, options.height || 400) / 55));
var fszSub = Math.max(TYPE_FLOOR, fsz * 0.9);   // label and readout: one size for the drawing and the measure
var tw = d3.llmSlider.textWidth;
var withSteppers = cfg.steppers !== false;
var gap = fsz * 0.6, box = Math.max(20, Math.round(fsz * 1.5));
var minusLeft = x - gap - box;                                   // [-] box spans [minusLeft, x - gap]
var labelRight = withSteppers ? minusLeft - fsz * 0.5 : x - fsz * 0.8;
var plusLeft = x + w + gap;                                      // [+] box spans [plusLeft, plusLeft + box]
var readoutLeft = withSteppers ? plusLeft + box + fsz * 0.5 : x + w + fsz * 0.8;

var bag = {};
if (container) {
if (!container.__lchKnobs || typeof container.__lchKnobs !== 'object') container.__lchKnobs = {};
bag = container.__lchKnobs;
}
var ui = options.uiState && typeof options.uiState === 'object' ? options.uiState : {};
var restored = ui.knobs && typeof ui.knobs === 'object' ? ui.knobs[key] : undefined;

function coerce(v) {                     // UNTRUSTED input -> a valid internal value, or null
if (v === null || v === undefined || v === '' || typeof v === 'boolean') return null;
if (isSnap) {
var n = isDate ? +new Date(v) : +v;
if (!isFinite(n)) return null;
var best = -1, bd = Infinity;
for (var i = 0; i < snaps.length; i++) {
var d = Math.abs(+snaps[i] - n);
if (d < bd) { bd = d; best = i; }
}
return best;                         // snap knobs hold an INDEX internally
}
var f = +v;
if (!isFinite(f) || f < dom[0] || f > dom[1]) return null;
return continuous ? f : Math.round((f - dom[0]) / step) * step + dom[0];
}

var cur = coerce(restored);
if (cur === null) cur = coerce(cfg.value);
if (cur === null) cur = coerce(cfg['default']);
if (cur === null) cur = isSnap ? 0 : dom[0];

var scale = isSnap ? d3.scaleLinear().domain([0, snaps.length - 1]).range([x, x + w])
: d3.scaleLinear().domain(dom).range([x, x + w]);

function stop(ev) { if (ev && typeof ev.stopPropagation === 'function') ev.stopPropagation(); }
function place(v) {                      // handle-only: where the caller's position() puts the value
var p = cfg.position(v);
return p && isFinite(+p[0]) && isFinite(+p[1]) ? [+p[0], +p[1]] : [0, 0];
}
function invertPlace(px) {               // handle-only: the value whose handle sits at pixel px
if (typeof cfg.invert === 'function') { var iv = +cfg.invert(px); if (isFinite(iv)) return iv; }
var lo = dom[0], hi = dom[1], pLo = place(lo)[0], pHi = place(hi)[0];
if (pLo === pHi) return cur;
var rising = pHi > pLo;
if (rising ? px <= pLo : px >= pLo) return lo;
if (rising ? px >= pHi : px <= pHi) return hi;
for (var i = 0; i < 60; i++) {
var mid = (lo + hi) / 2;
if ((place(mid)[0] < px) === rising) lo = mid; else hi = mid;
}
return (lo + hi) / 2;
}
var g = svg.append('g').attr('class', 'llm-slider lch-control').attr('data-knob', key).on('click', stop);
var labelText = '', labelW = 0;
if (cfg.label && !handleOnly) {
labelText = String(cfg.label);
var labelNode = g.append('text').attr('class', 'llm-slider-label')
.attr('x', labelRight).attr('y', y + fsz * 0.35).attr('text-anchor', 'end')
.attr('font-size', fszSub).attr('fill', fg).text(labelText);
labelW = measure(labelNode, labelText, fszSub);
if (+cfg.labelRoom > 0 && labelW > +cfg.labelRoom) {
var keep = labelText;
while (keep.length > 1 && measure(labelNode.text(keep + '\u2026'), keep + '\u2026', fszSub) > +cfg.labelRoom) keep = keep.slice(0, -1);
labelText = keep.length > 1 ? keep + '\u2026' : '';
labelNode.text(labelText);
labelW = labelText ? measure(labelNode, labelText, fszSub) : 0;
}
}
if (!handleOnly) g.append('line').attr('class', 'llm-slider-track')
.attr('x1', x).attr('x2', x + w).attr('y1', y).attr('y2', y)
.attr('stroke', fg).attr('stroke-width', 2).attr('opacity', 0.35);
var handle = g.append('g').attr('class', 'llm-slider-handle').attr('cursor', 'ew-resize');
handle.append('circle').attr('r', fsz * 0.55).attr('cy', handleOnly ? 0 : y).attr('fill', accent)
.attr('stroke', fg).attr('stroke-width', 1);
handle.append('rect').attr('x', -12).attr('y', (handleOnly ? 0 : y) - 12).attr('width', 24).attr('height', 24)
.attr('fill', 'transparent').attr('pointer-events', 'all');
handle.attr('role', 'slider').attr('tabindex', 0).attr('aria-label', String(cfg.label || key)).attr('aria-orientation', 'horizontal');
handle.on('keydown', function (event) {
var k = event && event.key, big = isSnap ? Math.max(1, Math.round(snaps.length / 10)) : 10;
var by = k === 'ArrowRight' || k === 'ArrowUp' ? 1 : k === 'ArrowLeft' || k === 'ArrowDown' ? -1
: k === 'PageUp' ? big : k === 'PageDown' ? -big : 0;
if (by) nudge(by);
else if (k === 'Home') setCur(isSnap ? 0 : dom[0], 'end');
else if (k === 'End') setCur(isSnap ? snaps.length - 1 : dom[1], 'end');
else return;
if (event && typeof event.preventDefault === 'function') event.preventDefault();
stop(event);
});
var readout = handleOnly ? null : g.append('text').attr('class', 'llm-slider-readout')
.attr('x', readoutLeft).attr('y', y + fsz * 0.35)
.attr('font-size', fszSub).attr('fill', fg);
var readoutText = '';

function measure(sel, txt, fs) {
try {
var node = typeof sel.node === 'function' ? sel.node() : null;
if (node && typeof node.getComputedTextLength === 'function') {
var mw = node.getComputedTextLength();
if (mw > 0) return mw;
}
} catch (e) { /* fall through to the estimate */ }
return tw(txt, fs);
}

function valueOf() { return isSnap ? snaps[cur] : cur; }
function stored() { return isSnap ? (isDate ? new Date(+snaps[cur]).toISOString() : snaps[cur]) : cur; }
function paint() {
handle.attr('aria-valuemin', isSnap ? 0 : dom[0]).attr('aria-valuemax', isSnap ? snaps.length - 1 : dom[1])
.attr('aria-valuenow', cur).attr('aria-valuetext', String(fmt(valueOf())));
if (handleOnly) { var at = place(cur); handle.attr('transform', 'translate(' + at[0] + ',' + at[1] + ')'); return; }
handle.attr('transform', 'translate(' + scale(cur) + ',0)');
readoutText = String(fmt(valueOf()));
readout.text(readoutText);
}
function reportControl() {
if (typeof options.onControlChange !== 'function') return;
try { options.onControlChange({ control: 'slider', key: key, value: String(stored()) }); }
catch (e) { /* a host that refuses the report must never take the chart down with it */ }
}
function persist(phase) {
bag[key] = stored();
onChange(valueOf(), phase);
if (phase === 'end' || phase === 'reset') reportControl();
if (typeof options.setUiState !== 'function') return;
var live = container && container.__lchUiLiveOpts === options && container.__lchUiLiveSeed === options.uiState
? container.__lchUiLive : null;
var base = live || ui;
var next = {}, k;
for (k in base) if (Object.prototype.hasOwnProperty.call(base, k)) next[k] = base[k];
next.knobs = {};
for (k in bag) if (Object.prototype.hasOwnProperty.call(bag, k)) next.knobs[k] = bag[k];
if (container) { container.__lchUiLive = next; container.__lchUiLiveOpts = options; container.__lchUiLiveSeed = options.uiState; }
try { options.setUiState(next); } catch (e) { /* persistence is advisory, never fatal */ }
}
function setCur(c, phase) {
var v = isSnap ? Math.max(0, Math.min(snaps.length - 1, Math.round(c)))
: Math.max(dom[0], Math.min(dom[1], c));
if (v === cur && phase !== 'init') return;
cur = v;
paint();
if (phase === 'drag') onChange(valueOf(), 'drag'); else persist(phase);
}
function nudge(dir) { setCur(isSnap ? cur + dir : cur + dir * step, 'end'); }
function mkStepper(parent, dir, left) {
var s = parent.append('g').attr('class', 'llm-slider-step lch-control').attr('cursor', 'pointer')
.attr('aria-label', dir < 0 ? d3.llmText('d3.slider.decrease', 'Decrease {label}', { label: String(cfg.label || key) }) : d3.llmText('d3.slider.increase', 'Increase {label}', { label: String(cfg.label || key) }))
.on('click', function () { nudge(dir); });
s.append('rect').attr('x', left).attr('y', y - box / 2).attr('width', box).attr('height', box)
.attr('rx', 3).attr('fill', 'transparent').attr('stroke', fg).attr('opacity', 0.6);
s.append('text').attr('x', left + box / 2).attr('y', y + fsz * 0.35).attr('text-anchor', 'middle')
.attr('font-size', fsz).attr('fill', fg).text(dir < 0 ? '-' : '+');
return s;
}
if (withSteppers && !handleOnly) {
var stepG = g.append('g').attr('class', 'llm-slider-steppers');
mkStepper(stepG, -1, minusLeft);
mkStepper(stepG, +1, plusLeft);
}

handle.call(d3.drag()
.on('drag', function (event) {
var v = handleOnly ? invertPlace(event.x) : scale.invert(event.x);
setCur(isSnap || continuous ? v : Math.round((v - dom[0]) / step) * step + dom[0], 'drag');
})
.on('end', function () { persist('end'); }));

paint();
if (!handleOnly) bag[key] = stored();   // a handle-only dot writes the bag only when the reader lets go
onChange(valueOf(), 'init');
var api = {
value: valueOf,
g: g,
set: function (v, fire) { var c = coerce(v); if (c === null) return; setCur(c, fire === false ? 'drag' : 'end'); },
reset: function (fire) { var c = coerce(cfg['default']); if (c === null) return; setCur(c, fire === false ? 'drag' : 'reset'); },
bounds: function () {
if (handleOnly) { var hp = place(cur); return { left: hp[0], right: hp[0] }; }
var left = labelText ? labelRight - labelW : (withSteppers ? minusLeft : x);
var right = readoutLeft + measure(readout, readoutText, fszSub);
return { left: left, right: right };
}
};
if (handleOnly) {
api.domain = function (d) {
if (d && d.length === 2 && isFinite(+d[0]) && isFinite(+d[1]) && +d[1] >= +d[0]) {
dom = [+d[0], +d[1]];
cur = Math.max(dom[0], Math.min(dom[1], cur));
paint();
}
return api;
};
api.refresh = function () { paint(); return api; };
}
return api;
};
d3.llmSlider.textWidth = function (txt, fontSize) {
var s = String(txt == null ? '' : txt), f = +fontSize > 0 ? +fontSize : 10;
var wide = s.match(/[\u1100-\u11ff\u2e80-\u9fff\uac00-\ud7af\uf900-\ufaff\uff00-\uffef]/g), n = wide ? wide.length : 0;
return ((s.length - n) * 0.6 + n) * f;
};

// @requires llmText
d3.llmKeyframes = function (rows, opts) {
opts = opts || {};
var timeAcc = opts.time || function (r) { return r.TIME; };
var ideal = Math.max(3, Math.min(300, Math.round(+opts.maxIdeal || 60)));
var p2 = function (n) { return n < 10 ? '0' + n : '' + n; };
var yrLike = function (v) { var n = +v; return isFinite(n) && n >= 1000 && n <= 9999 && Math.abs(n - Math.round(n)) < 1e-9; };
var toDate = function (v) {
if (v == null || v === '') return null;
if (v instanceof Date) return isNaN(+v) ? null : v;
if (yrLike(v)) return new Date(Date.UTC(+v, 0, 1));
var d = new Date(v); return isNaN(+d) ? null : d;
};
var rowDate = rows.map(function (r) { return toDate(timeAcc(r)); });
var GR = [
['day', function (d) { return d.getUTCFullYear() + '-' + p2(d.getUTCMonth() + 1) + '-' + p2(d.getUTCDate()); }],
['week', function (d) { var t = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()), th = new Date(t + (3 - (d.getUTCDay() + 6) % 7) * 864e5), y = th.getUTCFullYear(); return y + '-W' + p2(Math.floor((+th - Date.UTC(y, 0, 1)) / 6048e5) + 1); }],   // ISO-8601 week: the year of its Thursday, so the week across New Year is ONE bucket
['month', function (d) { return d.getUTCFullYear() + '-' + p2(d.getUTCMonth() + 1); }],
['quarter', function (d) { return d.getUTCFullYear() + '-Q' + (Math.floor(d.getUTCMonth() / 3) + 1); }],
['year', function (d) { return '' + d.getUTCFullYear(); }],
['decade', function (d) { return (Math.floor(d.getUTCFullYear() / 10) * 10) + 's'; }]
];
var bkeyOf;
if (rowDate.filter(Boolean).length >= rows.length * 0.6) {
var cn = GR.map(function (g) { return new Set(rowDate.filter(Boolean).map(g[1])).size; });
var gi = GR.length - 1;
for (var i = 0; i < GR.length; i++) { if (cn[i] > ideal) continue; if (i + 1 < GR.length && cn[i + 1] === cn[i]) continue; gi = i; break; }
var fn = GR[gi][1];
bkeyOf = function (r) { var d = toDate(timeAcc(r)); return d ? fn(d) : null; };
} else {
bkeyOf = function (r) { return timeAcc(r); };
}
var keys = Array.from(new Set(rows.map(bkeyOf).filter(function (v) { return v != null; })))
.sort(function (a, b) { return (yrLike(a) && yrLike(b)) ? (+a - +b) : d3.ascending(String(a), String(b)); });
var kIdx = new Map(keys.map(function (k, i) { return [k, i]; }));
var m = (opts.aggregation || '').toLowerCase();
var AGGLBL = { average: 'Average', median: 'Median', min: 'Min', max: 'Max',
count: 'Count', distinct: 'Distinct', sum: 'Total' };
var mKey = AGGLBL[m] ? m : 'sum';
var mLabel = d3.llmText('d3.keyframes.agg.' + mKey, AGGLBL[mKey]);
var aggregate = function (a) {
return !a.length ? null
: m === 'average' ? d3.mean(a)
: m === 'median' ? d3.median(a)
: m === 'min' ? d3.min(a)
: m === 'max' ? d3.max(a)
: m === 'count' ? a.length
: m === 'distinct' ? new Set(a).size
: d3.sum(a);
};
var RATE_WORDS = 'rate ratio pct percent percentage rating share score index nps csat margin yield coverage utilization utilisation average avg mean median gpa percentile quantile efficiency accuracy probability occupancy bmi density pressure humidity velocity latency throughput bandwidth iops ppm ppb dpmo bps capita'.split(' ');
var RATE_SUFFIXES = 'pct percent percentage rate ratio rating share score index nps csat margin yield coverage utilization utilisation gpa percentile quantile bmi density pressure humidity velocity efficiency occupancy latency throughput bandwidth iops ppm ppb dpmo bps'.split(' ');
var nameWords = function (name) {
var s = String(name || '');
try { s = s.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); } catch (eN) { /* an engine without normalize reads the name as written */ }
return s.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2').toLowerCase().split(/[^a-z]+/).filter(function (w) { return !!w; });
};
var isRate = function (col) {
if (col == null) return false;
var c = typeof col === 'string' ? { name: col } : col;
var add = String(c.additivity || '').toLowerCase();
if (add === 'intensive_rate') return true;
if (add === 'part_of_whole' || add === 'additive') return false;   // measured additive: never a rate, whatever its name
if (true === c.discourageAggregationAcrossGroups) return true;
var fmt = typeof c.modelFormat === 'string' ? c.modelFormat.replace(/"[^"]*"/g, '').replace(/\\./g, '') : '';
if (fmt.indexOf('%') !== -1) return true;
var words = nameWords(c.name), joined = words.join('');
if (words.some(function (w) { return RATE_WORDS.indexOf(w) !== -1; })) return true;
return RATE_SUFFIXES.some(function (sfx) { return joined.length > sfx.length && joined.slice(-sfx.length) === sfx; });
};
var LEVEL_PHRASES = ['eom', 'eop', 'eoq', 'eoy', 'end of month', 'end of period', 'end of quarter', 'end of year', 'end of the month',
'end of the period', 'month end', 'period end', 'quarter end', 'year end', 'at month end', 'month ending', 'period ending'];
var LEVEL_STOCK_NOUNS = ['balance', 'balances', 'inventory', 'stock', 'headcount', 'cash', 'backlog', 'position', 'positions'];
var LEVEL_MOVES = ('new hire hires hired joined joiners exit exits left leavers terminations terminated separations churned churn lost ' +
'gained added adds canceled onboarded adjustment adjustments received receipts sold shrink writeoff write off turns turnover').split(' ').concat(['cancelled']);
var isLevel = function (col) {
if (col == null) return false;
var c = typeof col === 'string' ? { name: col } : col;
if (isRate(c)) return false;
var phrase = ' ' + nameWords(c.name).join(' ') + ' ';
var said = function (list) { return list.some(function (p) { return phrase.indexOf(' ' + p + ' ') !== -1; }); };
if (said(['days', 'dias']) || said(LEVEL_MOVES)) return false;
if (said(LEVEL_PHRASES)) return true;
if (said(['closing', 'ending', 'opening', 'beginning'])) return said(LEVEL_STOCK_NOUNS);
if (said(['avg', 'average', 'mean', 'median', 'total', 'change', 'delta', 'movement'])) return false;
return said(['balance', 'balances', 'on hand', 'onhand', 'inventory', 'stock on hand', 'stock level', 'in stock', 'headcount',
'head count', 'fte', 'ftes', 'employees', 'employee count', 'workforce', 'staff count', 'active users', 'active customers',
'active accounts', 'active members', 'active subscribers', 'subscribers', 'backlog', 'open positions', 'open roles']);
};
var sums = mKey === 'sum' && m !== 'count' && m !== 'distinct';
var meanOf = function (a) { return !a.length ? null : d3.mean(a); };
var averaged = function (col) { return sums && isRate(col); };
return {
keys: keys,
kIdx: kIdx,
n: keys.length,
frameOf: function (r) { var k = bkeyOf(r); return kIdx.has(k) ? kIdx.get(k) : null; },
aggregate: aggregate,
aggName: mLabel,
aggMode: m,
isRate: isRate,
isLevel: isLevel,
aggregateFor: function (col) { return averaged(col) ? meanOf : aggregate; },
aggNameFor: function (col) { return averaged(col) ? d3.llmText('d3.keyframes.agg.average', AGGLBL.average) : mLabel; },
accumulatesFor: function (col) { return !/^(average|median|min|max)$/.test(m) && !averaged(col); }
};
};
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 NEAR_MISS_PX = 1, SHORT_KEEP = 3;   // 1 px, flat: a census of 142 saved generations found 8% of a wide room overprinting long labels
function nearMiss(w, room) { return overflow !== 'drop' && w <= room + NEAR_MISS_PX; }
function keepShort(s, w, room) { return overflow !== 'drop' && s.length <= SHORT_KEEP && w <= room * 1.5; }
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
if (nearMiss(w, room)) return room;                        // a near miss is drawn whole

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) : (keepShort(full, w, room) ? full : '');
return room;
}
}
node.textContent = lo > 0 ? full.slice(0, lo) + ell : (keepShort(full, w, room) ? full : '');
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.llmUtcDays = function (data, options) {
if (!data || !Array.isArray(data.columns) || !Array.isArray(data.rows)) return data;
if (options && options.dateCellsAreUtcDays === true) return data;
var DAY = 86400000;
var dateCols = [];
for (var ci = 0; ci < data.columns.length; ci++) {
var col = data.columns[ci];
if (col && /date|time/i.test(String(col.dataType || ''))) dateCols.push(ci);
}
if (!dateCols.length) return data;
function empty(v) { return v === null || v === undefined || v === ''; }
function localWall(t) { return t - new Date(t).getTimezoneOffset() * 60000; }
var fix = [];
for (var k = 0; k < dateCols.length; k++) {
var idx = dateCols[k], moved = 0, ok = true;
for (var r = 0; r < data.rows.length; r++) {
var row = data.rows[r];
if (!row || empty(row[idx])) continue;
var t = new Date(row[idx]).getTime();
if (!isFinite(t)) { ok = false; break; }
if (t % DAY === 0) continue;
if (localWall(t) % DAY !== 0) { ok = false; break; }
moved++;
}
if (ok && moved > 0) fix.push(idx);
}
if (!fix.length) return data;
var rows = data.rows.map(function (row) {
if (!row) return row;
var out = row.slice();
for (var f = 0; f < fix.length; f++) {
var j = fix[f];
if (empty(out[j])) continue;
var tt = new Date(out[j]).getTime();
if (tt % DAY === 0) continue;
out[j] = new Date(localWall(tt)).toISOString();
}
return out;
});
var result = {};
for (var key in data) if (Object.prototype.hasOwnProperty.call(data, key)) result[key] = data[key];
result.rows = rows;
return result;
};
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) {
  data = d3.llmUtcDays(data, options);
  const TYPE_FLOOR = 10;
  container.replaceChildren();
  var W = options.width, H = options.height;
  var FS = Math.max(TYPE_FLOOR, Math.min(14, Math.min(W, H) / 55));
  var SUB_FS = Math.max(TYPE_FLOOR, FS * 0.9), SMALL_FS = Math.max(TYPE_FLOOR, FS * 0.85);
  var CAP_FS = Math.max(TYPE_FLOOR, FS * 0.8), NOTE_FS = Math.max(TYPE_FLOOR, FS * 0.78);
  var fg = options.themeFg || 'currentColor';
  var accent = options.themeAccent || fg;
  var loc = options.cultureCode || 'en-US';
  var nf = new Intl.NumberFormat(loc, { notation: 'compact', maximumSignificantDigits: 3 });
  var pf = function (r) {
    return (r >= 0 ? '+' : '-') + new Intl.NumberFormat(loc, { maximumFractionDigits: 2 }).format(Math.abs(r) * 100) + '%';
  };
  var svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
  var NEEDS = 'What-if projection requires a date axis with at least 6 periods and one measure.';
  function emptyFrame(msg) {
    svg.append('rect').attr('x', 0.5).attr('y', 0.5).attr('width', W - 1).attr('height', H - 1)
      .attr('fill', 'none').attr('stroke', fg).attr('stroke-opacity', 0.25);
    svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle')
      .attr('font-size', FS).attr('fill', fg).text(msg);
  }

  var cols = data.columns || [], rows = data.rows || [];
  var idx = function (n) { return data.columns.findIndex(function (c) { return c.name === n; }); };
  var ciRow = idx('__rowIdx__');
  var ciTime = idx('Date'), ciVal = idx('Sum of Steps');
  if (ciTime < 0) throw new Error('INVALID:column "Date" not found');
  if (ciVal < 0) throw new Error('INVALID:column "Sum of Steps" not found');
  if (!rows.length) { emptyFrame(options.noDataText || 'No data to display'); return; }

  var asDate = function (v) { return (v instanceof Date) ? v : new Date(v); };
  var num = function (v) { if (v === null || v === undefined || v === '') return null; var n = +v; return isFinite(n) ? n : null; };
  var combine = function (vals) { return vals.length ? d3.mean(vals) : null; };

  var stamps = [];
  rows.forEach(function (r) { var d = asDate(r[ciTime]); if (!isNaN(+d)) stamps.push(+d); });
  if (!stamps.length) { emptyFrame(options.noDataText || 'No data to display'); return; }
  var distinctStamps = Array.from(new Set(stamps)).sort(function (a, b) { return a - b; });

  function grainOfKey(k) {
    k = String(k);
    if (/^\d{4}-\d{2}-\d{2}$/.test(k)) return 'day';
    if (/^\d{4}-W\d{2}$/.test(k)) return 'week';
    if (/^\d{4}-\d{2}$/.test(k)) return 'month';
    if (/^\d{4}-Q\d$/.test(k)) return 'quarter';
    if (/^\d{4}$/.test(k)) return 'year';
    return 'period';
  }
  function dateOfKey(k) {
    k = String(k); var y = +k.slice(0, 4);
    if (/^\d{4}-\d{2}-\d{2}$/.test(k)) return new Date(Date.UTC(y, +k.slice(5, 7) - 1, +k.slice(8, 10)));
    if (/^\d{4}-W\d{2}$/.test(k)) { var j4 = Date.UTC(y, 0, 4); return new Date(j4 - ((new Date(j4).getUTCDay() + 6) % 7) * 864e5 + (+k.slice(6, 8) - 1) * 6048e5); }
    if (/^\d{4}-\d{2}$/.test(k)) return new Date(Date.UTC(y, +k.slice(5, 7) - 1, 1));
    if (/^\d{4}-Q\d$/.test(k)) return new Date(Date.UTC(y, (+k.slice(6, 7) - 1) * 3, 1));
    return new Date(Date.UTC(y, 0, 1));
  }
  function inferGrain(sorted) {
    if (sorted.length < 2) return 'period';
    var gaps = [];
    for (var i = 1; i < sorted.length; i++) gaps.push(sorted[i] - sorted[i - 1]);
    gaps.sort(function (a, b) { return a - b; });
    var med = gaps[Math.floor(gaps.length / 2)], day = 86400000;
    if (med <= day * 1.5) return 'day';
    if (med <= day * 9) return 'week';
    if (med <= day * 45) return 'month';
    if (med <= day * 135) return 'quarter';
    return 'year';
  }
  var kf = null, grainName;
  if (distinctStamps.length > 200) {
    kf = d3.llmKeyframes(rows, { time: function (r) { return r[ciTime]; }, maxIdeal: 200, aggregation: 'average' });
    grainName = grainOfKey(kf.keys[0]);
  } else grainName = inferGrain(distinctStamps);

  function stepDate(from, k) {
    var d = new Date(+from);
    if (grainName === 'day') return d3.utcDay.offset(d, k);
    if (grainName === 'week') return d3.utcWeek.offset(d, k);
    if (grainName === 'month') return d3.utcMonth.offset(d, k);
    if (grainName === 'quarter') return d3.utcMonth.offset(d, k * 3);
    if (grainName === 'year') return d3.utcYear.offset(d, k);
    var step = distinctStamps.length > 1 ? (distinctStamps[distinctStamps.length - 1] - distinctStamps[0]) / (distinctStamps.length - 1) : 86400000;
    return new Date(+from + step * k);
  }
  var labelOf = function (d) {
    if (grainName === 'year') return String(d.getUTCFullYear());
    if (grainName === 'quarter') return d.getUTCFullYear() + '-Q' + (Math.floor(d.getUTCMonth() / 3) + 1);
    if (grainName === 'month') return d.getUTCFullYear() + '-' + String(d.getUTCMonth() + 1).padStart(2, '0');
    return d.toISOString().slice(0, 10);
  };
  var sayWhen = function (d) {
    if (grainName !== 'month' && grainName !== 'day' && grainName !== 'week') return labelOf(d);
    var how = grainName === 'month' ? { year: 'numeric', month: 'short', timeZone: 'UTC' } : { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' };
    try { return new Intl.DateTimeFormat(loc, { timeZone: 'UTC', ...(how) }).format(d); } catch (e) { return labelOf(d); }
  };

  var periodKey = kf ? function (r) { return kf.frameOf(r); } : function (r) { var d = asDate(r[ciTime]); return isNaN(+d) ? null : +d; };
  var periodWhen = kf ? function (k) { return dateOfKey(kf.keys[k]); } : function (k) { return new Date(k); };
  var byPeriod = new Map();
  rows.forEach(function (r, ri) {
    var key = periodKey(r); if (key === null || key === undefined) return;
    var v = num(r[ciVal]); if (v === null) return;
    if (!byPeriod.has(key)) byPeriod.set(key, { when: periodWhen(key), vals: [], idx: [], stamps: new Set() });
    var slot = byPeriod.get(key);
    slot.vals.push(v); slot.stamps.add(+asDate(r[ciTime]));
    slot.idx.push(ciRow >= 0 ? r[ciRow] : ri);
  });
  var periods = Array.from(byPeriod.values()).sort(function (a, b) { return +a.when - +b.when; });
  var T = periods.map(function (p) { return p.when; });
  var A = periods.map(function (p) { return combine(p.vals); });
  var n = A.length;
  if (n < 6) { emptyFrame(options.noDataText || 'No data to display'); return; }

  var fill = periods.map(function (p) { return kf ? p.stamps.size : p.vals.length; });
  var mid = fill.slice(1, n - 1).sort(function (a, b) { return a - b; });
  var fullSize = mid.length ? mid[Math.floor(mid.length / 2)] : 0;
  var partialLast = fullSize >= 2 && fill[n - 1] < fullSize * 0.8;
  var partialFirst = fullSize >= 2 && fill[0] < fullSize * 0.8;
  if (n - (partialLast ? 1 : 0) - (partialFirst ? 1 : 0) < 5) { partialLast = false; partialFirst = false; }
  var aN = partialLast ? n - 2 : n - 1, a0 = partialFirst ? 1 : 0;

  var T0 = d3.llmThemeColors(options);
  var color = T0.legible(T0.categories(['Sum of Steps'])('Sum of Steps'));
  var series = [{ name: 'Average Steps per User per Day', color: color,
    pts: periods.map(function (p) { return { when: p.when, v: combine(p.vals), idx: p.idx }; }) }];

  function meanPositiveRatio(a) {
    var rs = [];
    for (var i = 1; i < a.length; i++) if (a[i - 1] > 0 && a[i] > 0) rs.push(a[i] / a[i - 1]);
    if (!rs.length) return 0;
    return rs.reduce(function (x, y) { return x + y; }, 0) / rs.length - 1;
  }
  var g = (A[a0] > 0 && A[aN] > 0 && aN > a0) ? Math.pow(A[aN] / A[a0], 1 / (aN - a0)) - 1 : meanPositiveRatio(A.slice(a0, aN + 1));
  if (!isFinite(g)) g = 0;
  var lo = Math.max(-0.5, Math.min(-0.1, -3 * Math.abs(g)));
  var hi = Math.min(1.0, Math.max(0.1, 3 * Math.abs(g)));
  var hMax = Math.max(2, Math.min(60, 2 * n));
  function valueAt(r, k) { return A[aN] * Math.pow(1 + r, k); }
  function project(r, Hh) {
    var pts = [], flatPts = [];
    for (var k = 1; k <= Hh; k++) {
      var w = stepDate(T[aN], k);
      pts.push({ k: k, when: w, v: valueAt(r, k) });
      flatPts.push({ when: w, v: A[aN] });
    }
    return { pts: pts, end: pts.length ? pts[pts.length - 1].v : A[aN], flat: A[aN], flatPts: flatPts };
  }

  // layout
  var STRIP_Y = FS * 1.6, STRIP_H = 2 * FS * 2.6 + FS * 1.2;
  var READ_Y = STRIP_Y + STRIP_H, READ_H = FS * 2.4;
  var AXIS_BAND = 9 + CAP_FS * 1.3;
  var mL = FS * 4.2, mR = FS * 2.5;
  var plotY = READ_Y + READ_H;
  var CAP_LINE = CAP_FS * 1.25;
  function captionLines(sentences, room, maxLines) {
    var lines = [], ends = [];
    sentences.forEach(function (s) {
      var cur = '';
      String(s).split(' ').forEach(function (w) {
        var cand = cur ? cur + ' ' + w : w;
        if (!cur || d3.llmFitLabel(cand, room, { fontSize: CAP_FS }) === cand) cur = cand;
        else { lines.push(cur); ends.push(false); cur = w; }
      });
      if (cur) { lines.push(cur); ends.push(true); }
    });
    maxLines = Math.max(1, Math.floor(maxLines) || 1);
    if (lines.length <= maxLines) return lines;
    var rest = lines.slice(maxLines - 1).map(function (l, i) { return l + (ends[maxLines - 1 + i] && maxLines + i < lines.length ? ';' : ''); });
    return lines.slice(0, maxLines - 1).concat([rest.join(' ')]);
  }
  var caps = [];
  if (partialLast) caps.push('The last ' + grainName + ' (' + labelOf(T[n - 1]) + ') holds ' + fill[n - 1] + ' of about ' + fullSize + ' rows - projected from ' + labelOf(T[aN]));
  if (partialFirst) caps.push('The first ' + grainName + ' holds ' + fill[0] + ' of about ' + fullSize + ' rows - the historical rate starts after it');
  if (kf) caps.push(rows.length + ' rows bucketed to ' + periods.length + ' ' + grainName + ' averages');
  caps.push('Mean steps per user per ' + (kf ? grainName : 'day') + ', averaged across all ' + d3.llmDisplayName('UserID') + 's');
  caps.push('Default rate is the historical first-to-last ' + grainName + ' rate; any seasonal swing counts as growth');
  var capLines = captionLines(caps, W - mL - FS * 0.5, (H - plotY - AXIS_BAND - FS * 6 - 2) / CAP_LINE);
  var mB = AXIS_BAND + CAP_FS * 0.25 + Math.max(1, capLines.length) * CAP_LINE + 2;
  var plotH = Math.max(FS * 6, H - plotY - mB);
  var plotW = Math.max(FS * 8, W - mL - mR);

  var strip = svg.append('g').attr('class', 'lch-knobs');
  var readG = svg.append('g').attr('class', 'lch-readouts');
  var plot = svg.append('g').attr('transform', 'translate(' + mL + ',' + plotY + ')');

  var rate = g, horizon = Math.min(12, n);
  var horizonShort = false;
  var horizonFmt = function (v) { v = Math.round(v); return horizonShort ? String(v) : d3.llmText('d3.projection.periods', v === 1 ? '{count} {grain}' : '{count} {grain}s', { count: v, grain: grainName }, v); };
  var histWord = 'historical: ';
  var rateFmt = function (v) { return histWord && Math.abs(v - g) < 0.00025 ? d3.llmText('d3.projection.historical_rate', 'historical: {rate}', { rate: pf(v) }) : pf(v); };
  var rateLabel = d3.llmText('d3.projection.growth_per', 'growth per {grain}', { grain: grainName });
  var tw = d3.llmSlider.textWidth;
  var labelW = Math.max(tw(rateLabel, SUB_FS), tw(d3.llmText('d3.projection.horizon', 'horizon'), SUB_FS));
  var stepperW = Math.max(20, Math.round(FS * 1.5)) + FS * 1.1;
  var RESET_TXT = d3.llmText('d3.projection.reset', 'reset');
  function pillTextW(t) { var pr = svg.append('text').attr('font-size', SMALL_FS).attr('visibility', 'hidden').text(t), w = 0; try { w = pr.node().getComputedTextLength(); } catch (e) { w = 0; } pr.remove(); return w > 0 ? w : String(t).length * SMALL_FS * 0.6; }
  var resetW = Math.max(20, FS * 3.2, pillTextW(RESET_TXT) + FS * 0.2), resetH = Math.max(20, FS * 2.2);
  var resetLeft = W - FS * 0.6 - resetW;
  var kx = mL + labelW + stepperW;
  var readoutW = Math.max(tw(rateFmt(g), SUB_FS), tw(horizonFmt(hMax), SUB_FS));
  if (resetLeft - FS - readoutW - stepperW - kx < FS * 5) {
    histWord = '';
    readoutW = Math.max(tw(rateFmt(g), SUB_FS), tw(horizonFmt(hMax), SUB_FS));
  }
  var rateReadW = tw(rateFmt(g), SUB_FS);
  var kwFloor = kx + FS * 5 + stepperW + rateReadW + FS * 0.5 > resetLeft ? FS * 3 : FS * 5;
  var kw = Math.max(kwFloor, Math.min(FS * 14, plotW * 0.42, resetLeft - FS - readoutW - stepperW - kx));
  if (kx + kw + stepperW + tw(horizonFmt(hMax), SUB_FS) > W - FS * 0.6) horizonShort = true;
  var ky = STRIP_Y + FS * 0.9;

  var sRate = d3.llmSlider(svg, {
    container: container, options: options, key: 'rate', domain: [lo, hi], step: 0.0005,
    'default': g, x: kx, y: ky, width: kw, fontSize: FS, label: rateLabel, labelRoom: labelW + FS * 0.5,
    format: rateFmt,
    onChange: function (v, phase) { rate = v; if (phase !== 'init') repaint(); },
  });
  var sHor = d3.llmSlider(svg, {
    container: container, options: options, key: 'horizon', domain: [1, hMax], step: 1,
    'default': Math.min(12, n), x: kx, y: ky + FS * 2.6, width: kw,
    fontSize: FS, label: d3.llmText('d3.projection.horizon', 'horizon'), labelRoom: labelW + FS * 0.5, format: horizonFmt,
    onChange: function (v, phase) { horizon = Math.round(v); if (phase !== 'init') repaint(); },
  });

  var reset = svg.append('g').attr('class', 'lch-reset lch-control').attr('aria-label', RESET_TXT).attr('cursor', 'pointer')
    .on('click', function () { sRate.reset(); sHor.reset(); });
  reset.append('rect').attr('x', resetLeft).attr('y', ky - resetH / 2)
    .attr('width', resetW).attr('height', resetH).attr('rx', 3)
    .attr('fill', 'transparent').attr('stroke', fg).attr('opacity', 0.6);
  reset.append('text').attr('x', resetLeft + resetW / 2).attr('y', ky + FS * 0.35).attr('text-anchor', 'middle')
    .attr('font-size', SMALL_FS).attr('fill', fg).text(RESET_TXT);

  var tileW = plotW / 3;
  function tile(i, label) {
    var gg = readG.append('g').attr('transform', 'translate(' + (mL + i * tileW) + ',' + (READ_Y + FS * 1.1) + ')');
    gg.append('text').attr('font-size', NOTE_FS).attr('fill', fg).attr('fill-opacity', 0.7).text(label);
    return gg.append('text').attr('y', FS * 1.25).attr('font-size', FS * 1.05).attr('fill', fg);
  }
  function fitTile(t, forms) {
    t.selectAll('title').remove();
    for (var k = 0; k < forms.length; k++) {
      d3.llmFitLabel(t, tileW - FS * 0.5, { pad: 0, text: forms[k], overflow: 'drop' });
      if (t.text()) break;
    }
    if (!t.text()) d3.llmFitLabel(t, tileW - FS * 0.5, { pad: 0, text: forms[forms.length - 1], shrinkTo: TYPE_FLOOR, overflow: 'drop' });
    if (t.text() !== forms[0]) t.append('title').text(forms[0]);
  }
  var tileEnd = tile(0, d3.llmText('d3.projection.end_value', 'end value'));
  var tileFlat = tile(1, d3.llmText('d3.projection.vs_flat', 'vs flat'));
  var tileTarget = tile(2, d3.llmText('d3.projection.target', 'target'));

  var x = d3.scaleUtc().range([0, plotW]);
  var y = d3.scaleLinear().range([plotH, 0]);
  var xAxisG = plot.append('g').attr('class', 'lch-x').attr('transform', 'translate(0,' + plotH + ')');
  var yAxisG = plot.append('g').attr('class', 'lch-y');
  var flatPath = plot.append('path').attr('class', 'lch-flat').attr('fill', 'none')
    .attr('stroke', fg).attr('stroke-opacity', 0.28).attr('stroke-width', 1).attr('stroke-dasharray', '2 3');
  var actualG = plot.append('g').attr('class', 'lch-actual');
  var projPath = plot.append('path').attr('class', 'lch-proj').attr('fill', 'none')
    .attr('stroke', series[0].color).attr('stroke-opacity', 0.6).attr('stroke-width', 2).attr('stroke-dasharray', '5 4');
  var projLabel = plot.append('text').attr('class', 'lch-proj-label')
    .attr('font-size', SMALL_FS).attr('fill', fg).attr('fill-opacity', 0.85);
  var capFull = caps.join('. ');
  capLines.forEach(function (ln, k) {
    var t = svg.append('text').attr('class', 'lch-caption').attr('x', mL).attr('y', plotY + plotH + AXIS_BAND + CAP_FS + k * CAP_LINE)
      .attr('font-size', CAP_FS).attr('fill', fg).attr('fill-opacity', 0.7);
    d3.llmFitLabel(t, W - mL - FS * 0.5, { pad: 0, text: ln });
    if (t.text() !== ln) t.append('title').text(capFull);
  });

  var line = d3.line().x(function (d) { return x(d.when); }).y(function (d) { return y(d.v); });
  var tip = options.allowTooltips === false ? null : d3.llmTooltip(container);

  var s0 = series[0];
  var allIdx = s0.pts.reduce(function (acc, p) { return acc.concat(p.idx); }, []).join(',');
  // wide transparent hit stroke behind the visible line
  s0.hit = actualG.append('path').attr('class', 'd3-mark').attr('fill', 'none').attr('stroke', 'transparent')
    .attr('stroke-width', 12).style('pointer-events', 'stroke').style('cursor', 'pointer')
    .attr('data-row-idx', allIdx).attr('aria-label', s0.name);
  s0.path = actualG.append('path').attr('class', 'd3-mark').attr('fill', 'none').attr('stroke', s0.color).attr('stroke-width', 2)
    .style('cursor', 'pointer').attr('data-row-idx', allIdx).attr('aria-label', s0.name);
  s0.partPath = actualG.append('path').attr('fill', 'none').attr('stroke', s0.color).attr('stroke-width', 1.5)
    .attr('stroke-opacity', 0.55).attr('stroke-dasharray', '2 3');
  s0.dots = actualG.append('g');

  function drawMarks() {
    var showDots = periods.length <= 120;
    var isPartial = function (d) { return (partialLast && +d.when === +T[n - 1]) || (partialFirst && +d.when === +T[0]); };
    var fullPts = s0.pts.filter(function (d) { return !isPartial(d); });
    var ld = line(fullPts);
    s0.path.attr('d', ld); s0.hit.attr('d', ld);
    var edges = [];
    if (partialFirst && isPartial(s0.pts[0])) edges.push([s0.pts[0], s0.pts[1]]);
    if (partialLast && isPartial(s0.pts[s0.pts.length - 1])) edges.push([s0.pts[s0.pts.length - 2], s0.pts[s0.pts.length - 1]]);
    s0.partPath.attr('d', edges.map(function (e) { return line(e); }).join(''));
    s0.dots.selectAll('circle').data(showDots ? s0.pts : []).join('circle')
      .attr('class', 'd3-mark').attr('r', Math.max(2, FS * 0.28))
      .attr('cx', function (d) { return x(d.when); }).attr('cy', function (d) { return y(d.v); })
      .attr('fill', function (d) { return isPartial(d) ? 'none' : s0.color; })
      .attr('stroke', s0.color).attr('stroke-width', function (d) { return isPartial(d) ? 1.5 : 0; })
      .style('pointer-events', 'all').style('cursor', 'pointer')
      .attr('data-row-idx', function (d) { return d.idx.join(','); })
      .attr('aria-label', function (d) { return s0.name + ' ' + sayWhen(d.when) + ': ' + nf.format(d.v); })
      .on('mouseover', function (e, d) { if (tip) tip.show(s0.name + ' ' + sayWhen(d.when) + ': ' + nf.format(d.v), e); })
      .on('mousemove', function (e) { if (tip) tip.move(e); })
      .on('mouseout', function () { if (tip) tip.hide(); });
  }
  // the line itself shows hover detail when dots are dropped
  [s0.path, s0.hit].forEach(function (sel) {
    sel.on('mouseover', function (e) { if (tip) tip.show(s0.name, e); })
      .on('mousemove', function (e) { if (tip) tip.move(e); })
      .on('mouseout', function () { if (tip) tip.hide(); });
  });

  function repaint() {
    var p = project(rate, horizon);
    var lastActual = T[aN];
    var lastProj = p.pts.length ? p.pts[p.pts.length - 1].when : lastActual;
    x.domain([T[0], lastProj]);
    var ys = [];
    s0.pts.forEach(function (q) { if (q.v !== null) ys.push(q.v); });
    p.pts.forEach(function (q) { ys.push(q.v); });
    var yMin = Math.min.apply(null, ys), yMax = Math.max.apply(null, ys);
    if (yMin === yMax) { yMin -= 1; yMax += 1; }
    var padY = (yMax - yMin) * 0.08;
    y.domain([Math.max(0, Math.min(0, yMin - padY)), yMax + padY]);

    xAxisG.call(d3.axisBottom(x).ticks(Math.max(2, Math.floor(plotW / (FS * 6)))).tickSizeOuter(0)).attr('font-size', CAP_FS);
    yAxisG.call(d3.axisLeft(y).ticks(Math.max(2, Math.floor(plotH / (FS * 3)))).tickFormat(function (v) { return nf.format(v); }).tickSizeOuter(0)).attr('font-size', CAP_FS);

    drawMarks();
    projPath.attr('d', line([{ when: lastActual, v: A[aN] }].concat(p.pts)));
    flatPath.attr('d', line([{ when: lastActual, v: A[aN] }].concat(p.flatPts)));

    var projFull = d3.llmText('d3.projection.proj_reader', 'projected - assumes {rate} per {grain}, set by reader', { rate: pf(rate), grain: grainName });
    var projForms = [projFull, d3.llmText('d3.projection.proj', 'projected - assumes {rate} per {grain}', { rate: pf(rate), grain: grainName }),
      d3.llmText('d3.projection.proj_assumes', 'assumes {rate} per {grain}', { rate: pf(rate), grain: grainName }),
      d3.llmText('d3.projection.proj_rate', '{rate} per {grain}', { rate: pf(rate), grain: grainName })];
    var px0 = x(lastActual) + FS * 0.4;
    projLabel.selectAll('title').remove();
    projLabel.attr('text-anchor', 'start').attr('x', px0).attr('y', Math.max(FS, y(p.end) - FS * 0.8));
    for (var a = 0; a < projForms.length; a++) {
      d3.llmFitLabel(projLabel, W - mL - FS * 0.3 - px0, { pad: 0, text: projForms[a], overflow: 'drop' });
      if (projLabel.text()) break;
    }
    if (!projLabel.text()) {
      projLabel.attr('text-anchor', 'end').attr('x', plotW - FS * 0.3);
      for (var b = 0; b < projForms.length; b++) {
        d3.llmFitLabel(projLabel, plotW - FS * 0.6, { pad: 0, text: projForms[b], overflow: 'drop' });
        if (projLabel.text()) break;
      }
    }
    if (projLabel.text() !== projFull) projLabel.append('title').text(projFull);

    fitTile(tileEnd, [nf.format(p.end)]);
    fitTile(tileFlat, [p.flat === 0 ? d3.llmText('d3.projection.n_a', 'n/a') : pf((p.end - p.flat) / Math.abs(p.flat))]);
    fitTile(tileTarget, [d3.llmText('d3.projection.no_target', 'no target given'), d3.llmText('d3.projection.none_given', 'none given'), d3.llmText('d3.projection.none', 'none')]);
  }

  repaint();
}

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.

This application may no longer respond until reloaded. Reload 🗙