Orders by CountryCode, as bubbles on a world map

Where in the world is Orders largest?

One row per city — 117 of them across 55 countries, each with its country name AND ISO-2 code, world region, a city tier (Capital / Primary / Secondary), order count, revenue, and average order value. The city names alone resolve to real coordinates — no latitude/longitude columns anywhere — which is exactly the lookup a world bubble map needs, and the country columns roll the same rows up into a world choropleth. Orders and revenue give the bubbles independent size and colour; AvgOrderValue is a per-row rate, so treat it as an average, not a sum.

World City Sales — 117 Cities Across 55 Countries: 117 rows, 8 columns. Download the CSV

The first 10 rows
CountryCodeCountryRegionCityCityTierOrdersRevenueAvgOrderValue
USUnited StatesAmericasNew YorkPrimary3662384510105
USUnited StatesAmericasChicagoPrimary3841426351111
USUnited StatesAmericasWashingtonCapital1386213444154
USUnited StatesAmericasBoiseSecondary13414472108
USUnited StatesAmericasAshevilleSecondary582175764302
CACanadaAmericasTorontoPrimary3359466901139
CACanadaAmericasVancouverPrimary3607826003229
CACanadaAmericasOttawaCapital161515988599
CACanadaAmericasKelownaSecondary19750629257
CACanadaAmericasLondonSecondary338102414303
A world bubble map of the "World City Sales — 117 Cities Across 55 Countries" dataset: a circle at each of 55 CountryCode values, sized by its Orders.
A world bubble map of the "World City Sales — 117 Cities Across 55 Countries" dataset: a circle at each of 55 CountryCode values, sized by its Orders.

How to read it

A bubble's area, not its width, is its Orders, so a bubble twice as wide holds four times as much. US is largest at 9.6K.

The chart's code (87 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) {}
};
d3.llmValueColumn = function (columns, rows, opts) {
opts = opts || {};
var cols = Array.isArray(columns) ? columns : [];
var data = Array.isArray(rows) ? rows : [];

var isHost = function (c) {
var n = (c && c.name != null) ? String(c.name) : '';
return n.indexOf('__') === 0;
};
var taken = {};
(Array.isArray(opts.exclude) ? opts.exclude : []).forEach(function (i) {
if (i != null && i >= 0) taken[i] = 1;
});
var coordinates = [];
if (opts.excludeCoordinates) {
var coordWords = d3.llmValueColumn.nameWords;
var allLongitudes = function (ci) {
var seenL = 0;
for (var rr = 0; rr < data.length; rr++) {
var lv = data[rr] ? data[rr][ci] : null;
if (lv === null || lv === undefined || lv === '') continue;
lv = +lv; seenL++;
if (!isFinite(lv) || lv < -180 || lv > 180) return false;
}
return seenL > 0;
};
cols.forEach(function (c, ci) {
if (!c || isHost(c)) return;
var declared = String(c.semanticType || c.dataCategory || '').toLowerCase();
var w = coordWords(c.name);
if (declared === 'latitude' || declared === 'longitude'
|| w.some(function (t) { return /^(lat|latitude|lon|lng|longitude)$/.test(t); })
|| (w.indexOf('long') >= 0 && allLongitudes(ci))) {
taken[ci] = 1;
coordinates.push(String(c.name));
}
});
}

var NUMERIC_TYPES = { integer: 1, decimal: 1, double: 1, float: 1, single: 1,
number: 1, int64: 1, int32: 1, currency: 1, money: 1 };

var isNumericCol = function (c, i) {
var dt = (c && c.dataType != null) ? String(c.dataType).toLowerCase() : '';
if (dt) return NUMERIC_TYPES[dt] === 1;
var seen = 0, num = 0;
for (var r = 0; r < data.length && seen < 50; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '') continue;
seen++;
if (typeof v !== 'boolean' && isFinite(+v)) num++;
}
return seen > 0 && num === seen;
};

var isRegionCode = function (c) {
var k = (c && c.geoKind != null) ? String(c.geoKind).toLowerCase() : '';
if (!k) return false;
return k.indexOf('zip') === 0 || k.indexOf('us-zip') === 0 || k.indexOf('us-state') === 0 ||
k.indexOf('us-county') === 0 || k.indexOf('us-fips') === 0 || k.indexOf('fips') === 0 ||
k.indexOf('country-') === 0 || k.indexOf('iso-') === 0;
};

var ID_TOKENS = { id: 1, ids: 1, identifier: 1, code: 1, codes: 1, zip: 1, zipcode: 1,
postal: 1, postcode: 1, fips: 1, guid: 1, uuid: 1, sku: 1, upc: 1, ean: 1,
isbn: 1, key: 1, num: 1, number: 1, no: 1, ref: 1, serial: 1, barcode: 1,
account: 1, acct: 1, vin: 1, imei: 1, ssn: 1 };
var nameLooksLikeId = function (c) {
var n = (c && c.name != null) ? String(c.name) : '';
if (!n) return false;
var parts = n.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[^A-Za-z0-9]+/);
for (var p = 0; p < parts.length; p++) {
if (parts[p] && ID_TOKENS[parts[p].toLowerCase()] === 1) return true;
}
return false;
};

var looksLikeKeyData = function (c, i) {
var seen = 0, ints = 0, vals = {}, distinct = 0;
for (var r = 0; r < data.length && seen < 2000; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '') continue;
seen++;
var num = +v;
if (isFinite(num) && Math.floor(num) === num) ints++;
var kk = String(v);
if (vals[kk] !== 1) { vals[kk] = 1; distinct++; }
}
return seen >= 8 && ints === seen && (distinct / seen) >= 0.9;
};

var isIdentifierCol = function (c, i) {
if (!c) return false;
if (isRegionCode(c)) return true;
return nameLooksLikeId(c) && looksLikeKeyData(c, i);
};

var STRONG_ID_HEADS = { id: 1, ids: 1, identifier: 1, key: 1, zip: 1, zipcode: 1, postal: 1, postcode: 1, fips: 1,
guid: 1, uuid: 1, sku: 1, upc: 1, ean: 1, isbn: 1, serial: 1, barcode: 1, vin: 1, imei: 1, ssn: 1 };
var WEAK_ID_TAILS = { code: 1, codes: 1, number: 1, num: 1, no: 1, nbr: 1, ref: 1 };
var allIntegers = function (i) {
var seen = 0;
for (var r = 0; r < data.length && seen < 2000; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '' || typeof v === 'boolean') continue;
var n = +v;
if (!isFinite(n) || Math.floor(n) !== n) return false;
seen++;
}
return seen > 0;
};
var COUNT_WORDS = { count: 1, countd: 1, distinct: 1, recuento: 1, contagem: 1, anzahl: 1, aantal: 1, conteggio: 1,
antal: 1, antall: 1, lukumaara: 1, 'lukum\u00e4\u00e4r\u00e4': 1, pocet: 1, 'po\u010det': 1, liczba: 1 };
var NUMBER_OF = { number: 1, num: 1, no: 1, nombre: 1 };
var OF_WORDS = { of: 1, de: 1, du: 1, des: 1 };
var countsSomething = function (c, w) {
if (/^\s*#/.test(String(c.name))) return true;
for (var k = 0; k < w.length; k++) {
if (COUNT_WORDS[w[k]] === 1) return true;
if (NUMBER_OF[w[k]] === 1 && OF_WORDS[w[k + 1]] === 1) return true;
}
return false;
};
var CODE_WORDS = { zip: 1, zipcode: 1, postal: 1, postcode: 1, fips: 1, code: 1, iso: 1, geoid: 1 };
var isFlaggedIdentifier = function (c, i) {
if (!c) return false;
var w = d3.llmValueColumn.nameWords(c.name);
if (isRegionCode(c)) for (var cw = 0; cw < w.length; cw++) if (CODE_WORDS[w[cw]] === 1) return true;
if (!w.length || countsSomething(c, w)) return false;
var head = w[w.length - 1];
if (WEAK_ID_TAILS[head] === 1 && w.length > 1 && STRONG_ID_HEADS[w[w.length - 2]] === 1) head = w[w.length - 2];
if (!(STRONG_ID_HEADS[head] === 1 || w[0] === 'id')) return false;
return allIntegers(i);
};

var DATE_KEY_WORDS = { key: 1, date: 1, period: 1, month: 1, yyyymm: 1, yyyymmdd: 1, ym: 1, ymd: 1 };
var isDateKey = function (c, i) {
if (!c) return false;
var w = d3.llmValueColumn.nameWords(c.name), named = false;
for (var k = 0; k < w.length; k++) if (DATE_KEY_WORDS[w[k]] === 1) { named = true; break; }
if (!named) return false;
var seen = 0, ymd = 0, ym = 0;
for (var r = 0; r < data.length && seen < 2000; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '' || typeof v === 'boolean') continue;
var n = +v;
if (!isFinite(n) || Math.floor(n) !== n) return false;
seen++;
if (n >= 19000101 && n <= 21001231) {
var mo = Math.floor(n / 100) % 100, dd = n % 100;
if (mo >= 1 && mo <= 12 && dd >= 1 && dd <= 31) ymd++;
} else if (n >= 190001 && n <= 210012) {
var m2 = n % 100;
if (m2 >= 1 && m2 <= 12) ym++;
}
}
return seen > 0 && (ymd === seen || ym === seen);
};

var isTextMeasure = function (c) {
if (!c || !c.isMeasure) return false;
var dt = (c.dataType != null) ? String(c.dataType).toLowerCase() : '';
if (!dt || NUMERIC_TYPES[dt] === 1 || dt === 'datetime' || dt === 'date' || dt === 'boolean') return false;
if (c.stdDev != null || c.sum != null || c.avgValue != null) return false;
return String(c.valueNature || '').toLowerCase() !== 'continuous';
};

var valueIndex = -1, resolvedBy = 'count';
var skipped = [];
var skippedText = [];      // measures passed over because they hold text (isTextMeasure)

if (opts.prefer != null) {
var want = opts.prefer;
for (var q = 0; q < cols.length; q++) {
if (!cols[q]) continue;
if (q === want || (typeof want === 'string' && String(cols[q].name) === want)) {
if (!taken[q] && !isHost(cols[q])) { valueIndex = q; resolvedBy = 'preferred'; }
break;
}
}
}

var refused = {};
var notAQuantity = function (c, ci) {
if (refused[ci] !== undefined) return refused[ci];
return (refused[ci] = isTextMeasure(c) ? 'text' : ((isFlaggedIdentifier(c, ci) || isDateKey(c, ci)) ? 'key' : ''));
};
var IDENT_LAST = { id: 1, ids: 1, uuid: 1, guid: 1, key: 1, zip: 1, zipcode: 1, postal: 1, postalcode: 1, ssn: 1,
code: 1, codes: 1, sku: 1, isbn: 1, msisdn: 1, imei: 1 };
var ORDINAL_WORDS = { hour: 1, hr: 1, day: 1, dow: 1, dom: 1, weekday: 1, week: 1, wk: 1, woy: 1, month: 1, mth: 1,
quarter: 1, qtr: 1, year: 1, yr: 1, semester: 1, trimester: 1, decade: 1, period: 1, fiscal: 1,
fy: 1, rank: 1, level: 1, lvl: 1, tier: 1, grade: 1, band: 1, decile: 1, percentile: 1,
quartile: 1, quintile: 1, score: 1, rating: 1, stars: 1, step: 1, stage: 1, phase: 1, round: 1,
wave: 1, episode: 1, chapter: 1, age: 1, cohort: 1, generation: 1, seniority: 1, position: 1,
sequence: 1, seq: 1, priority: 1 };
var looksContinuous = function (c, i) {
var w = d3.llmValueColumn.nameWords(c.name);
if (w.length && IDENT_LAST[w[w.length - 1]] === 1) return false;
if (d3.llmValueColumn.localizedIdentifierWord(c.name)) return false;
var dt = (c && c.dataType != null) ? String(c.dataType).toLowerCase() : '';
var hasFraction = false, seenV = {}, distinct = 0, nonblank = 0, mn = Infinity, mx = -Infinity;
for (var r = 0; r < data.length; r++) {
var v = data[r] ? data[r][i] : null;
if (v == null || v === '' || typeof v === 'boolean') continue;
var n = +v;
if (!isFinite(n)) continue;
nonblank++;
var key = String(v);
if (seenV[key] !== 1) { seenV[key] = 1; distinct++; }
if (n < mn) mn = n;
if (n > mx) mx = n;
if (Math.floor(n) !== n) hasFraction = true;
}
if (nonblank === 0) return false;
var fractional = hasFraction || dt === 'decimal' || dt === 'double' || dt === 'float' || dt === 'single'
|| dt === 'currency' || dt === 'money';
var span = mx - mn + 1, density = span > 0 ? distinct / span : 1;
if (density >= 0.9) {
for (var k = 0; k < w.length; k++) if (ORDINAL_WORDS[w[k]] === 1 && distinct <= 120) return false;
if (mn >= 1900 && mx <= 2100) return false;
if (mn >= 0 && mx <= 20) return false;
}
return distinct > 12 && (fractional || distinct >= 100 || distinct / nonblank >= 0.30);
};
var measures = [];
for (var mi = 0; mi < cols.length; mi++) {
if (taken[mi] || !cols[mi] || !cols[mi].isMeasure || isHost(cols[mi])) continue;
if (!notAQuantity(cols[mi], mi)) measures.push(mi);
}
var measuresInferred = false;
var anyFlagged = false, anyProfiled = false;
for (var fi = 0; fi < cols.length; fi++) {
var fc = cols[fi];
if (!fc || isHost(fc)) continue;
if (fc.isMeasure) anyFlagged = true;
if (fc.valueNature != null || fc.distinctCount != null) anyProfiled = true;
}
if (!anyFlagged && !anyProfiled) {
for (var ni = 0; ni < cols.length; ni++) {
if (taken[ni] || !cols[ni] || isHost(cols[ni])) continue;
if (!isNumericCol(cols[ni], ni)) continue;
if (isIdentifierCol(cols[ni], ni) || isDateKey(cols[ni], ni)) continue;
if (!looksContinuous(cols[ni], ni)) continue;
measures.push(ni);
}
measuresInferred = measures.length > 0;
}

if (valueIndex < 0) {
for (var i = 0; i < cols.length; i++) {
if (taken[i]) continue;
if (!cols[i] || !cols[i].isMeasure || isHost(cols[i])) continue;
var why = notAQuantity(cols[i], i);
if (why === 'text') { skippedText.push(String(cols[i].name)); continue; }
if (why === 'key') { skipped.push(String(cols[i].name)); continue; }
valueIndex = i; resolvedBy = 'measure'; break;
}
}
if (valueIndex < 0) {
for (var j = 0; j < cols.length; j++) {
if (taken[j] || !cols[j] || isHost(cols[j])) continue;
if (!isNumericCol(cols[j], j)) continue;
if (refused[j] === 'key') continue;          // a flagged key rule 1 already refused and named
if (isIdentifierCol(cols[j], j) || isDateKey(cols[j], j)) {
skipped.push(String(cols[j].name));
continue;
}
valueIndex = j; resolvedBy = 'numeric'; break;
}
}

var labelIndex = -1;
for (var k = 0; k < cols.length; k++) {
if (taken[k] || !cols[k] || isHost(cols[k]) || k === valueIndex) continue;
labelIndex = k; break;
}

var isCount = valueIndex < 0;
var nameOf = function (idx) {
var c = cols[idx];
return (c && c.name != null) ? String(c.name) : '';
};

return {
valueIndex: valueIndex,
valueName: isCount ? (opts.countLabel || 'Rows') : nameOf(valueIndex),
labelIndex: labelIndex,
labelName: labelIndex >= 0 ? nameOf(labelIndex) : '',
isCount: isCount,
resolvedBy: resolvedBy,
skipped: skipped,
skippedText: skippedText,
coordinates: coordinates,
measures: measures,
measuresInferred: measuresInferred,
valueOf: function (row) {
if (isCount) return 1;
if (!row) return null;
var v = row[valueIndex];
if (v == null || v === '' || typeof v === 'boolean') return null;
var n = +v;
return isFinite(n) ? n : null;
}
};
};

d3.llmValueColumn.nameWords = function (name, opts) {
var s = String(name == null ? '' : name);
try { s = s.normalize('NFC'); } catch (e) { /* an unpaired surrogate: read it as it stands */ }
s = s.replace(/([\p{Ll}\p{Nd}])(?=\p{Lu})/gu, '$1 ').toLowerCase();
return s.split(opts && opts.digits ? /[^\p{L}\p{M}\p{N}]+/u : /[^\p{L}\p{M}]+/u)
.filter(function (w) { return w.length > 0; });
};

d3.llmValueColumn.localizedIdentifierWord = (function () {
var WORDS = {
de: ['nr', 'nummer', 'kennung', 'kennziffer', 'plz', 'postleitzahl'],
nl: ['nr', 'nummer'],
sv: ['nr', 'nummer'],
da: ['nr', 'nummer'],
nb: ['nr', 'nummer'],
fi: ['tunnus', 'koodi', 'nro'],
hu: ['azonos\u00edt\u00f3', 'k\u00f3d'],
tr: ['kod', 'kodu', 'numaras\u0131', 'numarasi'],
zh: ['\u7f16\u53f7', '\u4ee3\u7801', '\u7f16\u7801', '\u53f7\u7801', '\u90ae\u7f16'],
ja: ['\u756a\u53f7', '\u30b3\u30fc\u30c9'],
ko: ['\ubc88\ud638', '\ucf54\ub4dc'],
hi: ['\u0915\u094b\u0921', '\u0915\u094d\u0930\u092e\u093e\u0902\u0915'],
fr: ['num\u00e9ro'],
es: ['c\u00f3digo'],
pt: ['c\u00f3digo', 'cep'],
it: ['codice'],
pl: ['kod', 'numer'],
cs: ['k\u00f3d', '\u010d\u00edslo'],
sk: ['k\u00f3d', '\u010d\u00edslo'],
hr: ['\u0161ifra', 'oznaka'],
ru: ['\u043a\u043e\u0434', '\u043d\u043e\u043c\u0435\u0440'],
uk: ['\u043a\u043e\u0434', '\u043d\u043e\u043c\u0435\u0440'],
el: ['\u03ba\u03c9\u03b4\u03b9\u03ba\u03cc\u03c2'],
ar: ['\u0631\u0645\u0632', '\u0643\u0648\u062f', '\u0631\u0642\u0645'],
he: ['\u05e7\u05d5\u05d3'],
id: ['kode', 'nomor'],
vi: ['m\u00e3'],
th: ['\u0e23\u0e2b\u0e31\u0e2a']
};
var HEAD_INITIAL = ['fr', 'es', 'pt', 'it', 'pl', 'cs', 'sk', 'hr', 'ru', 'uk', 'el', 'ar', 'he', 'id', 'vi', 'th'];
var COMPOUNDS = ['nl', 'de', 'sv', 'da', 'nb', 'fi', 'hu'];
var NO_BREAKS = ['zh', 'ja', 'th'];
var UNFOLDED = ['num\u00e9ro'];
var GLUED = { ar: ['\u0627\u0644', '\u0648\u0627\u0644', '\u0628\u0627\u0644', '\u0641\u0627\u0644', '\u0643\u0627\u0644', '\u0644\u0644', '\u0648', '\u0641', '\u0628', '\u0643', '\u0644'], he: ['\u05d4', '\u05d5', '\u05d1', '\u05dc', '\u05de', '\u05e9', '\u05db', '\u05d5\u05d4', '\u05e9\u05d4', '\u05de\u05d4', '\u05d5\u05d1', '\u05d5\u05dc', '\u05d5\u05de', '\u05d1\u05d4', '\u05dc\u05d4'] };
var DEFAULT_PREFIXES = ['somme de', 'suma de', 'soma de', 'summe von', 'som van', 'somma di', 'summa av', 'sum av', 'sum af', 'soucet z', 'suma z', 'totaal van', 'total de', 'toplam', 'osszeg', 'nombre de', 'recuento de', 'contagem de', 'anzahl von', 'aantal van', 'conteggio di', 'antal av', 'lukumaara', 'pocet z', 'sum pa', '\u0441\u0443\u043c\u043c\u0430', '\u043a\u043e\u043b\u0438\u0447\u0435\u0441\u0442\u0432\u043e', '\u0441\u0443\u043c\u0430', '\u043a\u0456\u043b\u044c\u043a\u0456\u0441\u0442\u044c', '\u03b1\u03b8\u03c1\u03bf\u03b9\u03c3\u03bc\u03b1', '\u03c0\u03bb\u03b7\u03b8\u03bf\u03c2'];
var DEFAULT_SUFFIXES = ['osszege', 'sucet', '\u7684\u603b\u548c', '\u7684\u8ba1\u6570', '\u306e\u5408\u8a08', '\uc758 \ud569\uacc4'];
var has = function (list, x) { return list.indexOf(x) >= 0; };
var cpLen = function (s) { return Array.from(s).length; };
var STROKE = { '\u0142': 'l', '\u0141': 'L', '\u0131': 'i', '\u00f8': 'o', '\u00d8': 'O', '\u0111': 'd', '\u0110': 'D', '\u00f0': 'd', '\u00d0': 'D' };
var DIGIT_ZEROS = [0x0660, 0x06F0, 0x0966, 0x0E50, 0xFF10];
var foldName = function (s) {
var out = '';
Array.from(s).forEach(function (ch) {
if (STROKE[ch]) { out += STROKE[ch]; return; }
var cp = ch.codePointAt(0);
for (var z = 0; z < DIGIT_ZEROS.length; z++) if (cp >= DIGIT_ZEROS[z] && cp <= DIGIT_ZEROS[z] + 9) { out += String.fromCharCode(0x30 + cp - DIGIT_ZEROS[z]); return; }
if ((cp >= 0xFF21 && cp <= 0xFF3A) || (cp >= 0xFF41 && cp <= 0xFF5A)) { out += String.fromCharCode(cp - 0xFEE0); return; }
var d = ch.normalize('NFD').replace(/[\u0300-\u036f]/g, '');
out += d.length === 1 ? d : ch;
});
return out;
};
var readWords = function (name) {
return String(name == null ? '' : name).normalize('NFC')
.replace(/([\p{Ll}\p{Nd}])(\p{Lu})/gu, '$1 $2').replace(/[_\-.\/]+/g, ' ')
.replace(/[^\p{L}\p{M}\p{N}\x00-\x7F]/gu, ' ').toLowerCase().split(/\s+/)
.filter(function (w) { return w.length > 0; });
};
var readName = function (name) {
var s = String(name == null ? '' : name).normalize('NFC');
var words = readWords(s), folded = readWords(foldName(s));
return { words: words, folded: folded.length === words.length ? folded : words.map(foldName) };
};
var lowerNfc = function (s) { return s.normalize('NFC').toLowerCase(); };
var alt = function (phrases) {
return phrases.slice().sort(function (a, b) { return b.length - a.length; })
.map(function (t) { return t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+'); }).join('|');
};
var hasCjk = function (t) {
return Array.from(t).some(function (ch) { var c = ch.codePointAt(0); return (c >= 0x2e80 && c <= 0x9fff) || (c >= 0xac00 && c <= 0xd7af); });
};
var PREFIX_RE = new RegExp('^\\s*(?:(?:sum|count|count\\s+distinct|distinct\\s+count)\\s+of\\s+|(?:' + alt(DEFAULT_PREFIXES) + ')\\s+)', 'i');
var SUFFIX_RE = (function () {
var latin = DEFAULT_SUFFIXES.filter(function (l) { return !hasCjk(l); }), cjk = DEFAULT_SUFFIXES.filter(hasCjk), parts = [];
if (latin.length) parts.push('(?:\\s+|\\s*[\u2013\u2014-]\\s*)(' + alt(latin) + ')');
if (cjk.length) parts.push('\\s*(' + alt(cjk) + ')');
return new RegExp('(?:' + parts.join('|') + ')\\s*$', 'i');
})();
var stripAgg = function (name) {
var s = String(name == null ? '' : name), folded = foldName(s);
var m = PREFIX_RE.exec(folded);
if (m) return s.slice(m[0].length).trim();
var sm = SUFFIX_RE.exec(folded);
if (sm && folded.slice(0, sm.index).trim() !== '') return s.slice(0, sm.index).trim();
return s.trim();
};
var endsWithStem = function (word, token, minStem) {
return !!word && !!token && word.length > token.length && word.endsWith(token) && cpLen(word.slice(0, word.length - token.length)) >= minStem;
};
var gluedStems = function (word, lang) {
var out = [], list = GLUED[lang];
if (!word || !list) return out;
list.slice().sort(function (a, b) { return b.length - a.length; }).forEach(function (p) {
if (word.length > p.length && word.startsWith(p)) { var st = word.slice(p.length); if (cpLen(st) >= 2 && out.indexOf(st) < 0) out.push(st); }
});
return out;
};
var readsAs = function (word, token, lang, first) {
if (!word) return false;
if (word === token) return true;
if (has(NO_BREAKS, lang)) {
if (cpLen(token) < 2) return false;
return (first ? word.startsWith(token) : word.endsWith(token)) && word.length > token.length;
}
if (first) return gluedStems(word, lang).indexOf(token) >= 0;
if (lang === 'ko') return /\p{Script=Hangul}/u.test(token) && endsWithStem(word, token, 2);
if (has(COMPOUNDS, lang)) return endsWithStem(word, token, 3);
return false;
};
return function (name) {
var n = String(name == null ? '' : name).trim();
if (!n) return false;
var whole = readName(n), stripped = readName(stripAgg(n));
for (var lang in WORDS) {
var first = has(HEAD_INITIAL, lang), reading = first ? stripped : whole;
for (var t = 0; t < WORDS[lang].length; t++) {
var token = WORDS[lang][t];
var plain = has(UNFOLDED, token) || lang === 'vi';
var words = plain ? reading.words : reading.folded;
if (words.length === 0) continue;
var tok = plain ? lowerNfc(token) : readName(token).folded.join(' ');
if (readsAs(first ? words[0] : words[words.length - 1], tok, lang, first)) return true;
}
}
return false;
};
})();
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;
};
// @requires llmText
d3.llmGeoZoom = function (svg, opts) {
var TYPE_FLOOR = 10;   // the minimum readable type, px: the hint and the pad glyphs draw no smaller
opts = opts || {};
if (!svg || typeof svg.append !== 'function') return null;
var still = function () {
return { layer: svg, still: true, group: function () { return svg.append('g'); },
reset: function () {}, step: function () {} };
};
if (typeof d3.zoom !== 'function' || typeof d3.zoomIdentity === 'undefined') return still();

var w = +opts.width, h = +opts.height;
var ox = +opts.originX || 0, oy = +opts.originY || 0;
if (!(w > 0) || !(h > 0)) return still();
var maxScale = +opts.maxScale > 1 ? +opts.maxScale : 8;
var fg = opts.themeFg || '#333';
var fs = Math.max(TYPE_FLOOR, +opts.fontSize > 0 ? +opts.fontSize : 11);
var coop = opts.cooperative === false ? false : true;
var onZoom = typeof opts.onZoom === 'function' ? opts.onZoom : null;
var hintText = opts.hintText || d3.llmText('d3.zoom.hint_pan', 'Use Ctrl (Cmd) + scroll to zoom, or drag to pan');

var clipId = 'llmzoomclip-' + Math.abs(((w * 131 + h * 17 + ox * 7 + oy) | 0));
svg.append('defs').append('clipPath').attr('id', clipId).append('rect')
.attr('x', ox).attr('y', oy).attr('width', w).attr('height', h);

var viewport = svg.append('g').attr('clip-path', 'url(#' + clipId + ')');
viewport.append('rect').attr('class', 'llm-zoom-surface')
.attr('x', ox).attr('y', oy).attr('width', w).attr('height', h)
.attr('fill', 'transparent');
var layer = viewport.append('g');

var groups = [];
function group(gopts) {
var g = layer.append('g');
groups.push({ g: g, o: gopts || {} });
return g;
}
function scaleGroups(k) {
if (!(k > 0)) return;
for (var gi = 0; gi < groups.length; gi++) {
var ge = groups[gi], go = ge.o;
try {
if (+go.stroke > 0) ge.g.selectAll('path:not([data-llm-edge])').attr('stroke-width', +go.stroke / k);
if (+go.dotStroke > 0) ge.g.selectAll('circle').each(dotScaler(+go.dotStroke, k));
} catch (e) { /* a border width is never worth breaking the chart for */ }
}
}
function dotScaler(dotStroke, k) {
return function () {
if (this.__llmBaseR == null) this.__llmBaseR = parseFloat(this.getAttribute('r'));
if (isFinite(this.__llmBaseR)) this.setAttribute('r', this.__llmBaseR / k);
this.setAttribute('stroke-width', dotStroke / k);
};
}

var ctrl = null;

var PAD_BTN = Math.max(15, Math.min(22, Math.round(fs * 1.7)));
var PAD_GAP = 2, PAD_W = PAD_BTN * 3 + PAD_GAP * 2;
var padX = ox + w - PAD_W - 6, padY = oy + 6;
var pad = null, panBtns = [];
if (w >= PAD_W + fs * 8 && h >= PAD_BTN * 3 + PAD_GAP * 2 + 16) {
pad = svg.append('g').attr('class', 'llm-zoom-pad');
var CELLS = [
[0, 0, 'in', '+'], [1, 0, 'up', '\u2191'], [2, 0, 'out', '\u2212'],
[0, 1, 'left', '\u2190'], [1, 1, 'reset', '\u27F2'], [2, 1, 'right', '\u2192'],
[1, 2, 'down', '\u2193']
];
for (var ci = 0; ci < CELLS.length; ci++) addPadButton(CELLS[ci]);
}
function addPadButton(cell) {
{
var bx = padX + cell[0] * (PAD_BTN + PAD_GAP);
var by = padY + cell[1] * (PAD_BTN + PAD_GAP);
var g = pad.append('g').attr('class', 'llm-zoom-btn lch-control').style('cursor', 'pointer')
.attr('aria-label', { 'in': d3.llmText('d3.zoom.in', 'Zoom in'), out: d3.llmText('d3.zoom.out', 'Zoom out'), reset: d3.llmText('d3.zoom.reset_view', 'Reset the view'), up: d3.llmText('d3.zoom.pan_up', 'Pan up'), down: d3.llmText('d3.zoom.pan_down', 'Pan down'), left: d3.llmText('d3.zoom.pan_left', 'Pan left'), right: d3.llmText('d3.zoom.pan_right', 'Pan right') }[cell[2]] || String(cell[2]));
g.append('rect').attr('x', bx).attr('y', by).attr('rx', 3)
.attr('width', PAD_BTN).attr('height', PAD_BTN)
.attr('fill', opts.backgroundColor || '#fff').attr('fill-opacity', 0.85)
.attr('stroke', fg).attr('stroke-opacity', 0.35);
g.append('text').attr('x', bx + PAD_BTN / 2).attr('y', by + PAD_BTN / 2)
.attr('text-anchor', 'middle').attr('dominant-baseline', 'central')
.attr('font-size', Math.max(TYPE_FLOOR, PAD_BTN - 6)).attr('fill', fg)
.style('pointer-events', 'none').text(cell[3]);
g.on('click', function (event) {
if (event && typeof event.stopPropagation === 'function') event.stopPropagation();
llmZoomStep(cell[2]);
});
if (cell[2] === 'reset') { ctrl = g; g.style('opacity', 0.35); panBtns.push(g); }
else if (cell[2] !== 'in' && cell[2] !== 'out') { g.style('opacity', 0.35); panBtns.push(g); }
}
}

var hint = svg.append('g').style('display', 'none').style('pointer-events', 'none');
hint.append('rect').attr('x', ox + w / 2 - fs * 12).attr('y', oy + h / 2 - fs).attr('rx', 4)
.attr('width', fs * 24).attr('height', fs * 2)
.attr('fill', fg).attr('fill-opacity', 0.72);
hint.append('text').attr('x', ox + w / 2).attr('y', oy + h / 2 + fs * 0.4)
.attr('text-anchor', 'middle').attr('font-size', fs)
.attr('fill', opts.backgroundColor || '#fff').text(hintText);

var hintFitted = false;
function fitHint(cx, cy, frameW, f) {
var t = hint.select('text'), r = hint.select('rect'), words = String(t.text() || '');
function tw(s) { t.text(s); var v = 0; try { v = t.node().getComputedTextLength(); } catch (eM) { v = 0; } return v > 0 ? v : s.length * f * 0.6; }
var maxW = Math.max(f * 6, frameW - f * 3), parts = /\s/.test(words.trim()) ? words.trim().split(/\s+/) : Array.from(words), sep = /\s/.test(words.trim()) ? ' ' : '';
var lines = [], cur = '';
parts.forEach(function (wd) {
var nx = cur ? cur + sep + wd : wd;
if (cur && tw(nx) > maxW) { lines.push(cur); cur = wd; } else cur = nx;
});
if (cur) lines.push(cur);
var widest = 0;
lines.forEach(function (ln) { widest = Math.max(widest, tw(ln)); });
var lh = f * 1.25, boxW = Math.min(frameW - f, widest + f * 1.6), boxH = lines.length * lh + f * 0.75;
t.text(null);
lines.forEach(function (ln, i) {
t.append('tspan').attr('x', cx).attr('y', cy - (lines.length - 1) * lh / 2 + i * lh + f * 0.4).text(ln);
});
r.attr('x', cx - boxW / 2).attr('y', cy - boxH / 2).attr('width', boxW).attr('height', boxH);
}
var hintTimer = null;
function showHint() {
try {
hint.raise().style('display', null).style('opacity', 1);
if (!hintFitted) { hintFitted = true; fitHint(ox + w / 2, oy + h / 2, w, fs); }
if (hintTimer) clearTimeout(hintTimer);
hintTimer = setTimeout(function () { hint.style('display', 'none'); }, 1500);
} catch (e) { /* a hint is never worth breaking the chart for */ }
}

function filt(event) {
if (!event) return false;
if (event.type === 'wheel') {
if (!coop || event.ctrlKey || event.metaKey) return true;
showHint();
return false;
}
if (event.touches) {
if (!coop) return true;
if (event.touches.length < 2) { showHint(); return false; }
return true;
}
if (event.type === 'dblclick') return true;
return !event.button;                       // primary-button drag pans
}

var adopted = false, adoptedBaseR = null;
function adopt() {
if (adopted) return;
adopted = true;
try {
var layerNode = layer.node(), svgNode = svg.node();
if (!layerNode || !svgNode) return;
if (layerNode.childNodes.length) return;          // drawn correctly - nothing to do
var kids = [].slice.call(svgNode.childNodes), moved = 0;
for (var i = 0; i < kids.length; i++) {
var n = kids[i];
if (n.nodeType !== 1 || !n.querySelector) continue;
if (n === viewport.node() || n === hint.node()) continue;
if (ctrl && n === ctrl.node()) continue;
if (pad && n === pad.node()) continue;
if (n.tagName === 'defs' || n.tagName === 'title') continue;
var isFurniture = (n.classList && n.classList.contains('d3-legend-mark'))
|| n.querySelector('.d3-legend-mark');
if (isFurniture) continue;
var holdsMap = n.tagName === 'path'
|| (n.classList && n.classList.contains('d3-mark'))
|| n.querySelector('.d3-mark')
|| (n.tagName === 'g' && n.querySelector('path'));
if (!holdsMap) continue;
layerNode.appendChild(n);                        // document order is preserved
moved++;
}
if (!moved) return;
adoptedBaseR = [];
var ms = layerNode.querySelectorAll('.d3-mark');
for (var j = 0; j < ms.length; j++) {
var r = parseFloat(ms[j].getAttribute('r'));
if (isFinite(r)) adoptedBaseR.push([ms[j], r, parseFloat(ms[j].getAttribute('stroke-width')) || 0]);
}
} catch (e) { /* a heal is never worth breaking the chart for */ }
}

var textBase = null;
function scaleLayerText(k) {
if (!(k > 0)) return;
try {
var layerNode = layer.node();
if (!layerNode) return;
var ts = layerNode.querySelectorAll('text');
if (textBase === null || textBase.length !== ts.length) {
textBase = [];
for (var i = 0; i < ts.length; i++) {
var cs = null;
try { cs = window.getComputedStyle(ts[i]).fontSize; } catch (e) { cs = null; }
var px = parseFloat(ts[i].getAttribute('font-size'));
if (!isFinite(px)) px = parseFloat(cs);
textBase.push(isFinite(px) && px > 0 ? px : 0);
}
}
for (var j = 0; j < ts.length; j++) {
if (textBase[j] > 0) ts[j].setAttribute('font-size', (textBase[j] / k).toFixed(2));
}
} catch (e) { /* a label size is never worth breaking the chart for */ }
}

function scaleAdopted(k) {
if (!adoptedBaseR || !(k > 0)) return;
for (var i = 0; i < adoptedBaseR.length; i++) {
var e = adoptedBaseR[i];
e[0].setAttribute('r', e[1] / k);
if (e[2]) e[0].setAttribute('stroke-width', e[2] / k);
}
}

var zoom = d3.zoom()
.wheelDelta(function (event) {
return -event.deltaY * (event.deltaMode === 1 ? 0.05 : event.deltaMode ? 1 : 0.002);
})
.scaleExtent([1, maxScale])
.extent([[0, 0], [w, h]])
.translateExtent([[0, 0], [w, h]])
.clickDistance(4)
.filter(filt)
.on('zoom', function (event) {
var t = event && event.transform ? event.transform : d3.zoomIdentity;
adopt();                       // no-op when the chart drew into the layer as intended
layer.attr('transform', t.toString());
scaleAdopted(t.k);
scaleLayerText(t.k);
scaleGroups(t.k);
if (onZoom) { try { onZoom(t); } catch (e) { /* never break the render */ } }
try {
if (ctrl) ctrl.style('opacity', t.k > 1.001 ? 1 : 0.35);
for (var pi = 0; pi < panBtns.length; pi++) panBtns[pi].style('opacity', t.k > 1.001 ? 1 : 0.35);
if (pad) pad.raise();
} catch (e) { /* ignore */ }
});

try { viewport.call(zoom); } catch (e) { if (pad) pad.remove(); return { layer: layer, group: group, reset: function () {}, step: function () {} }; }

function reset() {
try { viewport.call(zoom.transform, d3.zoomIdentity); } catch (e) { /* ignore */ }
}

function llmZoomStep(dir) {
try {
if (dir === 'reset') { reset(); return; }
if (dir === 'in') { viewport.call(zoom.scaleBy, 1.6); return; }
if (dir === 'out') { viewport.call(zoom.scaleBy, 1 / 1.6); return; }
var t = d3.zoomTransform(viewport.node());
var k = t && t.k > 0 ? t.k : 1;
var dx = (w * 0.18) / k, dy = (h * 0.18) / k;
if (dir === 'left') viewport.call(zoom.translateBy, dx, 0);
else if (dir === 'right') viewport.call(zoom.translateBy, -dx, 0);
else if (dir === 'up') viewport.call(zoom.translateBy, 0, dy);
else if (dir === 'down') viewport.call(zoom.translateBy, 0, -dy);
} catch (e) { /* a control is never worth breaking the chart for */ }
}

return { layer: layer, group: group, reset: reset, zoom: zoom, viewport: viewport, pad: pad, step: llmZoomStep };
};
// @requires llmText
d3.llmGeoPointNotes = function (geoPoint, opts) {
opts = opts || {};
var gp = geoPoint || null;
var unit = opts.unit === 'row' ? 'row' : 'point';
var offMap = +opts.offMap || 0;
var missing = gp ? Math.max(offMap - (gp.ambiguousRows || 0), gp.unplaced || 0) : offMap;
var missingText = unit === 'row'
? d3.llmText('d3.geonotes.rows_off_map', missing === 1 ? '{count} row off-map' : '{count} rows off-map', { count: missing }, missing)
: d3.llmText('d3.geonotes.points_off_map', missing === 1 ? '{count} point off-map' : '{count} points off-map', { count: missing }, missing);

var coarse = null;
if (gp && gp.precisionCounts) {
var pc = gp.precisionCounts, nZip = pc.zip3 || 0, nSt = pc.state || 0, nCty = pc.country || 0;
var nCoarse = nZip + nSt + nCty, nPlaced = (pc.latlon || 0) + (pc.city || 0) + nCoarse;
if (nCoarse > 0) {
var tierTxt = (nCty >= nSt && nCty >= nZip) ? d3.llmText('d3.geonotes.tier_country', 'the largest city in each country')
: (nSt >= nZip ? d3.llmText('d3.geonotes.tier_state', 'state centers') : d3.llmText('d3.geonotes.tier_zip3', 'ZIP-prefix centers'));
coarse = nCoarse === nPlaced
? (unit === 'row' ? d3.llmText('d3.geonotes.coarse_all_rows', 'no exact location for any row; using {tier}', { tier: tierTxt })
: d3.llmText('d3.geonotes.coarse_all_points', 'no exact location for any point; using {tier}', { tier: tierTxt }))
: (unit === 'row' ? d3.llmText('d3.geonotes.coarse_some_rows', '{coarse} of {placed} rows have no exact location; using {tier}', { coarse: nCoarse, placed: nPlaced, tier: tierTxt })
: d3.llmText('d3.geonotes.coarse_some', '{coarse} of {placed} have no exact location; using {tier}', { coarse: nCoarse, placed: nPlaced, tier: tierTxt }));
}
} else if (gp && (gp.precision === 'zip3' || gp.precision === 'state' || gp.precision === 'country')) {
coarse = d3.llmText('d3.geonotes.coarse_ceiling', 'no exact location; using {tier}', { tier: gp.precision === 'zip3' ? d3.llmText('d3.geonotes.tier_zip3', 'ZIP-prefix centers')
: gp.precision === 'country' ? d3.llmText('d3.geonotes.tier_country', 'the largest city in each country') : d3.llmText('d3.geonotes.tier_state', 'state centers') });
}

var ambiguous = null;
if (gp && gp.ambiguousRows > 0) {
var ambEx = (gp.ambiguousExamples || []).slice(0, 3).join(', ');
ambiguous = ambEx
? d3.llmText('d3.geonotes.ambiguous_examples', gp.ambiguousRows === 1 ? '{count} row not shown: place name matches several cities ({examples}); add a Country (or State) field to tell them apart'
: '{count} rows not shown: place names match several cities ({examples}); add a Country (or State) field to tell them apart', { count: gp.ambiguousRows, examples: ambEx }, gp.ambiguousRows)
: d3.llmText('d3.geonotes.ambiguous', gp.ambiguousRows === 1 ? '{count} row not shown: place name matches several cities; add a Country (or State) field to tell them apart'
: '{count} rows not shown: place names match several cities; add a Country (or State) field to tell them apart', { count: gp.ambiguousRows }, gp.ambiguousRows);
}

var rolesRefused = (gp && gp.rolesRefused && gp.rolesRefused.length)
? d3.llmText('d3.geonotes.role_refused', 'a column named for place lookup was not usable; positions resolved without it') : null;

return { missing: missing, missingText: missingText, coarse: coarse, counted: !!(gp && gp.precisionCounts),
ambiguous: ambiguous, rolesRefused: rolesRefused };
};
d3.llmGeoMarks = function (layer, opts) {
opts = opts || {};
var options = opts.options || {};
var pts = opts.points || [];
var rad = typeof opts.radius === 'function' ? opts.radius : function () { return 4; };
var fill = typeof opts.fill === 'function' ? opts.fill : function () { return '#3182bd'; };
var stroke = opts.stroke || '#333';
var sw = +opts.strokeWidth > 0 ? +opts.strokeWidth : 0.6;
var fo = opts.fillOpacity != null ? +opts.fillOpacity : 0.75;
var precByIdx = null;
var d = opts.data;
if (d && d.columns && d.rows) {
var pCol = -1, iCol = -1;
for (var ci = 0; ci < d.columns.length; ci++) {
var nm = d.columns[ci] && d.columns[ci].name;
if (nm === '__geoPrecision__') pCol = ci;
if (nm === '__rowIdx__') iCol = ci;
}
if (pCol >= 0 && iCol >= 0) {
precByIdx = new Map();
for (var ri = 0; ri < d.rows.length; ri++) {
var rw = d.rows[ri];
if (rw && rw[iCol] != null && rw[pCol] != null) precByIdx.set(rw[iCol], rw[pCol]);
}
}
}
var TIER_RANK = { latlon: 0, city: 1, zip3: 2, state: 3, country: 4 };
function tierOfIdx(k) {
if (precByIdx.has(k)) return precByIdx.get(k);
var s = String(k).trim(), n = +s;
if (s !== '' && isFinite(n) && precByIdx.has(n)) return precByIdx.get(n);
return precByIdx.has(s) ? precByIdx.get(s) : null;
}
var precOf = typeof opts.precision === 'function' ? opts.precision
: function (p) {
if (p.prec != null) return p.prec;
if (!precByIdx || p.idx == null) return null;
var ks = Array.isArray(p.idx) ? p.idx
: (typeof p.idx === 'string' && p.idx.indexOf(',') >= 0 ? p.idx.split(',') : [p.idx]);
var worst = null;
for (var ki = 0; ki < ks.length; ki++) {
var t = tierOfIdx(ks[ki]);
if (t != null && (worst == null || (TIER_RANK[t] || 0) > (TIER_RANK[worst] || 0))) worst = t;
}
return worst;
};
var idxOf = typeof opts.rowIdx === 'function' ? opts.rowIdx : function (p) { return p.idx; };

function isApprox(p) {
var t = precOf(p);
return !!t && t !== 'latlon' && t !== 'city';
}
var mode = options.approximatePositions === 'skip' ? 'skip'
: options.approximatePositions === 'aggregate' ? 'aggregate' : 'mark';

var bySize = function (a, b) { return rad(b) - rad(a); };
var exactPts = pts.filter(function (p) { return !isApprox(p); }).sort(bySize);
var approxPts = pts.filter(isApprox);
var approxAsCircles = exactPts.length === 0 && approxPts.length > 0 && mode !== 'skip';
var nExact = exactPts.length, nApprox = approxPts.length;
var aggregated = 0;
if (mode === 'skip') {
approxPts = [];
} else if (mode === 'aggregate') {
var byAnchor = new Map();
for (var i = 0; i < approxPts.length; i++) {
var p = approxPts[i];
var key = Math.round(p.x) + ',' + Math.round(p.y);
var e = byAnchor.get(key);
if (!e) {
byAnchor.set(key, { x: p.x, y: p.y, size: p.size, cval: p.cval, cat: p.cat,
label: p.label, prec: precOf(p), idx: idxOf(p), rowIdxs: [idxOf(p)], n: 1,
members: [p] });
} else {
e.size += p.size; e.rowIdxs.push(idxOf(p)); e.n++; e.members.push(p);
if (e.label !== p.label) e.label = null;
}
}
approxPts = Array.from(byAnchor.values());
aggregated = approxPts.filter(function (p) { return p.n > 1; }).length;
}
approxPts.sort(bySize);
if (approxAsCircles) {
exactPts = exactPts.concat(approxPts).sort(bySize);
approxPts = [];
}

var circles = layer.append('g').selectAll('circle').data(exactPts).join('circle')
.attr('class', 'd3-mark')
.attr('cx', function (p) { return p.x; })
.attr('cy', function (p) { return p.y; })
.attr('r', function (p) { return rad(p); })
.attr('fill', function (p) { return fill(p); }).attr('fill-opacity', fo)
.attr('stroke', stroke).attr('stroke-width', sw)
.attr('data-row-idx', function (p) { return p.rowIdxs ? p.rowIdxs.join(',') : idxOf(p); });

var squares = layer.append('g').selectAll('rect').data(approxPts).join('rect')
.attr('class', 'd3-mark')
.attr('x', function (p) { return p.x - rad(p); })
.attr('y', function (p) { return p.y - rad(p); })
.attr('width', function (p) { return rad(p) * 2; })
.attr('height', function (p) { return rad(p) * 2; })
.attr('fill', function (p) { return fill(p); }).attr('fill-opacity', fo)
.attr('stroke', stroke).attr('stroke-width', sw)
.attr('data-row-idx', function (p) {
return p.rowIdxs ? p.rowIdxs.join(',') : idxOf(p);
});

var framed = false, curK = 1;
var baseR = function (p) { return framed ? p.__frameR : rad(p); };

function rescale(t) {
var k = t && +t.k > 0 ? +t.k : (+t > 0 ? +t : 1);
if (!(k > 0)) k = 1;
curK = k;
if (!framed) {
circles.attr('r', function (p) { return rad(p) / k; })
.attr('stroke-width', sw / k);
squares.attr('x', function (p) { return p.x - rad(p) / k; })
.attr('y', function (p) { return p.y - rad(p) / k; })
.attr('width', function (p) { return rad(p) * 2 / k; })
.attr('height', function (p) { return rad(p) * 2 / k; })
.attr('stroke-width', sw / k);
return;
}
var rk = function (p) { var r = baseR(p); return r == null ? null : r / k; };
circles.interrupt().attr('r', rk).attr('stroke-width', sw / k);
squares.interrupt()
.attr('x', function (p) { var r = rk(p); return r == null ? null : p.x - r; })
.attr('y', function (p) { var r = rk(p); return r == null ? null : p.y - r; })
.attr('width', function (p) { var r = rk(p); return r == null ? null : r * 2; })
.attr('height', function (p) { var r = rk(p); return r == null ? null : r * 2; })
.attr('stroke-width', sw / k);
}

function frame(i, cfg) {
cfg = cfg || {};
var all = !(i >= 0);
var num = function (v) { return (v == null || v === '' || !isFinite(+v)) ? null : +v; };
var ownSize = function (q) {
return num(all ? q.sizeAll : (q.sizeByFrame ? q.sizeByFrame[i] : null));
};
var sizeAt = function (p) {
if (!p.members) return ownSize(p);
var s = null;
for (var m = 0; m < p.members.length; m++) {
var v = ownSize(p.members[m]);
if (v != null) s = (s == null ? 0 : s) + v;
}
return s;
};
var toR = typeof cfg.radius === 'function' ? cfg.radius
: function (v, p) { return rad(Object.assign({}, p, { size: v })); };
var rowsOf = function (q) {
var r = all ? q.rowsAll : (q.rowsByFrame ? q.rowsByFrame[i] : null);
return r && r.length ? r : [];
};
var rowsAt = function (p) {
if (!p.members) return rowsOf(p).join(',');
var out = [];
for (var m = 0; m < p.members.length; m++) out = out.concat(rowsOf(p.members[m]));
return out.join(',');
};
var fillAt = function (p) {
var src = p.members ? p.members[0] : p;
if (typeof cfg.fill === 'function') return cfg.fill(src, i);
var c = all ? src.fillAll : (src.fillByFrame ? src.fillByFrame[i] : null);
return c != null ? c : (cfg.noData || fill(src));
};
var every = pts.concat(exactPts.concat(approxPts).filter(function (p) { return !!p.members; }));
for (var q = 0; q < every.length; q++) {
var s = sizeAt(every[q]);
var r = s == null ? null : +toR(s, every[q]);
every[q].__frameR = (r == null || !isFinite(r) || r < 0) ? null : r;
}
framed = true;
var k = curK;
var rk = function (p) { return p.__frameR == null ? null : p.__frameR / k; };
var tween = cfg.tween, fillTween = cfg.fillTween;
if (typeof tween !== 'function' || typeof fillTween !== 'function')
throw new Error('gm.frame needs cfg.tween and cfg.fillTween: pass the shared frame helpers llmFrameTween and llmFrameFill in, as the reference chart does');
var animate = !!cfg.animate;
var ms = cfg.ms;
var desc = function (a, b) {
var ra = a.__frameR == null ? -1 : a.__frameR, rb = b.__frameR == null ? -1 : b.__frameR;
return rb - ra;
};
circles.sort(desc);
squares.sort(desc);
var circleAttrs = { r: rk };
var squareAttrs = {
x: function (p) { var v = rk(p); return v == null ? null : p.x - v; },
y: function (p) { var v = rk(p); return v == null ? null : p.y - v; },
width: function (p) { var v = rk(p); return v == null ? null : v * 2; },
height: function (p) { var v = rk(p); return v == null ? null : v * 2; }
};
tween(circles, { animate: animate, ms: ms, attrs: circleAttrs });
tween(squares, { animate: animate, ms: ms, attrs: squareAttrs });
var both = layer.selectAll('.d3-mark');
var trans = null;
if (animate && typeof both.transition === 'function') {
var dur = Math.max(120, Math.min(600, Math.round((+ms > 0 ? +ms : 1000) * 0.6)));
trans = layer.transition().duration(dur);
}
fillTween(circles, trans, fillAt, cfg.noData || null);
fillTween(squares, trans, fillAt, cfg.noData || null);
circles.attr('stroke-width', sw / k).attr('data-row-idx', rowsAt)
.attr('display', function (p) { return p.__frameR == null ? 'none' : null; });
squares.attr('stroke-width', sw / k).attr('data-row-idx', rowsAt)
.attr('display', function (p) { return p.__frameR == null ? 'none' : null; });
return { drawn: both.filter(function (p) { return p.__frameR != null; }).size() };
}

return {
marks: layer.selectAll('.d3-mark'),
rescale: rescale,
frame: frame,
radiusOf: function (p) { return baseR(p); },
circles: circles,
squares: squares,
isApprox: isApprox,
mode: mode,
exactCount: nExact,
approxCount: nApprox,
approxAsCircles: approxAsCircles,
aggregatedCount: aggregated
};
};
d3.llmWorldFit = function (proj, opts) {
opts = opts || {};
var FAR_SOUTH = -60;
var geo = (opts.geo && opts.geo.features && opts.geo.features.length) ? opts.geo : null;
var mapW = +opts.width || 0, mapH = +opts.height || 0;
var pad = isFinite(+opts.pad) && opts.pad !== null && opts.pad !== undefined ? +opts.pad : 8;
var vp = opts.viewport || [mapW, mapH];
var VW = +vp[0] || mapW, VH = +vp[1] || mapH;
var pts = (opts.points || []).filter(function (p) {
return p && p.length > 1 && p[0] !== null && p[1] !== null && isFinite(+p[0]) && isFinite(+p[1]);
});

var isFarSouth = function (f) { var b = d3.geoBounds(f); return b[1][1] < FAR_SOUTH; };
var anyFarSouth = pts.some(function (p) { return +p[1] < FAR_SOUTH; })
|| (opts.regions || []).some(function (f) { return !!f && isFarSouth(f); });
var trimSouth = !!geo && !anyFarSouth;
var sliver = trimSouth ? Math.max(8, Math.round(Math.min(VW, VH) * 0.03)) : 0;

var box = opts.box || [[pad, pad], [mapW - pad, mapH - pad]];
var x0 = box[0][0], y0 = box[0][1], x1 = box[1][0], y1 = box[1][1];
var polys = geo ? geo.features.filter(function (f) { return f.geometry && f.geometry.type !== 'Point'; }) : [];
var fitGeo = (geo && opts.fitPolygons && polys.length) ? { type: 'FeatureCollection', features: polys } : geo;
var fitTo = function (bottom) {
if (geo) proj.fitExtent([[x0, y0], [x1, bottom]], fitGeo);
else if (pts.length) proj.fitExtent(opts.pointBox || [[x0, y0], [x1, bottom]], { type: 'MultiPoint', coordinates: pts });
};
fitTo(y1);
var path = d3.geoPath(proj);

var farSouthCol = { type: 'FeatureCollection', features: polys.filter(isFarSouth) };
if (opts.refit !== false && trimSouth && farSouthCol.features.length) {
var fsB = path.bounds(farSouthCol), worldB = path.bounds(geo);
var cut = fsB[0][1] + sliver;                  // where the clip will land
var crop = Math.max(0, worldB[1][1] - cut);    // dead space this would leave
if (crop > 1) { fitTo(y1 + crop); path = d3.geoPath(proj); }
}
var aTop = opts.anchorLow;
if (trimSouth && aTop !== undefined && aTop !== null && isFinite(+aTop)) {
var vis = polys.filter(function (f) { return !isFarSouth(f); });
if (vis.length) {
var vb = path.bounds({ type: 'FeatureCollection', features: vis });
var cutA = farSouthCol.features.length ? path.bounds(farSouthCol)[0][1] + sliver : vb[1][1];
var slackTop = Math.max(0, vb[0][1] - aTop);
var slackBottom = Math.max(0, y1 - cutA);
var bottomGap = Math.max(24, Math.round((slackTop + slackBottom) * 0.3));
var dy = Math.round((mapH - bottomGap) - cutA);
if (dy > 1) {
var t = proj.translate();
proj.translate([t[0], t[1] + Math.min(dy, slackTop + slackBottom)]);
path = d3.geoPath(proj);
}
}
}
var farSouthTop = farSouthCol.features.length ? path.bounds(farSouthCol)[0][1] : Infinity;
var clipBottom = (trimSouth && isFinite(farSouthTop)) ? Math.min(mapH, farSouthTop + sliver) : mapH;
var clipTop = +opts.clipTop || 0;

var clipId = 'llmgeoclip-' + Math.abs((VW * 131 + VH) | 0);
var defineClip = function (svg) {
svg.append('defs').append('clipPath').attr('id', clipId).append('rect')
.attr('x', 0).attr('y', clipTop).attr('width', mapW).attr('height', Math.max(1, clipBottom - clipTop));
};
var basemap = function (svg, layer, plain) {
if (!geo || !svg || !layer) return null;
defineClip(svg);
var g = layer.append('g');
if (plain) return g.attr('clip-path', 'url(#' + clipId + ')');
return g.attr('class', 'llm-basemap').attr('clip-path', 'url(#' + clipId + ')')
.style('pointer-events', 'none');
};
var clip = function (svg, g) {
if (!geo || !svg || !g) return g;
defineClip(svg);
return g.attr('clip-path', 'url(#' + clipId + ')');
};

return { path: path, projection: proj, trimSouth: trimSouth, clipBottom: clipBottom, clipTop: clipTop,
sliver: sliver, farSouth: FAR_SOUTH, basemap: basemap, clip: clip };
};
// @requires llmText
d3.llmFilterScope = function (options) {
var f = options && options.filterScope;
var vals = [];
if (f && typeof f === 'object' && f.values && typeof f.values.length === 'number' && typeof f.values !== 'string') {
for (var i = 0; i < f.values.length; i++) {
var v = f.values[i];
if (v !== null && v !== undefined && String(v).trim() !== '' && vals.indexOf(String(v)) < 0) vals.push(String(v));
}
}
var label = '';
if (f && typeof f === 'object' && typeof f.label === 'string' && f.label.trim()) label = f.label.trim();
else if (vals.length === 1) label = d3.llmText('d3.filterscope.only', '{value} only', { value: vals[0] });
else if (vals.length === 2) label = d3.llmText('d3.segments.and', '{first} and {second}', { first: vals[0], second: vals[1] });
else if (vals.length > 2) label = d3.llmText('d3.filterscope.and_more', '{first} and {count} more', { first: vals[0], count: vals.length - 1 }, vals.length - 1);
var narrowed = label !== '';
return {
narrowed: narrowed,
label: label,
field: f && typeof f === 'object' && typeof f.field === 'string' ? f.field : '',
values: vals,
title: function (name) { return narrowed ? String(name) + ' \u00b7 ' + label : String(name); },
baseline: function (key, compute) {
var mem = null;
try { mem = d3.__lchBaselines || (d3.__lchBaselines = {}); } catch (e) { mem = {}; }
var k = String(key);
if (!narrowed) {
var v = typeof compute === 'function' ? compute() : compute;
if (typeof v === 'number' && isFinite(v)) mem[k] = v;
return { value: v, cohort: 'all' };
}
if (Object.prototype.hasOwnProperty.call(mem, k)) return { value: mem[k], cohort: 'all' };
return { value: typeof compute === 'function' ? compute() : compute, cohort: 'shown' };
},
domain: function (key, values) {
var mem = null;
try { mem = d3.__lchBaselines || (d3.__lchBaselines = {}); } catch (e) { mem = {}; }
var k = 'domain:' + String(key), shown = [];
for (var i = 0; values && i < values.length; i++) {
var n = values[i];
if (n !== null && n !== undefined && n !== '' && typeof n !== 'boolean' && isFinite(+n)) shown.push(+n);
}
var out = function (v, cohort) {
var lo = null, hi = null;
for (var j = 0; j < v.length; j++) { if (lo === null || v[j] < lo) lo = v[j]; if (hi === null || v[j] > hi) hi = v[j]; }
return { values: v, lo: lo, hi: hi, cohort: cohort };
};
if (!narrowed) {
if (shown.length) mem[k] = shown.slice();
return out(shown, 'all');
}
var kept = Object.prototype.hasOwnProperty.call(mem, k) ? mem[k] : null;
if (kept && typeof kept.length === 'number' && kept.length) {
var full = out(kept, 'all'), wide = kept.slice();
for (var w = 0; w < shown.length; w++) if (shown[w] < full.lo || shown[w] > full.hi) wide.push(shown[w]);
return out(wide, 'all');
}
return out(shown, 'shown');
},
track: function (key, kind, values, reference) {
var mem = null;
try { mem = d3.__lchBaselines || (d3.__lchBaselines = {}); } catch (e) { mem = {}; }
var kd = kind === 'span' || kind === 'range' ? kind : 'top';
var k = 'track:' + kd + ':' + String(key), ref = +reference, lo = null, hi = null, wide = null;
if (kd === 'span' && !isFinite(ref)) ref = 0;
for (var i = 0; values && i < values.length; i++) {
var n = values[i];
if (n === null || n === undefined || n === '' || typeof n === 'boolean' || !isFinite(+n)) continue;
n = kd === 'span' ? Math.abs(+n - ref) : +n;
if (lo === null || n < lo) lo = n;
if (hi === null || n > hi) hi = n;
}
var shown = kd === 'range' ? (lo === null ? null : [lo, hi]) : (hi || 1);
var kept = Object.prototype.hasOwnProperty.call(mem, k) ? mem[k] : null, cohort = 'all', widened = false;
if (!narrowed) {
if (shown !== null) mem[k] = kd === 'range' ? shown.slice() : shown;
wide = shown;
} else if (kd === 'range' ? kept && kept.length === 2 : typeof kept === 'number' && isFinite(kept)) {
if (kd === 'range') {
wide = kept.slice();
if (shown !== null && shown[0] < wide[0]) { wide[0] = shown[0]; widened = true; }
if (shown !== null && shown[1] > wide[1]) { wide[1] = shown[1]; widened = true; }
} else {
wide = kept;
if (shown > kept) { wide = shown; widened = true; }
}
} else {
wide = shown;
cohort = 'shown';
}
if (kd === 'top') return { domain: [0, wide], lo: 0, hi: wide, value: wide, cohort: cohort, widened: widened };
if (kd === 'span') return { domain: [-wide, wide], lo: -wide, hi: wide, value: wide, cohort: cohort, widened: widened };
if (wide === null) return { domain: [0, 1], lo: null, hi: null, value: null, cohort: cohort, widened: widened };
var pad = wide[1] > wide[0] ? 0 : (Math.abs(wide[0]) * 0.01 || 0.01);
return { domain: [wide[0] - pad, wide[1] + pad], lo: wide[0], hi: wide[1], value: null, cohort: cohort, widened: widened };
},
among: function (text) { return narrowed ? String(text) + ' (' + label + ')' : String(text); }
};
};
d3.llmFilterScope.reference = function (field, values) {
var w = String(field == null ? '' : field).replace(/YoY|MoM|QoQ|WoW/g, function (m) { return ' ' + m.toLowerCase() + ' '; })
.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ');
if (/\b(growth|yoy|mom|qoq|wow|change|gap|variance|delta)\b/i.test(w)) return { value: 0, kind: 'zero' };
if (!/\b(attainment|achievement|of (target|plan|quota|budget|goal)|vs\.? (target|plan|quota|budget|goal)|to (target|plan|quota|goal))\b/i.test(w)) return null;
var v = [];
for (var i = 0; values && i < values.length; i++) { var n = values[i]; if (n !== null && n !== undefined && n !== '' && isFinite(+n)) v.push(+n); }
for (var k = 0; k < v.length; k++) if (v[k] < 0) return { value: 0, kind: 'zero' };
v.sort(function (a, b) { return a - b; });
var md = v.length ? (v.length % 2 ? v[(v.length - 1) / 2] : (v[v.length / 2 - 1] + v[v.length / 2]) / 2) : 1;
return { value: md < 10 ? 1 : 100, kind: 'goal' };
};
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) {
  container.replaceChildren();
  const { columns, rows } = data;
  const W = options.width, H = options.height;
  const TF = options.themeFg || 'currentColor';
  const CF = Math.max(10, Math.min(14, Math.round(Math.min(W, H) / 55)));
  const SUB = Math.max(10, CF - 1);
  const svg = d3.select(container).append('svg').attr('width', W).attr('height', H);
  const fmt = new Intl.NumberFormat(options.cultureCode, { maximumFractionDigits: 2 });
  const col = n => columns.findIndex(c => c.name === n);
  const sizeIdx = col('Orders'), catIdx = col('CityTier');
  if (sizeIdx < 0) throw new Error('INVALID:column "Orders" not found');
  if (catIdx < 0) throw new Error('INVALID:column "CityTier" not found');
  const cityIdx = col('City'), ctryIdx = col('Country'), regIdx = col('Region'), codeIdx = col('CountryCode');
  const revIdx = col('Revenue'), aovIdx = col('AvgOrderValue');
  const idxIdx = col('__rowIdx__');
  let latIdx = col('__geoLat__'), lonIdx = col('__geoLon__');
  if (latIdx < 0 || lonIdx < 0) {
    latIdx = columns.findIndex(c => d3.llmValueColumn.nameWords(c.name).some(t => t === 'lat' || t === 'latitude'));
    lonIdx = columns.findIndex(c => d3.llmValueColumn.nameWords(c.name).some(t => t === 'lon' || t === 'lng' || t === 'long' || t === 'longitude'));
  }
  if (latIdx < 0 || lonIdx < 0) throw new Error('INVALID:column "__geoLat__" not found');
  const emptyMsg = (typeof options.noDataText === 'string' && options.noDataText) ? options.noDataText : 'No data to display';
  const showEmpty = () => svg.append('text').attr('x', W / 2).attr('y', H / 2).attr('text-anchor', 'middle')
    .attr('font-size', CF).attr('fill', TF).text(emptyMsg);
  if (!rows.length) { showEmpty(); return; }

  const pts = []; let offMap = 0, noSize = 0;
  rows.forEach((r, i) => {
    const rla = r[latIdx], rlo = r[lonIdx];
    if (rla == null || rla === '' || rlo == null || rlo === '') { offMap++; return; }
    const la = +rla, lo = +rlo;
    if (!isFinite(la) || !isFinite(lo) || la < -90 || la > 90 || lo < -180 || lo > 180) { offMap++; return; }
    const sRaw = r[sizeIdx];
    const blank = sRaw == null || sRaw === '' || !isFinite(+sRaw);
    if (blank) noSize++;
    const num = j => (j >= 0 && r[j] != null && r[j] !== '' && isFinite(+r[j])) ? +r[j] : null;
    pts.push({ la, lo, size: blank ? null : +sRaw,
      label: cityIdx >= 0 ? r[cityIdx] : null,
      country: ctryIdx >= 0 ? r[ctryIdx] : null, region: regIdx >= 0 ? r[regIdx] : null,
      code: codeIdx >= 0 ? r[codeIdx] : null,
      rev: num(revIdx), aov: num(aovIdx),
      cat: r[catIdx] == null ? '(blank)' : String(r[catIdx]),
      idx: idxIdx >= 0 ? r[idxIdx] : i,
      prec: col('__geoPrecision__') >= 0 ? r[col('__geoPrecision__')] : null });
  });
  if (!pts.length) { showEmpty(); return; }

  const T = d3.llmThemeColors(options);
  const catsAll = [...new Set(pts.map(p => p.cat))];
  const ranked = catsAll.slice().sort((a, b) => (d3.sum(pts.filter(p => p.cat === b), p => p.size || 0)) - (d3.sum(pts.filter(p => p.cat === a), p => p.size || 0)));
  const colorOf = T.categories(catsAll);
  const fill = p => T.legible(colorOf(p.cat));

  const PANEL_GAP = 12;
  const PANEL_W = W >= 500 ? Math.min(Math.round(W * 0.22), 170) : 0;
  const mapW = W - (PANEL_W ? PANEL_W + PANEL_GAP : 0);

  // Narrow layout: legend + size key in a band under the plot
  let bandLayout = null, bandH = 0;
  const legCats = ranked.slice(0, 8);
  if (!PANEL_W) {
    const rowH = CF + 5;
    const rowsL = [[]]; let xx = 8;
    legCats.forEach(c => {
      const w = 14 + String(c).length * SUB * 0.58 + 10;
      if (xx + w > W - 8 && rowsL[rowsL.length - 1].length) { rowsL.push([]); xx = 8; }
      rowsL[rowsL.length - 1].push({ c, x: xx, w }); xx += w;
    });
    const showLeg = ranked.length >= 2;
    const legH = showLeg ? rowsL.length * rowH : 0;
    const sizeH = 2 * 12 + 4;
    bandH = Math.min(Math.round(H * 0.45), 8 + legH + sizeH + 4);
    bandLayout = { rowsL, rowH, showLeg, legH };
  }
  const mapH = H - bandH;

  let zoomRescale = null;
  const z = d3.llmGeoZoom(svg, { width: mapW, height: mapH, themeFg: TF, backgroundColor: options.backgroundColor,
    fontSize: CF, maxScale: 8, onZoom: t => { if (zoomRescale) zoomRescale(t); } });
  const mapLayer = z ? z.layer : svg;

  const geo = options.geo && options.geo.features && options.geo.features.length ? options.geo : null;
  const proj = d3.geoNaturalEarth1();
  const wf = d3.llmWorldFit(proj, { geo: geo, points: pts.map(p => [p.lo, p.la]), width: mapW, height: mapH,
    viewport: [W, H], box: [[6, 22], [mapW - 6, mapH - 6]], pointBox: [[30, 30], [mapW - 30, mapH - 16]], anchorLow: 20 });
  const land = options.geoLandColor || '#e6e6e6';
  if (geo) {
    wf.basemap(svg, mapLayer, true).selectAll('path').data(geo.features).join('path')
      .attr('d', wf.path).attr('fill', land)
      .attr('stroke', options.backgroundColor || options.themeBg || '#fff').attr('stroke-width', 0.6);
  }

  const placed = [];
  for (const p of pts) {
    const xy = proj([p.lo, p.la]);
    if (xy && isFinite(xy[0])) { p.x = xy[0]; p.y = xy[1]; placed.push(p); } else offMap++;
  }
  const mapCap = options.maxMapPoints > 0 ? options.maxMapPoints : 2000;
  let dropped = 0;
  if (placed.length > mapCap) {
    placed.sort((a, b) => (b.size == null ? -1 : b.size) - (a.size == null ? -1 : a.size));
    dropped = placed.length - mapCap; placed.length = mapCap;
  }
  placed.sort((a, b) => (b.size == null ? -1 : b.size) - (a.size == null ? -1 : a.size));

  const rmax = Math.max(6, Math.min(bandLayout ? 12 : 26, Math.min(mapW, mapH) / 18));
  const scope = d3.llmFilterScope(options);
  const smax = scope.domain('size:' + sizeIdx, placed.map(p => p.size)).hi || 1;
  const rad = d3.scaleSqrt().domain([0, smax]).range([2.5, rmax]);
  const onLand = d3.llmThemeColors(Object.assign({}, options, { backgroundColor: land, themeBg: land }));

  const gm = d3.llmGeoMarks(mapLayer, {
    points: placed, data: data, options: options,
    radius: p => (p.size == null ? rad.range()[0] : rad(p.size)),
    fill: p => (p.size == null ? 'none' : fill(p)),
    stroke: p => (p.size == null ? onLand.legible(fill(p)) : '#333'), strokeWidth: 0.8, fillOpacity: 0.75
  });
  zoomRescale = gm.rescale;
  if (options.allowTooltips !== false) {
    gm.marks.append('title').text(p => {
      const lines = [];
      lines.push((p.label != null ? String(p.label) : 'Place') + (p.country != null ? ' - ' + p.country + (p.region != null ? ' (' + p.region + ')' : '') : ''));
      lines.push('Orders: ' + (p.size == null ? 'no value' : fmt.format(p.size)));
      lines.push('City tier: ' + p.cat);
      if (p.rev != null) lines.push('Revenue: ' + fmt.format(p.rev));
      if (p.aov != null) lines.push('Avg order value: ' + fmt.format(p.aov));
      if (gm.isApprox(p)) lines.push('No exact location; shown at the largest city in its country');
      return lines.join('\n');
    });
  }

  // Notes stack (bottom-left of map)
  const gpn = d3.llmGeoPointNotes(options.geoPoint, { offMap: offMap, unit: 'point' });
  let noteY = mapH - 8;
  const note = txt => {
    const t = svg.append('text').attr('x', 8).attr('y', noteY).attr('font-size', SUB).attr('fill', TF).text(txt);
    noteY -= SUB + 3;
    d3.llmFitLabel(t, mapW - 16, { pad: 0, text: txt });
    if (t.text() !== txt) t.append('title').text(txt);
  };
  if (dropped > 0) note('Showing largest ' + fmt.format(mapCap) + ' of ' + fmt.format(mapCap + dropped) + ' points - raise the map-point cap to see more');
  if (gpn.missing > 0) note(gpn.missingText);
  if (noSize > 0) note(noSize + (noSize === 1 ? ' point has' : ' points have') + ' no Orders: drawn as a hollow ring at the smallest size');
  if (gpn.coarse) note(gpn.coarse);
  if (gpn.ambiguous) note(gpn.ambiguous);
  if (gpn.rolesRefused) note(gpn.rolesRefused);

  const fit = (t, s, room) => { d3.llmFitLabel(t, room, { pad: 0, text: s }); if (t.text() !== s) t.append('title').text(s); };
  const compact = v => new Intl.NumberFormat(options.cultureCode, { notation: 'compact', maximumSignificantDigits: 3 }).format(v);
  const idxsFor = c => {
    const idxs = [];
    placed.forEach(p => { if (p.cat === c) (p.rowIdxs || [p.idx]).forEach(i => idxs.push(i)); });
    return idxs;
  };

  // Narrow: band under the plot
  if (bandLayout) {
    let by = mapH + 6;
    if (bandLayout.showLeg) {
      bandLayout.rowsL.forEach(row => {
        row.forEach(e => {
          svg.append('rect').attr('class', 'd3-legend-mark').attr('data-row-idx', idxsFor(e.c).join(','))
            .attr('x', e.x - 2).attr('y', by).attr('width', e.w - 4).attr('height', CF + 4)
            .attr('fill', 'transparent').style('cursor', 'pointer').style('pointer-events', 'all');
          svg.append('circle').attr('cx', e.x + 5).attr('cy', by + (CF + 4) / 2).attr('r', 4.5)
            .attr('fill', T.legible(colorOf(e.c))).style('pointer-events', 'none');
          const t = svg.append('text').attr('x', e.x + 14).attr('y', by + CF).attr('font-size', SUB).attr('fill', TF)
            .style('pointer-events', 'none').text(String(e.c));
          fit(t, String(e.c), Math.max(10, e.w - 18));
        });
        by += bandLayout.rowH;
      });
    }
    if (smax > 0) {
      const midY = by + 14;
      let sx = 8;
      const lt = svg.append('text').attr('x', sx).attr('y', midY + SUB * 0.35).attr('font-size', SUB).attr('font-weight', '700').attr('fill', TF).text('Orders');
      sx += 6 * SUB * 0.6 + 8;
      const refs = [smax, smax * 0.4, smax * 0.1].map(v => Math.abs(v) >= 1 ? Math.round(v) : +v.toPrecision(2))
        .filter((v, i, a) => v > 0 && a.indexOf(v) === i);
      refs.forEach(v => {
        const r = Math.min(rad(v), 12), lab = compact(v), lw = lab.length * SUB * 0.6;
        if (sx + 2 * r + 3 + lw > W - 6) return;
        svg.append('circle').attr('cx', sx + r).attr('cy', midY).attr('r', r).attr('fill', 'none')
          .attr('stroke', TF).attr('stroke-opacity', 0.5).attr('stroke-width', 1);
        svg.append('text').attr('x', sx + 2 * r + 3).attr('y', midY + SUB * 0.35).attr('font-size', SUB).attr('fill', TF).text(lab);
        sx += 2 * r + 3 + lw + 10;
      });
    }
  }

  // Right panel: tier legend + size key
  if (PANEL_W) {
    const px = mapW + PANEL_GAP, panelR = W - 6;
    let cy = 10 + CF;
    const head = s => { fit(svg.append('text').attr('x', px).attr('y', cy).attr('font-size', CF).attr('font-weight', '700').attr('fill', TF).text(s), s, panelR - px); cy += CF + 5; };
    if (ranked.length >= 2) {
      head('City Tier');
      ranked.slice(0, 8).forEach(c => {
        svg.append('rect').attr('class', 'd3-legend-mark').attr('data-row-idx', idxsFor(c).join(','))
          .attr('x', px - 3).attr('y', cy - CF + 1).attr('width', PANEL_W - 6).attr('height', CF + 4)
          .attr('fill', 'transparent').style('cursor', 'pointer').style('pointer-events', 'all');
        svg.append('circle').attr('cx', px + 5).attr('cy', cy - CF * 0.33).attr('r', 4.5)
          .attr('fill', T.legible(colorOf(c))).style('pointer-events', 'none');
        const t = svg.append('text').attr('x', px + 14).attr('y', cy).attr('font-size', SUB).attr('fill', TF)
          .style('pointer-events', 'none').text(String(c));
        fit(t, String(c), panelR - px - 14);
        cy += CF + 5;
      });
      if (ranked.length > 8) { svg.append('text').attr('x', px + 14).attr('y', cy).attr('font-size', SUB).attr('fill', TF).text('+' + (ranked.length - 8) + ' more'); cy += CF + 5; }
      const cap = 'Tiers ranked by total Orders, not tier order';
      const lines = [];
      let cur = '';
      cap.split(' ').forEach(w => { const nx = cur ? cur + ' ' + w : w; if (nx.length * SUB * 0.58 > panelR - px && cur) { lines.push(cur); cur = w; } else cur = nx; });
      if (cur) lines.push(cur);
      lines.slice(0, 3).forEach(s => { svg.append('text').attr('x', px).attr('y', cy).attr('font-size', SUB).attr('fill', TF).attr('fill-opacity', 0.8).text(s); cy += SUB + 3; });
      cy += 6;
      svg.append('line').attr('x1', px).attr('x2', panelR).attr('y1', cy).attr('y2', cy).attr('stroke', TF).attr('stroke-opacity', 0.15);
      cy += CF + 6;
    }
    if (smax > 0 && cy < H - 40) {
      head('Orders');
      const keyR = Math.max(6, Math.round(Math.min(rmax, PANEL_W * 0.30, H * 0.07)));
      const top = rad(smax) <= keyR ? smax : rad.invert(keyR);
      const refs = [top, top * 0.4, top * 0.1].map(v => Math.abs(v) >= 1 ? Math.round(v) : +v.toPrecision(2))
        .filter((v, i, a) => v > 0 && a.indexOf(v) === i);
      const PITCH = CF + 3;
      const use = refs.slice(0, Math.min(3, Math.max(1, Math.floor((2 * keyR) / PITCH) + 1)));
      const kx = px + keyR + 2, baseY = cy + 2 * keyR;
      use.forEach((v, i) => {
        const r = rad(v), ccy = baseY - r, ly = cy + CF + i * PITCH;
        svg.append('circle').attr('cx', kx).attr('cy', ccy).attr('r', r).attr('fill', 'none')
          .attr('stroke', TF).attr('stroke-opacity', 0.5).attr('stroke-width', 1);
        svg.append('line').attr('x1', kx).attr('x2', kx + keyR + 6).attr('y1', ccy - r).attr('y2', ly - CF * 0.32)
          .attr('stroke', TF).attr('stroke-opacity', 0.35).attr('stroke-width', 0.6);
        svg.append('text').attr('x', kx + keyR + 9).attr('y', ly).attr('font-size', SUB).attr('fill', TF).text(compact(v));
      });
    }
  }
}

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 🗙