@aquera/nile-visualization 2.9.39 → 2.9.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1502 @@
1
+ /**
2
+ * Category-axis pagination ("chip scroll") for every cartesian Nile chart.
3
+ *
4
+ * HOW IT REACHES EVERY CHART WITHOUT PER-CHART CODE
5
+ * -------------------------------------------------
6
+ * Like `chart-events.ts`, this is registered ONCE on the shared Highcharts
7
+ * instance (`highcharts-provider.ts`). It hooks the Chart class's `render`
8
+ * event, so every chart created through that instance — `<nile-chart>` and
9
+ * every `<nile-*-chart>` — is checked after each render/redraw.
10
+ *
11
+ * WHAT IT DOES
12
+ * ------------
13
+ * When the category axis holds more categories than fit (each category needs
14
+ * at least `minBand` px), the axis is windowed to one "page" via
15
+ * `axis.setExtremes()`. Highcharts keeps drawing the axes, grid, tooltip and
16
+ * legend exactly as before — only the visible category range changes.
17
+ *
18
+ * On top of the chart it overlays:
19
+ * - soft fades over the category labels, only on a side where data is hidden;
20
+ * - round chevron buttons (the hidden count is in their tooltip/aria-label), shown on hover of the
21
+ * category axis (always on touch devices, or with `chips: 'always'`):
22
+ * horizontal axis (column/line/area…): ‹ › at the two ends of the label row;
23
+ * vertical axis (bar/dumbbell…): ▲ above the label block, ▼ on the
24
+ * value-axis label line beneath it.
25
+ * Clicking a chip moves a full page. The mouse wheel over the category labels
26
+ * (or over the plot, in the axis's own direction) moves one category at a time
27
+ * and only captures the wheel while there is somewhere left to go.
28
+ *
29
+ * The value axis stays fixed across pages (`getExtremesFromAll`), so bars
30
+ * don't change scale as you page.
31
+ *
32
+ * NEVER APPLIES TO
33
+ * ----------------
34
+ * Polar charts (radar, spiderweb, radial bar) and non-axis types (pie, donut,
35
+ * variable pie, funnel, gauge, organization, timeline, euler/venn, flame,
36
+ * map…). Numeric/datetime x-axes (scatter, histogram, time series) are only
37
+ * paginated when explicitly turned on.
38
+ *
39
+ * CONFIGURATION (highest priority first)
40
+ * --------------------------------------
41
+ * 1. Attributes on the chart element:
42
+ * pagination="auto|on|off" page-size="12" page-start="0" pagination-chips="hover|always"
43
+ * 2. `config.chart.pagination` — the Nile-native way:
44
+ * el.config = { chart: { type: 'bar', categories, data, pagination: { pageSize: 8, chips: 'always', valueSpan: 400 } } }
45
+ * 3. `options.pagination` (the Highcharts `options` passthrough).
46
+ * See {@link NileChartPaginationConfig} for every field.
47
+ * OPT-IN: with no pagination config at all, nothing happens (upgrading changes no chart).
48
+ * Passing ANY pagination setting — `chart.pagination`, `options.pagination`, or one of
49
+ * the `pagination` / `page-size` / `page-start` / `value-span` / `value-start`
50
+ * attributes — turns it on in `auto` mode (page only when categories overflow),
51
+ * unless `enabled` says otherwise.
52
+ *
53
+ * Value axis (opt-in): `value-span="400"` (+ optional `value-start`) or
54
+ * `options.pagination.valueSpan` pages the value axis too — see the section
55
+ * at the end of this file.
56
+ *
57
+ * Emits `nile-chart-page-change` (bubbling, composed) from the chart container
58
+ * whenever the visible window changes.
59
+ */
60
+ export const NILE_CHART_PAGE_CHANGE = 'nile-chart-page-change';
61
+ export const NILE_CHART_VALUE_PAGE_CHANGE = 'nile-chart-value-page-change';
62
+ /** Series types that have no meaningful category axis to page. */
63
+ const EXCLUDED_TYPES = new Set([
64
+ 'pie',
65
+ 'variablepie',
66
+ 'funnel',
67
+ 'pyramid',
68
+ 'funnel3d',
69
+ 'pyramid3d',
70
+ 'gauge',
71
+ 'solidgauge',
72
+ 'organization',
73
+ 'venn',
74
+ 'euler',
75
+ 'flame',
76
+ 'sunburst',
77
+ 'treemap',
78
+ 'treegraph',
79
+ 'sankey',
80
+ 'dependencywheel',
81
+ 'networkgraph',
82
+ 'packedbubble',
83
+ 'wordcloud',
84
+ 'item',
85
+ 'xrange',
86
+ 'gantt',
87
+ 'map',
88
+ 'mapline',
89
+ 'mappoint',
90
+ 'mapbubble',
91
+ 'tiledwebmap',
92
+ 'geoheatmap',
93
+ ]);
94
+ /** Series types drawn as bands (need more room per category than a line point). */
95
+ const BAND_TYPES = new Set([
96
+ 'column',
97
+ 'bar',
98
+ 'columnrange',
99
+ 'columnpyramid',
100
+ 'boxplot',
101
+ 'errorbar',
102
+ 'waterfall',
103
+ 'dumbbell',
104
+ 'lollipop',
105
+ 'heatmap',
106
+ 'cylinder',
107
+ 'variwide',
108
+ ]);
109
+ /**
110
+ * "Event" series: discrete points on a hidden axis, labelled by data labels
111
+ * (timeline). They page by event, need room per event for the labels, and put
112
+ * their chevrons at the ends of the line rather than on an axis label row.
113
+ */
114
+ const EVENT_TYPES = new Set(['timeline']);
115
+ const EVENT_BAND_H = 90;
116
+ const EVENT_BAND_V = 60;
117
+ function isEventAxis(chart, axis) {
118
+ const on = (chart.series ?? []).filter((s) => s.xAxis === axis);
119
+ return on.length > 0 && on.every((s) => EVENT_TYPES.has(s.type));
120
+ }
121
+ const DEFAULT_BAND_MIN = 36;
122
+ const DEFAULT_LINE_MIN = 24;
123
+ /** Labels longer than this still rotate rather than leaving only a few categories per page. */
124
+ const MAX_LABEL_BAND = 72;
125
+ const FADE = 32;
126
+ const HOST_ATTRS = [
127
+ 'pagination',
128
+ 'page-size',
129
+ 'page-start',
130
+ 'pagination-chips',
131
+ 'value-span',
132
+ 'value-start',
133
+ ];
134
+ // zoom-type / panning / pan-key are read once, when the chart is built.
135
+ const ARROW = {
136
+ up: 'M3.5 10 8 5.5l4.5 4.5',
137
+ down: 'M3.5 6 8 10.5 12.5 6',
138
+ left: 'M10 3.5 5.5 8l4.5 4.5',
139
+ right: 'M6 3.5 10.5 8 6 12.5',
140
+ };
141
+ const STYLE = `
142
+ .nile-pg{position:absolute;left:0;top:0;width:100%;height:100%;pointer-events:none;z-index:4}
143
+ .nile-pg-fade{position:absolute;pointer-events:none;opacity:0;transition:opacity .15s;
144
+ --nile-pg-fade-c:var(--nile-chart-pagination-fade,var(--nile-chart-bg,var(--ng-colors-bg-primary,var(--nile-colors-white-base,#fff))))}
145
+ .nile-pg-fade.f-left{background:linear-gradient(90deg,var(--nile-pg-fade-c),transparent)}
146
+ .nile-pg-fade.f-right{background:linear-gradient(270deg,var(--nile-pg-fade-c),transparent)}
147
+ .nile-pg-fade.f-top{background:linear-gradient(180deg,var(--nile-pg-fade-c),transparent)}
148
+ .nile-pg-fade.f-bottom{background:linear-gradient(0deg,var(--nile-pg-fade-c),transparent)}
149
+ .nile-pg.more-low .nile-pg-fade.low,.nile-pg.more-high .nile-pg-fade.high{opacity:1}
150
+ .nile-pg-chip{position:absolute;box-sizing:border-box;margin:0;width:20px;height:20px;padding:0;display:inline-flex;align-items:center;justify-content:center;
151
+ border:0;border-radius:50%;cursor:pointer;white-space:nowrap;opacity:0;pointer-events:none;transition:opacity .15s,background-color .15s;
152
+ background:var(--nile-chart-pagination-chip-bg,var(--ng-colors-bg-secondary,var(--nile-colors-neutral-100,#f5f5f5)));
153
+ color:var(--nile-chart-pagination-chip-color,var(--ng-colors-text-tertiary-600,var(--nile-colors-dark-500,#535862)));
154
+ font:500 10px/1 var(--ng-font-family-body,var(--nile-font-family-body,inherit));font-variant-numeric:tabular-nums}
155
+ .nile-pg-chip svg{display:block;width:12px;height:12px;flex:none}
156
+ .nile-pg-chip:hover{background:var(--nile-chart-pagination-chip-bg-hover,var(--ng-colors-bg-tertiary,var(--nile-colors-neutral-200,#e9eaeb)));
157
+ color:var(--ng-colors-text-primary-900,var(--nile-colors-dark-900,#181d27))}
158
+ .nile-pg-chip:focus-visible{opacity:1;pointer-events:auto;outline:2px solid var(--ng-colors-border-brand,var(--nile-colors-primary-600,#2d79eb));outline-offset:1px}
159
+ .nile-pg.more-low:is(.hot,.always) .nile-pg-chip.low,.nile-pg.more-high:is(.hot,.always) .nile-pg-chip.high{opacity:1;pointer-events:auto}
160
+ @media (hover:none){.nile-pg.more-low .nile-pg-chip.low,.nile-pg.more-high .nile-pg-chip.high{opacity:1;pointer-events:auto}}
161
+ @media (prefers-reduced-motion:reduce){.nile-pg-fade,.nile-pg-chip{transition:none}}
162
+ `;
163
+ const STATE = Symbol('nilePager');
164
+ /* ------------------------------------------------------------------ config */
165
+ /**
166
+ * Shadow hosts around the chart, innermost first. `<nile-chart>` renders an inner
167
+ * `<nile-*-chart>`, so attributes may sit on either element — the inner one wins.
168
+ */
169
+ function hostsOf(chart) {
170
+ const hosts = [];
171
+ let node = chart?.renderTo ?? null;
172
+ while (node && hosts.length < 4) {
173
+ const root = node.getRootNode?.();
174
+ const host = root && root.host;
175
+ if (!(host instanceof Element))
176
+ break;
177
+ hosts.push(host);
178
+ node = host;
179
+ }
180
+ return hosts;
181
+ }
182
+ function hostAttr(hosts, name) {
183
+ for (const h of hosts) {
184
+ const v = h.getAttribute(name);
185
+ if (v !== null)
186
+ return v;
187
+ }
188
+ return null;
189
+ }
190
+ /** Accepts the object form or the shorthand (`true` / `false` / `'auto'` / `'on'` / `'off'`). */
191
+ function asConfig(v) {
192
+ if (v && typeof v === 'object')
193
+ return v;
194
+ if (v === undefined || v === null || v === '')
195
+ return {};
196
+ return { enabled: v };
197
+ }
198
+ /**
199
+ * The effective pagination settings for a chart, merged lowest → highest priority:
200
+ * 1. `options.pagination` (Highcharts passthrough)
201
+ * 2. `config.chart.pagination` on the chart element (or root-level `config.pagination`
202
+ * for a flat `<nile-chart>` config) — outer `<nile-chart>` first, inner chart wins
203
+ * 3. attributes on the chart element (`pagination`, `page-size`, … — inner element wins)
204
+ */
205
+ /** Attributes that count as opting in (`pagination-chips` alone only styles, it doesn't opt in). */
206
+ const OPT_IN_ATTRS = ['pagination', 'page-size', 'page-start', 'value-span', 'value-start'];
207
+ function resolvePagination(chart) {
208
+ const fromOptions = chart.userOptions?.pagination ?? chart.options?.pagination;
209
+ let provided = fromOptions !== undefined && fromOptions !== null;
210
+ const cfg = { ...asConfig(fromOptions) };
211
+ const hosts = hostsOf(chart);
212
+ for (const host of [...hosts].reverse()) {
213
+ const c = host.config;
214
+ const own = c?.chart?.pagination ?? c?.pagination;
215
+ if (own !== undefined && own !== null) {
216
+ provided = true;
217
+ Object.assign(cfg, asConfig(own));
218
+ }
219
+ }
220
+ if (OPT_IN_ATTRS.some((a) => hostAttr(hosts, a) !== null))
221
+ provided = true;
222
+ const num = (name) => {
223
+ const v = hostAttr(hosts, name);
224
+ const n = v === null || v.trim() === '' ? NaN : Number(v);
225
+ return Number.isFinite(n) ? n : undefined;
226
+ };
227
+ const attr = hostAttr(hosts, 'pagination');
228
+ if (attr !== null)
229
+ cfg.enabled = attr === '' ? 'on' : attr;
230
+ const size = num('page-size');
231
+ if (size !== undefined && size > 0)
232
+ cfg.pageSize = size;
233
+ const start = num('page-start');
234
+ if (start !== undefined && start >= 0)
235
+ cfg.start = start;
236
+ const chips = hostAttr(hosts, 'pagination-chips');
237
+ if (chips === 'always' || chips === 'hover')
238
+ cfg.chips = chips;
239
+ const span = num('value-span');
240
+ if (span !== undefined)
241
+ cfg.valueSpan = span;
242
+ const vStart = num('value-start');
243
+ if (vStart !== undefined)
244
+ cfg.valueStart = vStart;
245
+ return { ...cfg, provided };
246
+ }
247
+ function readConfig(chart) {
248
+ const cfg = resolvePagination(chart);
249
+ if (!cfg.provided)
250
+ return null; // opt-in: no pagination config → off
251
+ const e = cfg.enabled;
252
+ if (e === false || e === 'off' || e === 'false')
253
+ return null;
254
+ const mode = e === true || e === 'on' || e === 'true' ? 'on' : 'auto';
255
+ return {
256
+ mode,
257
+ pageSize: cfg.pageSize && cfg.pageSize > 0 ? Math.floor(cfg.pageSize) : undefined,
258
+ start: cfg.start && cfg.start > 0 ? Math.floor(cfg.start) : 0,
259
+ minBand: cfg.minBand && cfg.minBand > 0 ? cfg.minBand : undefined,
260
+ chips: cfg.chips === 'always' ? 'always' : 'hover',
261
+ fixedValueAxis: cfg.fixedValueAxis !== false,
262
+ };
263
+ }
264
+ /* ------------------------------------------------------------- eligibility */
265
+ function seriesXs(series) {
266
+ if (typeof series.getColumn === 'function') {
267
+ const col = series.getColumn('x');
268
+ if (col && col.length)
269
+ return col;
270
+ }
271
+ return series.xData ?? [];
272
+ }
273
+ function isCategoryAxis(axis) {
274
+ return !!(axis.categories?.length || axis.options?.type === 'category' || axis.names?.length);
275
+ }
276
+ /** Distinct x values the axis can step through, ascending; `null` = not pageable. */
277
+ function collectXs(chart, axis, cfg) {
278
+ if (chart.polar || chart.angular)
279
+ return null;
280
+ if (chart.options?.navigator?.enabled || chart.options?.scrollbar?.enabled)
281
+ return null;
282
+ if (!chart.series?.length)
283
+ return null;
284
+ if (chart.series.some((s) => EXCLUDED_TYPES.has(s.type)))
285
+ return null;
286
+ const events = isEventAxis(chart, axis);
287
+ if (axis.options?.visible === false && cfg.mode === 'auto' && !events)
288
+ return null;
289
+ const category = isCategoryAxis(axis) && !events;
290
+ if (!category && !events && cfg.mode === 'auto')
291
+ return null;
292
+ if (axis.options?.type === 'datetime' && cfg.mode === 'auto' && !events)
293
+ return null;
294
+ const onAxis = chart.series.filter((s) => s.xAxis === axis);
295
+ if (category) {
296
+ let n = Math.max(axis.categories?.length ?? 0, axis.names?.length ?? 0);
297
+ for (const s of onAxis) {
298
+ const xs = seriesXs(s);
299
+ for (let i = 0; i < xs.length; i++)
300
+ if (Number.isFinite(xs[i]) && xs[i] + 1 > n)
301
+ n = Math.floor(xs[i]) + 1;
302
+ }
303
+ return Array.from({ length: n }, (_, i) => i);
304
+ }
305
+ const set = new Set();
306
+ // Numeric axes: only what is drawn (e.g. skip histogram's hidden sample series).
307
+ for (const s of onAxis.filter((x) => x.visible !== false && x.options?.visible !== false)) {
308
+ const xs = seriesXs(s);
309
+ for (let i = 0; i < xs.length; i++)
310
+ if (Number.isFinite(xs[i]))
311
+ set.add(xs[i]);
312
+ }
313
+ return Array.from(set).sort((a, b) => a - b);
314
+ }
315
+ function autoPageSize(chart, axis, cfg) {
316
+ if (cfg.pageSize)
317
+ return cfg.pageSize;
318
+ if (isEventAxis(chart, axis)) {
319
+ const min = cfg.minBand ?? (axis.horiz ? EVENT_BAND_H : EVENT_BAND_V);
320
+ return Math.max(1, Math.floor((axis.len || 0) / min));
321
+ }
322
+ const banded = chart.series.some((s) => s.xAxis === axis && BAND_TYPES.has(s.type));
323
+ let min = cfg.minBand ?? (banded ? DEFAULT_BAND_MIN : DEFAULT_LINE_MIN);
324
+ // On a horizontal axis, give each category room for its label so a page reads
325
+ // without Highcharts having to rotate or stagger the labels.
326
+ if (!cfg.minBand && axis.horiz && axis.options?.labels?.enabled !== false) {
327
+ min = Math.max(min, Math.min(MAX_LABEL_BAND, longestLabelPx(axis) + 24));
328
+ }
329
+ return Math.max(1, Math.floor((axis.len || 0) / min));
330
+ }
331
+ let measureCtx;
332
+ /** Width (px) of the longest category label at the axis label font. */
333
+ function longestLabelPx(axis) {
334
+ const names = axis.categories?.length ? axis.categories : axis.names ?? [];
335
+ if (!names.length)
336
+ return 0;
337
+ const style = axis.options?.labels?.style ?? {};
338
+ const size = parseFloat(String(style.fontSize ?? '11')) || 11;
339
+ const px = String(style.fontSize ?? '').endsWith('em') ? size * 14 : size;
340
+ if (measureCtx === undefined) {
341
+ try {
342
+ measureCtx = document.createElement('canvas').getContext('2d');
343
+ }
344
+ catch {
345
+ measureCtx = null;
346
+ }
347
+ }
348
+ let longest = 0;
349
+ for (const n of names) {
350
+ const t = String(n ?? '');
351
+ const w = measureCtx
352
+ ? ((measureCtx.font = `${px}px ${axis.chart?.renderer?.style?.fontFamily || 'sans-serif'}`),
353
+ measureCtx.measureText(t).width)
354
+ : t.length * px * 0.55;
355
+ if (w > longest)
356
+ longest = w;
357
+ }
358
+ return longest;
359
+ }
360
+ /* ----------------------------------------------------------------- overlay */
361
+ function arrowSvg(dir) {
362
+ return `<svg viewBox="0 0 16 16" aria-hidden="true"><path d="${ARROW[dir]}" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
363
+ }
364
+ function ensureOverlay(chart, st) {
365
+ if (st.root && st.root.isConnected && st.root.parentNode === chart.container)
366
+ return;
367
+ const doc = chart.container.ownerDocument;
368
+ const root = doc.createElement('div');
369
+ root.className = 'nile-pg';
370
+ root.setAttribute('part', 'pagination');
371
+ const style = doc.createElement('style');
372
+ style.textContent = STYLE;
373
+ root.appendChild(style);
374
+ const mkFade = (side) => {
375
+ const f = doc.createElement('i');
376
+ f.className = `nile-pg-fade ${side}`;
377
+ root.appendChild(f);
378
+ return f;
379
+ };
380
+ const mkChip = (side) => {
381
+ const b = doc.createElement('button');
382
+ b.type = 'button';
383
+ b.className = `nile-pg-chip ${side}`;
384
+ b.setAttribute('part', `pagination-chip pagination-chip-${side === 'low' ? 'previous' : 'next'}`);
385
+ b.addEventListener('click', (ev) => {
386
+ ev.stopPropagation();
387
+ move(chart, side === 'low' ? -st.pageSize : st.pageSize, 'chip');
388
+ });
389
+ // Keep the chip from starting a Highcharts drag/zoom.
390
+ b.addEventListener('mousedown', (ev) => ev.stopPropagation());
391
+ b.addEventListener('pointerdown', (ev) => ev.stopPropagation());
392
+ root.appendChild(b);
393
+ return b;
394
+ };
395
+ st.fades = { low: mkFade('low'), high: mkFade('high') };
396
+ st.chips = { low: mkChip('low'), high: mkChip('high') };
397
+ chart.container.appendChild(root);
398
+ st.root = root;
399
+ }
400
+ /**
401
+ * Bounding box of the axis's CURRENTLY VISIBLE tick labels. (The label group's own
402
+ * box also counts labels Highcharts is still fading out after a range change.)
403
+ */
404
+ function labelBox(axis) {
405
+ let x1 = Infinity, y1 = Infinity, x2 = -Infinity, y2 = -Infinity;
406
+ try {
407
+ const c = axis.chart.container.getBoundingClientRect();
408
+ const lo = Math.min(axis.min, axis.max);
409
+ const hi = Math.max(axis.min, axis.max);
410
+ for (const key of Object.keys(axis.ticks ?? {})) {
411
+ const tick = axis.ticks[key];
412
+ const label = tick?.label;
413
+ const pos = Number(tick?.pos);
414
+ if (!label?.element || !Number.isFinite(pos) || pos < lo - 1e-9 || pos > hi + 1e-9)
415
+ continue;
416
+ if (label.visibility === 'hidden' || label.element.getAttribute('opacity') === '0')
417
+ continue;
418
+ // Screen rect relative to the container: honours rotation, and isn't Highcharts'
419
+ // text-keyed bbox cache (which can return another label's position).
420
+ const r = label.element.getBoundingClientRect();
421
+ if (!r.width || !r.height)
422
+ continue;
423
+ x1 = Math.min(x1, r.left - c.left);
424
+ y1 = Math.min(y1, r.top - c.top);
425
+ x2 = Math.max(x2, r.right - c.left);
426
+ y2 = Math.max(y2, r.bottom - c.top);
427
+ }
428
+ }
429
+ catch {
430
+ /* labels not rendered */
431
+ }
432
+ return Number.isFinite(x1) ? { x: x1, y: y1, w: x2 - x1, h: y2 - y1 } : null;
433
+ }
434
+ function place(el, css) {
435
+ el.removeAttribute('style');
436
+ Object.assign(el.style, css);
437
+ }
438
+ function layout(chart, axis, st, cfg) {
439
+ ensureOverlay(chart, st);
440
+ const root = st.root;
441
+ const chips = st.chips;
442
+ const fades = st.fades;
443
+ const W = chart.chartWidth;
444
+ const H = chart.chartHeight;
445
+ const horiz = !!axis.horiz;
446
+ // Which screen side holds the LOWER category indices.
447
+ const lowFirst = horiz ? !axis.reversed : !!axis.reversed; // horiz: left; vertical: top
448
+ const box = labelBox(axis);
449
+ const clampY = (y) => Math.min(H - 9, Math.max(9, y));
450
+ const clampX = (x) => Math.min(W - 2, Math.max(2, x));
451
+ if (st.events) {
452
+ // No axis row: chevrons sit at the two ends of the timeline, centred on the
453
+ // plot, with full-height fades at the edges where more events are hidden.
454
+ const left = chart.plotLeft;
455
+ const top = chart.plotTop;
456
+ const w = chart.plotWidth;
457
+ const h = chart.plotHeight;
458
+ const CHIP = 20;
459
+ const [a, b] = lowFirst ? ['low', 'high'] : ['high', 'low'];
460
+ if (horiz) {
461
+ const cy = top + h / 2;
462
+ place(fades[a], {
463
+ left: `${left}px`,
464
+ top: `${top}px`,
465
+ width: `${FADE * 1.5}px`,
466
+ height: `${h}px`,
467
+ });
468
+ place(fades[b], {
469
+ left: `${left + w - FADE * 1.5}px`,
470
+ top: `${top}px`,
471
+ width: `${FADE * 1.5}px`,
472
+ height: `${h}px`,
473
+ });
474
+ fades[a].className = `nile-pg-fade ${a} f-left`;
475
+ fades[b].className = `nile-pg-fade ${b} f-right`;
476
+ place(chips[a], {
477
+ left: `${clampX(left + 2)}px`,
478
+ top: `${cy}px`,
479
+ transform: 'translateY(-50%)',
480
+ });
481
+ place(chips[b], {
482
+ left: `${Math.min(W - CHIP - 2, left + w - CHIP - 2)}px`,
483
+ top: `${cy}px`,
484
+ transform: 'translateY(-50%)',
485
+ });
486
+ setChip(chips[a], 'left');
487
+ setChip(chips[b], 'right');
488
+ }
489
+ else {
490
+ const cx = left + w / 2;
491
+ place(fades[a], {
492
+ left: `${left}px`,
493
+ top: `${top}px`,
494
+ width: `${w}px`,
495
+ height: `${FADE * 1.5}px`,
496
+ });
497
+ place(fades[b], {
498
+ left: `${left}px`,
499
+ top: `${top + h - FADE * 1.5}px`,
500
+ width: `${w}px`,
501
+ height: `${FADE * 1.5}px`,
502
+ });
503
+ fades[a].className = `nile-pg-fade ${a} f-top`;
504
+ fades[b].className = `nile-pg-fade ${b} f-bottom`;
505
+ place(chips[a], {
506
+ left: `${cx}px`,
507
+ top: `${clampY(top + 12)}px`,
508
+ transform: 'translate(-50%,-50%)',
509
+ });
510
+ place(chips[b], {
511
+ left: `${cx}px`,
512
+ top: `${clampY(top + h - 12)}px`,
513
+ transform: 'translate(-50%,-50%)',
514
+ });
515
+ setChip(chips[a], 'up');
516
+ setChip(chips[b], 'down');
517
+ }
518
+ st.axisRegion = { x: left, y: top, w, h };
519
+ }
520
+ else if (horiz) {
521
+ const rowH = box ? box.h : 18;
522
+ const rowY = box ? box.y : axis.opposite ? axis.top - rowH - 4 : axis.top + axis.height + 4;
523
+ const cy = clampY(rowY + rowH / 2);
524
+ const left = axis.left;
525
+ const right = left + axis.width;
526
+ const [lSide, rSide] = lowFirst ? ['low', 'high'] : ['high', 'low'];
527
+ place(fades[lSide], {
528
+ left: `${left}px`,
529
+ top: `${rowY}px`,
530
+ width: `${FADE}px`,
531
+ height: `${rowH}px`,
532
+ });
533
+ place(fades[rSide], {
534
+ left: `${right - FADE}px`,
535
+ top: `${rowY}px`,
536
+ width: `${FADE}px`,
537
+ height: `${rowH}px`,
538
+ });
539
+ fades[lSide].className = `nile-pg-fade ${lSide} f-left`;
540
+ fades[rSide].className = `nile-pg-fade ${rSide} f-right`;
541
+ // Chevrons sit just outside the ends of the label row when the chart has room
542
+ // there (the y-axis label column on the left, spacing on the right); otherwise
543
+ // they tuck inside the row over the faded end label.
544
+ const CHIP = 20;
545
+ const lx = left >= CHIP + 4 ? left - CHIP - 2 : left + 2;
546
+ const rx = W - right >= CHIP + 4 ? right + 2 : right - CHIP - 2;
547
+ place(chips[lSide], { left: `${clampX(lx)}px`, top: `${cy}px`, transform: 'translateY(-50%)' });
548
+ place(chips[rSide], {
549
+ left: `${Math.min(W - CHIP - 2, rx)}px`,
550
+ top: `${cy}px`,
551
+ transform: 'translateY(-50%)',
552
+ });
553
+ setChip(chips[lSide], 'left');
554
+ setChip(chips[rSide], 'right');
555
+ st.axisRegion = {
556
+ x: Math.min(lx, left) - 6,
557
+ y: rowY - 6,
558
+ w: Math.max(rx + CHIP, right) - Math.min(lx, left) + 12,
559
+ h: rowH + 12,
560
+ };
561
+ }
562
+ else {
563
+ const blockX = box ? box.x : axis.opposite ? axis.left + axis.width : 0;
564
+ const blockW = box ? box.w : axis.opposite ? W - blockX : axis.left;
565
+ const cx = clampX(blockX + blockW / 2);
566
+ const top = axis.top;
567
+ const bottom = top + axis.height;
568
+ const [tSide, bSide] = lowFirst ? ['low', 'high'] : ['high', 'low'];
569
+ const fh = Math.min(FADE, (bottom - top) / 3);
570
+ place(fades[tSide], {
571
+ left: `${blockX}px`,
572
+ top: `${top}px`,
573
+ width: `${blockW}px`,
574
+ height: `${fh}px`,
575
+ });
576
+ place(fades[bSide], {
577
+ left: `${blockX}px`,
578
+ top: `${bottom - fh}px`,
579
+ width: `${blockW}px`,
580
+ height: `${fh}px`,
581
+ });
582
+ fades[tSide].className = `nile-pg-fade ${tSide} f-top`;
583
+ fades[bSide].className = `nile-pg-fade ${bSide} f-bottom`;
584
+ // ▲ sits just above the label block; ▼ sits on the value-axis label line beneath it.
585
+ place(chips[tSide], {
586
+ left: `${cx}px`,
587
+ top: `${clampY(top - 12)}px`,
588
+ transform: 'translate(-50%,-50%)',
589
+ });
590
+ place(chips[bSide], {
591
+ left: `${cx}px`,
592
+ top: `${clampY(bottom + 15)}px`,
593
+ transform: 'translate(-50%,-50%)',
594
+ });
595
+ setChip(chips[tSide], 'up');
596
+ setChip(chips[bSide], 'down');
597
+ st.axisRegion = { x: blockX - 4, y: top - 24, w: blockW + 8, h: bottom - top + 48 };
598
+ }
599
+ const before = st.start;
600
+ const after = Math.max(0, st.total - st.start - st.pageSize);
601
+ updateChip(chips.low, before, 'previous');
602
+ updateChip(chips.high, after, 'next');
603
+ root.classList.toggle('more-low', before > 0);
604
+ root.classList.toggle('more-high', after > 0);
605
+ root.classList.toggle('always', cfg.chips === 'always');
606
+ root.hidden = false;
607
+ }
608
+ function setChip(btn, dir) {
609
+ if (btn.dataset.dir === dir)
610
+ return;
611
+ btn.dataset.dir = dir;
612
+ btn.innerHTML = arrowSvg(dir);
613
+ }
614
+ /** Chevron-only button: the hidden count lives in the accessible name + tooltip, not on screen. */
615
+ function updateChip(btn, count, word) {
616
+ const label = count > 0
617
+ ? `Show ${word} ${count === 1 ? 'category' : `categories (${count} more)`}`
618
+ : `No ${word} categories`;
619
+ btn.setAttribute('aria-label', label);
620
+ btn.title = count > 0 ? `${count} more` : '';
621
+ btn.tabIndex = count > 0 ? 0 : -1;
622
+ }
623
+ /* ------------------------------------------------------------ interaction */
624
+ function attachListeners(chart, st) {
625
+ const c = chart.container;
626
+ const inRect = (r, x, y) => !!r && x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
627
+ const local = (ev) => {
628
+ const b = c.getBoundingClientRect();
629
+ return { x: ev.clientX - b.left, y: ev.clientY - b.top };
630
+ };
631
+ const onMove = (ev) => {
632
+ if (!st.root || !st.active)
633
+ return;
634
+ const { x, y } = local(ev);
635
+ st.root.classList.toggle('hot', inRect(st.axisRegion, x, y));
636
+ };
637
+ const onLeave = () => st.root?.classList.remove('hot');
638
+ const onWheel = (ev) => {
639
+ if (!st.active || ev.ctrlKey)
640
+ return;
641
+ const axis = chart.xAxis?.[0];
642
+ if (!axis)
643
+ return;
644
+ const { x, y } = local(ev);
645
+ // Event axes hover over the whole plot, but only a sideways gesture pages them.
646
+ const overAxis = !st.events && inRect(st.axisRegion, x, y);
647
+ const overPlot = x >= chart.plotLeft &&
648
+ x <= chart.plotLeft + chart.plotWidth &&
649
+ y >= chart.plotTop &&
650
+ y <= chart.plotTop + chart.plotHeight;
651
+ if (!overAxis && !overPlot)
652
+ return;
653
+ const scale = ev.deltaMode === 1 ? 16 : ev.deltaMode === 2 ? axis.len || 300 : 1;
654
+ let d;
655
+ if (axis.horiz) {
656
+ // Over the labels any wheel direction pages; over the plot only a horizontal
657
+ // gesture (or shift+wheel) does, so ordinary vertical page scrolling still works.
658
+ const dx = ev.deltaX || (ev.shiftKey ? ev.deltaY : 0);
659
+ d = overAxis ? (Math.abs(ev.deltaX) > Math.abs(ev.deltaY) ? ev.deltaX : ev.deltaY) : dx;
660
+ if (axis.reversed)
661
+ d = -d;
662
+ }
663
+ else {
664
+ d = ev.deltaY;
665
+ // Vertical category axis: lower indices sit at the top when reversed (bar default).
666
+ if (!axis.reversed)
667
+ d = -d;
668
+ }
669
+ d *= scale;
670
+ if (!d)
671
+ return;
672
+ const band = (axis.len || 1) / Math.max(1, st.pageSize);
673
+ if (Math.sign(d) !== Math.sign(st.wheelAcc))
674
+ st.wheelAcc = 0;
675
+ st.wheelAcc += d;
676
+ const steps = Math.trunc(st.wheelAcc / Math.max(12, band));
677
+ const canMove = d < 0 ? st.start > 0 : st.start + st.pageSize < st.total;
678
+ if (!canMove) {
679
+ st.wheelAcc = 0;
680
+ return; // at the edge — let the page scroll.
681
+ }
682
+ ev.preventDefault();
683
+ if (steps) {
684
+ st.wheelAcc -= steps * Math.max(12, band);
685
+ move(chart, steps, 'wheel');
686
+ }
687
+ };
688
+ // End of a Highcharts pan: snap the window to whole categories.
689
+ const doc = c.ownerDocument;
690
+ const onRelease = () => {
691
+ if (!st.panned)
692
+ return;
693
+ st.panned = false;
694
+ if (st.active)
695
+ apply(chart, st);
696
+ };
697
+ doc.addEventListener('mouseup', onRelease);
698
+ doc.addEventListener('touchend', onRelease);
699
+ st.cleanup.push(() => {
700
+ doc.removeEventListener('mouseup', onRelease);
701
+ doc.removeEventListener('touchend', onRelease);
702
+ });
703
+ c.addEventListener('mousemove', onMove);
704
+ c.addEventListener('mouseleave', onLeave);
705
+ c.addEventListener('wheel', onWheel, { passive: false });
706
+ st.cleanup.push(() => {
707
+ c.removeEventListener('mousemove', onMove);
708
+ c.removeEventListener('mouseleave', onLeave);
709
+ c.removeEventListener('wheel', onWheel);
710
+ });
711
+ const hosts = hostsOf(chart);
712
+ if (hosts.length && typeof MutationObserver !== 'undefined') {
713
+ const mo = new MutationObserver(() => update(chart));
714
+ hosts.forEach((h) => mo.observe(h, { attributes: true, attributeFilter: HOST_ATTRS }));
715
+ st.cleanup.push(() => mo.disconnect());
716
+ }
717
+ }
718
+ /* ------------------------------------------------------------------- core */
719
+ function windowExtremes(st) {
720
+ const last = Math.max(st.start, Math.min(st.total, st.start + st.pageSize) - 1);
721
+ const min = st.xs[st.start];
722
+ const max = st.xs[last];
723
+ if (!st.events)
724
+ return { min, max };
725
+ // Events sit ON the extremes otherwise, cutting their labels at the plot edge:
726
+ // pad by half the typical gap between events.
727
+ const n = last - st.start;
728
+ const gap = n > 0 ? (max - min) / n : (st.xs[st.start + 1] ?? st.xs[st.start - 1] ?? min + 1) - min;
729
+ const pad = Math.abs(gap || 1) / 2;
730
+ return { min: min - pad, max: max + pad };
731
+ }
732
+ function clampStart(st) {
733
+ st.start = Math.max(0, Math.min(st.start, st.total - st.pageSize));
734
+ }
735
+ /** Move the window by `delta` categories (negative = toward the first category). */
736
+ function move(chart, delta, source = 'api') {
737
+ const st = chart?.[STATE];
738
+ if (!st || !st.active)
739
+ return;
740
+ const before = st.start;
741
+ st.start += delta;
742
+ clampStart(st);
743
+ if (st.start === before)
744
+ return;
745
+ st.nextSource = source;
746
+ st.nextDirection = st.start > before ? 'next' : 'previous';
747
+ // Called from inside a render (e.g. a page-change listener)? Defer the redraw.
748
+ if (rendering > 0)
749
+ schedule(chart, st, () => apply(chart, st));
750
+ else
751
+ apply(chart, st);
752
+ }
753
+ /** >0 while Highcharts is inside a render pass that this module is handling. */
754
+ let rendering = 0;
755
+ function apply(chart, st) {
756
+ const axis = chart.xAxis?.[0];
757
+ if (!axis)
758
+ return;
759
+ const { min, max } = windowExtremes(st);
760
+ st.applied = { min, max };
761
+ // Numeric axes refuse to show less than `minRange` (Highcharts defaults it to
762
+ // 5 × the point spacing), which would stretch a small page. Allow any page size.
763
+ if (!isCategoryAxis(axis) && max > min) {
764
+ const allow = (max - min) / 2;
765
+ if (!(axis.userMinRange <= allow))
766
+ axis.userMinRange = allow; // what Highcharts recomputes minRange from
767
+ if (!(axis.minRange <= allow))
768
+ axis.minRange = allow;
769
+ }
770
+ axis.setExtremes(min, max, true, false, { trigger: 'nile-pagination' });
771
+ }
772
+ function emitChange(chart, st) {
773
+ const end = Math.min(st.total, st.start + st.pageSize);
774
+ const key = st.active ? `${st.start}|${end}|${st.total}` : 'off';
775
+ if (key === st.lastEmitted)
776
+ return;
777
+ st.lastEmitted = key;
778
+ if (!st.active) {
779
+ // Switching back on later announces 'init' again — but resuming after a
780
+ // zoom is reported as 'auto', since pagination never really went away.
781
+ if (!st.pausedByZoom)
782
+ st.lastShown = false;
783
+ return;
784
+ }
785
+ const first = !st.lastShown;
786
+ st.lastShown = true;
787
+ const source = st.nextSource ?? (first ? 'init' : 'auto');
788
+ const direction = st.nextSource ? st.nextDirection : undefined;
789
+ st.nextSource = null;
790
+ st.nextDirection = undefined;
791
+ const axis = chart.xAxis?.[0];
792
+ const names = axis?.categories?.length ? axis.categories : axis?.names ?? [];
793
+ const categories = st.xs.slice(st.start, end).map((x) => names[x] ?? x);
794
+ const detail = {
795
+ chart,
796
+ start: st.start,
797
+ end,
798
+ pageSize: st.pageSize,
799
+ total: st.total,
800
+ categories,
801
+ source,
802
+ ...(direction ? { direction } : {}),
803
+ hasPrevious: st.start > 0,
804
+ hasNext: end < st.total,
805
+ };
806
+ chart.container?.dispatchEvent(new CustomEvent(NILE_CHART_PAGE_CHANGE, { bubbles: true, composed: true, detail }));
807
+ }
808
+ function deactivate(chart, st) {
809
+ const wasApplied = st.applied;
810
+ st.active = false;
811
+ st.applied = null;
812
+ if (st.root)
813
+ st.root.hidden = true;
814
+ if (wasApplied) {
815
+ const axis = chart.xAxis?.[0];
816
+ const ext = axis?.getExtremes?.();
817
+ // Only undo our own window — never a range the user/consumer set.
818
+ if (ext && ext.userMin === wasApplied.min && ext.userMax === wasApplied.max) {
819
+ schedule(chart, st, () => axis.setExtremes(undefined, undefined, true, false, { trigger: 'nile-pagination' }), 'reset');
820
+ }
821
+ }
822
+ const axis = chart.xAxis?.[0];
823
+ if (axis)
824
+ reserveRightSpace(chart, axis, st, false);
825
+ emitChange(chart, st);
826
+ }
827
+ function schedule(chart, st, fn, kind = 'apply') {
828
+ const first = st.queue.size === 0;
829
+ st.queue.set(kind, fn);
830
+ if (!first)
831
+ return;
832
+ // Never redraw from inside Highcharts' own render pass.
833
+ queueMicrotask(() => {
834
+ const jobs = Array.from(st.queue.values());
835
+ st.queue.clear();
836
+ for (const job of jobs) {
837
+ if (!chart.renderer || chart.renderer.forExport || !chart.container)
838
+ return; // destroyed
839
+ job();
840
+ }
841
+ });
842
+ }
843
+ const CHIP_ROOM = 24;
844
+ /** Make room right of a horizontal category axis for the › chevron (and give it back when done). */
845
+ function reserveRightSpace(chart, axis, st, want) {
846
+ if (want && axis.horiz) {
847
+ const free = chart.chartWidth - (axis.left + axis.width);
848
+ const need = Math.ceil(CHIP_ROOM - free);
849
+ if (need > 0) {
850
+ st.reservedRight += need;
851
+ const spacingRight = (chart.spacing?.[1] ?? 10) + need;
852
+ schedule(chart, st, () => chart.update({ chart: { spacingRight } }, true, false, false), 'space');
853
+ }
854
+ }
855
+ else if (st.reservedRight > 0) {
856
+ const spacingRight = Math.max(0, (chart.spacing?.[1] ?? 10) - st.reservedRight);
857
+ st.reservedRight = 0;
858
+ schedule(chart, st, () => chart.update({ chart: { spacingRight } }, true, false, false), 'space');
859
+ }
860
+ }
861
+ function getState(chart) {
862
+ let st = chart[STATE];
863
+ if (!st) {
864
+ st = {
865
+ start: 0,
866
+ total: 0,
867
+ pageSize: 0,
868
+ active: false,
869
+ pausedByZoom: false,
870
+ panned: false,
871
+ events: false,
872
+ xs: [],
873
+ applied: null,
874
+ queue: new Map(),
875
+ reservedRight: 0,
876
+ wheelAcc: 0,
877
+ axisRegion: null,
878
+ root: null,
879
+ chips: null,
880
+ fades: null,
881
+ lastEmitted: '',
882
+ nextSource: null,
883
+ nextDirection: undefined,
884
+ lastShown: false,
885
+ cleanup: [],
886
+ };
887
+ chart[STATE] = st;
888
+ attachListeners(chart, st);
889
+ }
890
+ return st;
891
+ }
892
+ /** Re-evaluate pagination for a chart. Called on every render. */
893
+ function update(chart) {
894
+ if (!chart?.container || chart.renderer?.forExport || chart.options?.chart?.forExport)
895
+ return;
896
+ const axis = chart.xAxis?.[0];
897
+ const cfg = axis ? readConfig(chart) : null;
898
+ const existing = chart[STATE];
899
+ const xs = cfg && axis ? collectXs(chart, axis, cfg) : null;
900
+ if (!cfg || !axis || !xs || xs.length < 2) {
901
+ if (existing) {
902
+ existing.pausedByZoom = false;
903
+ deactivate(chart, existing);
904
+ }
905
+ return;
906
+ }
907
+ const st = getState(chart);
908
+ const pageSize = Math.min(autoPageSize(chart, axis, cfg), xs.length);
909
+ const ext = axis.getExtremes();
910
+ // Highcharts panning (chart.panning) moved our window: follow it — it is still
911
+ // pagination, not a zoom. It snaps to whole categories when the pointer is released.
912
+ if (st.active &&
913
+ axis.eventArgs?.trigger === 'pan' &&
914
+ ext.userMin !== undefined &&
915
+ !(st.applied && ext.userMin === st.applied.min && ext.userMax === st.applied.max)) {
916
+ let nearest = 0;
917
+ for (let i = 1; i < xs.length; i++)
918
+ if (Math.abs(xs[i] - ext.userMin) < Math.abs(xs[nearest] - ext.userMin))
919
+ nearest = i;
920
+ const before = st.start;
921
+ st.xs = xs;
922
+ st.total = xs.length;
923
+ st.start = nearest;
924
+ clampStart(st);
925
+ st.applied = { min: ext.userMin, max: ext.userMax };
926
+ st.panned = true;
927
+ if (st.start !== before) {
928
+ st.nextSource = 'pan';
929
+ st.nextDirection = st.start > before ? 'next' : 'previous';
930
+ }
931
+ }
932
+ // A range set by the user (drag-zoom) or the consumer (setExtremes / axis min-max)
933
+ // always wins over pagination; it resumes once that range is cleared.
934
+ const hasUserRange = ext.userMin !== undefined || ext.userMax !== undefined;
935
+ const ownRange = !!st.applied && ext.userMin === st.applied.min && ext.userMax === st.applied.max;
936
+ const userZoomed = (hasUserRange && !ownRange) || axis.options?.min != null || axis.options?.max != null;
937
+ if (pageSize >= xs.length || userZoomed) {
938
+ st.pausedByZoom = userZoomed;
939
+ deactivate(chart, st);
940
+ return;
941
+ }
942
+ if (!st.total)
943
+ st.start = cfg.start; // first time this chart paginates
944
+ st.events = isEventAxis(chart, axis);
945
+ st.xs = xs;
946
+ st.total = xs.length;
947
+ st.pageSize = pageSize;
948
+ clampStart(st);
949
+ st.active = true;
950
+ st.pausedByZoom = false;
951
+ let dirty = false;
952
+ if (cfg.fixedValueAxis) {
953
+ for (const s of chart.series) {
954
+ if (s.xAxis === axis && !s.options.getExtremesFromAll) {
955
+ s.options.getExtremesFromAll = true;
956
+ s.isDirty = true;
957
+ s.isDirtyData = true;
958
+ dirty = true;
959
+ }
960
+ }
961
+ }
962
+ const want = windowExtremes(st);
963
+ if (!st.panned && (dirty || ext.userMin !== want.min || ext.userMax !== want.max)) {
964
+ schedule(chart, st, () => apply(chart, st));
965
+ }
966
+ reserveRightSpace(chart, axis, st, true);
967
+ layout(chart, axis, st, cfg);
968
+ emitChange(chart, st);
969
+ }
970
+ const REGISTERED = Symbol.for('nile.chartPagination.registered');
971
+ /**
972
+ * Register category-axis pagination on a Highcharts instance. Idempotent.
973
+ * Called once from `highcharts-provider.ts`.
974
+ */
975
+ export function registerNileChartPagination(H) {
976
+ if (!H?.addEvent || !H?.Chart || H[REGISTERED])
977
+ return;
978
+ H[REGISTERED] = true;
979
+ // chart.zoomType / chart.panning / chart.panKey from the element's config (or
980
+ // `zoom-type` / `panning` / `pan-key` attributes) → Highcharts options, before
981
+ // the chart is constructed. `this.renderTo` is already set at 'init'.
982
+ H.addEvent(H.Chart, 'init', function (e) {
983
+ try {
984
+ const opts = e?.args?.[0];
985
+ if (opts && typeof opts === 'object')
986
+ injectNavigation(this, opts);
987
+ }
988
+ catch {
989
+ /* never block chart creation */
990
+ }
991
+ });
992
+ H.addEvent(H.Chart, 'render', function () {
993
+ rendering++;
994
+ try {
995
+ update(this);
996
+ valueUpdate(this);
997
+ }
998
+ catch (err) {
999
+ // Pagination is an enhancement — never break a chart over it.
1000
+ // eslint-disable-next-line no-console
1001
+ console.warn('[nile-visualization] chart pagination skipped:', err);
1002
+ }
1003
+ finally {
1004
+ rendering--;
1005
+ }
1006
+ });
1007
+ H.addEvent(H.Chart, 'destroy', function () {
1008
+ const vs = this[VSTATE];
1009
+ if (vs) {
1010
+ vs.cleanup.forEach((fn) => fn());
1011
+ vs.root?.remove();
1012
+ delete this[VSTATE];
1013
+ }
1014
+ const st = this[STATE];
1015
+ if (!st)
1016
+ return;
1017
+ st.cleanup.forEach((fn) => fn());
1018
+ st.cleanup = [];
1019
+ st.root?.remove();
1020
+ delete this[STATE];
1021
+ });
1022
+ }
1023
+ const ZOOM_TYPES = ['x', 'y', 'xy'];
1024
+ const PAN_KEYS = ['alt', 'ctrl', 'meta', 'shift'];
1025
+ /** Resolve chart.zoomType / chart.panning / chart.panKey for a chart about to be built. */
1026
+ function readNavigation(chart) {
1027
+ const hosts = hostsOf(chart);
1028
+ const out = {};
1029
+ // Config: outer <nile-chart> first, inner chart wins.
1030
+ for (const host of [...hosts].reverse()) {
1031
+ const c = host.config;
1032
+ const src = c?.chart ?? c;
1033
+ if (!src || typeof src !== 'object')
1034
+ continue;
1035
+ if (ZOOM_TYPES.includes(src.zoomType))
1036
+ out.zoomType = src.zoomType;
1037
+ if (src.panning !== undefined && src.panning !== null) {
1038
+ out.panning =
1039
+ typeof src.panning === 'object'
1040
+ ? {
1041
+ enabled: src.panning.enabled !== false,
1042
+ ...(ZOOM_TYPES.includes(src.panning.type) ? { type: src.panning.type } : {}),
1043
+ }
1044
+ : { enabled: !!src.panning };
1045
+ }
1046
+ if (PAN_KEYS.includes(src.panKey))
1047
+ out.panKey = src.panKey;
1048
+ }
1049
+ // Attributes win.
1050
+ const z = hostAttr(hosts, 'zoom-type');
1051
+ if (z !== null && ZOOM_TYPES.includes(z))
1052
+ out.zoomType = z;
1053
+ const pan = hostAttr(hosts, 'panning');
1054
+ if (pan !== null)
1055
+ out.panning = { ...(out.panning ?? {}), enabled: pan !== 'false' && pan !== 'off' };
1056
+ const key = hostAttr(hosts, 'pan-key');
1057
+ if (key !== null && PAN_KEYS.includes(key))
1058
+ out.panKey = key;
1059
+ return out;
1060
+ }
1061
+ function injectNavigation(chart, opts) {
1062
+ const nav = readNavigation(chart);
1063
+ if (!nav.zoomType && !nav.panning && !nav.panKey)
1064
+ return;
1065
+ opts.chart = opts.chart ?? {};
1066
+ if (nav.zoomType)
1067
+ opts.chart.zooming = { ...(opts.chart.zooming ?? {}), type: nav.zoomType };
1068
+ if (nav.panning) {
1069
+ // Default pan direction: x, or xy when the value axis is paginated too.
1070
+ const valuePaged = Number(resolvePagination(chart).valueSpan) > 0;
1071
+ opts.chart.panning = {
1072
+ ...(typeof opts.chart.panning === 'object' ? opts.chart.panning : {}),
1073
+ enabled: nav.panning.enabled,
1074
+ type: nav.panning.type ?? (valuePaged ? 'xy' : 'x'),
1075
+ };
1076
+ }
1077
+ if (nav.panKey)
1078
+ opts.chart.panKey = nav.panKey;
1079
+ }
1080
+ /** Programmatic paging for a live chart (e.g. from a component method). */
1081
+ export function pageChart(chart, delta) {
1082
+ move(chart, delta, 'api');
1083
+ }
1084
+ /** Programmatic value-axis paging: move the value window by `delta` data units. */
1085
+ export function pageChartValues(chart, delta) {
1086
+ valuePan(chart, delta, 'api');
1087
+ }
1088
+ const VSTATE = Symbol('nileValuePager');
1089
+ /** Series drawn up from a zero baseline — the value window should include 0 for these. Range types (columnrange, arearange, dumbbell…) float, so they don't. */
1090
+ const ZERO_BASED = new Set([
1091
+ 'column',
1092
+ 'bar',
1093
+ 'columnpyramid',
1094
+ 'cylinder',
1095
+ 'waterfall',
1096
+ 'lollipop',
1097
+ 'histogram',
1098
+ 'area',
1099
+ 'areaspline',
1100
+ 'streamgraph',
1101
+ 'variwide',
1102
+ ]);
1103
+ function readValueConfig(chart) {
1104
+ const o = resolvePagination(chart);
1105
+ const en = o.enabled;
1106
+ if (en === false || en === 'off' || en === 'false')
1107
+ return null;
1108
+ const span = Number(o.valueSpan);
1109
+ if (!Number.isFinite(span) || span <= 0)
1110
+ return null;
1111
+ const start = o.valueStart;
1112
+ return {
1113
+ span,
1114
+ start: Number.isFinite(start) ? Number(start) : undefined,
1115
+ chips: o.chips === 'always' ? 'always' : 'hover',
1116
+ };
1117
+ }
1118
+ function valueOff(chart) {
1119
+ const vs = chart[VSTATE];
1120
+ if (!vs || !vs.active)
1121
+ return;
1122
+ vs.active = false;
1123
+ if (vs.root)
1124
+ vs.root.hidden = true;
1125
+ if (vs.reservedRight > 0 || vs.reservedTop > 0) {
1126
+ const spacingRight = Math.max(0, (chart.spacing?.[1] ?? 10) - vs.reservedRight);
1127
+ const spacingTop = Math.max(0, (chart.spacing?.[0] ?? 10) - vs.reservedTop);
1128
+ vs.reservedRight = 0;
1129
+ vs.reservedTop = 0;
1130
+ queueMicrotask(() => chart.container && chart.update({ chart: { spacingRight, spacingTop } }, true, false, false));
1131
+ }
1132
+ const axis = chart.yAxis?.[0];
1133
+ if (axis) {
1134
+ vs.queued = true;
1135
+ queueMicrotask(() => {
1136
+ vs.queued = false;
1137
+ if (chart.container && !vs.active)
1138
+ axis.setExtremes(undefined, undefined, true, false, { trigger: 'nile-pagination' });
1139
+ });
1140
+ }
1141
+ }
1142
+ function valueApplySoon(chart, vs) {
1143
+ if (vs.queued)
1144
+ return;
1145
+ vs.queued = true;
1146
+ queueMicrotask(() => {
1147
+ vs.queued = false;
1148
+ if (!chart.container || !vs.active)
1149
+ return;
1150
+ chart.yAxis[0].setExtremes(vs.start, vs.start + vs.span, true, false, {
1151
+ trigger: 'nile-pagination',
1152
+ });
1153
+ });
1154
+ }
1155
+ function valuePan(chart, dv, source = 'api') {
1156
+ const vs = chart?.[VSTATE];
1157
+ if (!Number.isFinite(dv))
1158
+ return false;
1159
+ if (!vs || !vs.active)
1160
+ return false;
1161
+ const next = Math.max(vs.lo, Math.min(vs.hi - vs.span, vs.start + dv));
1162
+ if (Math.abs(next - vs.start) < 1e-9)
1163
+ return false;
1164
+ vs.nextDirection = next > vs.start ? 'higher' : 'lower';
1165
+ vs.nextSource = source;
1166
+ vs.start = next;
1167
+ if (rendering > 0)
1168
+ valueApplySoon(chart, vs);
1169
+ else
1170
+ chart.yAxis[0].setExtremes(vs.start, vs.start + vs.span, true, false, {
1171
+ trigger: 'nile-pagination',
1172
+ });
1173
+ return true;
1174
+ }
1175
+ function valueState(chart) {
1176
+ let vs = chart[VSTATE];
1177
+ if (vs)
1178
+ return vs;
1179
+ vs = {
1180
+ nextSource: null,
1181
+ nextDirection: undefined,
1182
+ lastEmitted: '',
1183
+ active: false,
1184
+ lo: 0,
1185
+ hi: 0,
1186
+ start: 0,
1187
+ span: 0,
1188
+ started: false,
1189
+ queued: false,
1190
+ reservedRight: 0,
1191
+ reservedTop: 0,
1192
+ region: null,
1193
+ root: null,
1194
+ chips: null,
1195
+ fades: null,
1196
+ cleanup: [],
1197
+ };
1198
+ chart[VSTATE] = vs;
1199
+ const st = vs;
1200
+ const c = chart.container;
1201
+ const local = (ev) => {
1202
+ const b = c.getBoundingClientRect();
1203
+ return { x: ev.clientX - b.left, y: ev.clientY - b.top };
1204
+ };
1205
+ const inRegion = (x, y) => {
1206
+ const r = st.region;
1207
+ return !!r && x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
1208
+ };
1209
+ const onMove = (ev) => {
1210
+ if (!st.root || !st.active)
1211
+ return;
1212
+ const { x, y } = local(ev);
1213
+ st.root.classList.toggle('hot', inRegion(x, y));
1214
+ };
1215
+ const onLeave = () => st.root?.classList.remove('hot');
1216
+ const onWheel = (ev) => {
1217
+ if (!st.active || ev.ctrlKey)
1218
+ return;
1219
+ const axis = chart.yAxis?.[0];
1220
+ if (!axis)
1221
+ return;
1222
+ const { x, y } = local(ev);
1223
+ const overAxis = inRegion(x, y);
1224
+ const overPlot = x >= chart.plotLeft &&
1225
+ x <= chart.plotLeft + chart.plotWidth &&
1226
+ y >= chart.plotTop &&
1227
+ y <= chart.plotTop + chart.plotHeight;
1228
+ const scale = ev.deltaMode === 1 ? 16 : ev.deltaMode === 2 ? axis.len || 300 : 1;
1229
+ let d = 0;
1230
+ if (axis.horiz) {
1231
+ // Horizontal value axis (bar): sideways gesture over the plot, any gesture over the numbers.
1232
+ if (overAxis)
1233
+ d = Math.abs(ev.deltaX) > Math.abs(ev.deltaY) ? ev.deltaX : ev.deltaY;
1234
+ else if (overPlot)
1235
+ d = ev.deltaX || (ev.shiftKey ? ev.deltaY : 0);
1236
+ if (axis.reversed)
1237
+ d = -d;
1238
+ }
1239
+ else if (overAxis) {
1240
+ // Vertical value axis: only over its own numbers, so page scrolling over the plot is untouched.
1241
+ d = axis.reversed ? ev.deltaY : -ev.deltaY;
1242
+ }
1243
+ if (!d)
1244
+ return;
1245
+ if (valuePan(chart, (d * scale * st.span) / Math.max(1, axis.len), 'wheel'))
1246
+ ev.preventDefault();
1247
+ };
1248
+ c.addEventListener('mousemove', onMove);
1249
+ c.addEventListener('mouseleave', onLeave);
1250
+ c.addEventListener('wheel', onWheel, { passive: false });
1251
+ vs.cleanup.push(() => {
1252
+ c.removeEventListener('mousemove', onMove);
1253
+ c.removeEventListener('mouseleave', onLeave);
1254
+ c.removeEventListener('wheel', onWheel);
1255
+ });
1256
+ return vs;
1257
+ }
1258
+ function valueOverlay(chart, vs) {
1259
+ if (vs.root && vs.root.isConnected && vs.root.parentNode === chart.container)
1260
+ return;
1261
+ const doc = chart.container.ownerDocument;
1262
+ const root = doc.createElement('div');
1263
+ root.className = 'nile-pg nile-pg-value';
1264
+ root.setAttribute('part', 'value-pagination');
1265
+ const style = doc.createElement('style');
1266
+ style.textContent = STYLE;
1267
+ root.appendChild(style);
1268
+ const mkFade = (side) => {
1269
+ const f = doc.createElement('i');
1270
+ f.className = `nile-pg-fade ${side}`;
1271
+ root.appendChild(f);
1272
+ return f;
1273
+ };
1274
+ const mkChip = (side) => {
1275
+ const b = doc.createElement('button');
1276
+ b.type = 'button';
1277
+ b.className = `nile-pg-chip ${side}`;
1278
+ b.setAttribute('part', `pagination-chip value-chip-${side === 'low' ? 'lower' : 'higher'}`);
1279
+ b.addEventListener('click', (ev) => {
1280
+ ev.stopPropagation();
1281
+ valuePan(chart, side === 'low' ? -vs.span : vs.span, 'chip');
1282
+ });
1283
+ b.addEventListener('mousedown', (ev) => ev.stopPropagation());
1284
+ b.addEventListener('pointerdown', (ev) => ev.stopPropagation());
1285
+ root.appendChild(b);
1286
+ return b;
1287
+ };
1288
+ vs.fades = { low: mkFade('low'), high: mkFade('high') };
1289
+ vs.chips = { low: mkChip('low'), high: mkChip('high') };
1290
+ chart.container.appendChild(root);
1291
+ vs.root = root;
1292
+ }
1293
+ function valueLayout(chart, axis, vs, chipsMode) {
1294
+ valueOverlay(chart, vs);
1295
+ const chips = vs.chips;
1296
+ const fades = vs.fades;
1297
+ const root = vs.root;
1298
+ const W = chart.chartWidth;
1299
+ const H = chart.chartHeight;
1300
+ const box = labelBox(axis);
1301
+ const CHIP = 20;
1302
+ if (axis.horiz) {
1303
+ const rowH = box ? box.h : 18;
1304
+ const rowY = box ? box.y : axis.top + axis.height + 4;
1305
+ const cy = Math.min(H - 11, Math.max(11, rowY + rowH / 2));
1306
+ const left = axis.left;
1307
+ const right = left + axis.width;
1308
+ const [l, r] = axis.reversed ? ['high', 'low'] : ['low', 'high'];
1309
+ place(fades[l], {
1310
+ left: `${left}px`,
1311
+ top: `${rowY}px`,
1312
+ width: `${FADE + 8}px`,
1313
+ height: `${rowH}px`,
1314
+ });
1315
+ place(fades[r], {
1316
+ left: `${right - FADE - 8}px`,
1317
+ top: `${rowY}px`,
1318
+ width: `${FADE + 8}px`,
1319
+ height: `${rowH}px`,
1320
+ });
1321
+ fades[l].className = `nile-pg-fade ${l} f-left`;
1322
+ fades[r].className = `nile-pg-fade ${r} f-right`;
1323
+ // Just outside the ends of the number row (room on the right is reserved below).
1324
+ // ‹ takes the place of the first number (hidden while paging — see valueUpdate).
1325
+ const lx = Math.max(2, left - CHIP / 2);
1326
+ const rx = W - right >= CHIP + 4 ? right + 2 : right - CHIP - 2;
1327
+ place(chips[l], { left: `${lx}px`, top: `${cy}px`, transform: 'translateY(-50%)' });
1328
+ place(chips[r], {
1329
+ left: `${Math.min(W - CHIP - 2, rx)}px`,
1330
+ top: `${cy}px`,
1331
+ transform: 'translateY(-50%)',
1332
+ });
1333
+ setChip(chips[l], 'left');
1334
+ setChip(chips[r], 'right');
1335
+ vs.region = {
1336
+ x: Math.min(lx, left) - 4,
1337
+ y: rowY - 6,
1338
+ w: Math.max(rx + CHIP, right) - Math.min(lx, left) + 8,
1339
+ h: rowH + 12,
1340
+ };
1341
+ }
1342
+ else {
1343
+ const blockX = box ? box.x : axis.opposite ? axis.left + axis.width : 0;
1344
+ const blockW = box ? box.w : axis.opposite ? W - blockX : axis.left;
1345
+ const cx = Math.max(CHIP / 2 + 2, blockX + blockW / 2);
1346
+ const top = axis.top;
1347
+ const bottom = top + axis.height;
1348
+ const [t, b] = axis.reversed ? ['low', 'high'] : ['high', 'low'];
1349
+ const fh = Math.min(FADE, (bottom - top) / 3);
1350
+ place(fades[t], {
1351
+ left: `${blockX}px`,
1352
+ top: `${top - 8}px`,
1353
+ width: `${blockW}px`,
1354
+ height: `${fh}px`,
1355
+ });
1356
+ place(fades[b], {
1357
+ left: `${blockX}px`,
1358
+ top: `${bottom - fh + 8}px`,
1359
+ width: `${blockW}px`,
1360
+ height: `${fh}px`,
1361
+ });
1362
+ fades[t].className = `nile-pg-fade ${t} f-top`;
1363
+ fades[b].className = `nile-pg-fade ${b} f-bottom`;
1364
+ // Mirrors the horizontal case: the lower-values chevron takes the place of the
1365
+ // first (lowest) number, which is hidden while it shows; the higher-values
1366
+ // chevron sits just past the last number (room above is reserved in valueUpdate).
1367
+ const lowY = axis.reversed ? top + 2 : bottom - 2;
1368
+ const highY = axis.reversed ? Math.min(H - 11, bottom + 14) : Math.max(11, top - 14);
1369
+ place(chips.low, { left: `${cx}px`, top: `${lowY}px`, transform: 'translate(-50%,-50%)' });
1370
+ place(chips.high, { left: `${cx}px`, top: `${highY}px`, transform: 'translate(-50%,-50%)' });
1371
+ setChip(chips[t], 'up');
1372
+ setChip(chips[b], 'down');
1373
+ vs.region = { x: blockX - 4, y: top - 26, w: blockW + 8, h: bottom - top + 40 };
1374
+ }
1375
+ const eps = vs.span * 1e-6;
1376
+ const lower = vs.start > vs.lo + eps;
1377
+ const higher = vs.start + vs.span < vs.hi - eps;
1378
+ const fmt = (v) => (Math.abs(v) >= 100 ? Math.round(v) : Math.round(v * 100) / 100).toLocaleString();
1379
+ chips.low.setAttribute('aria-label', lower ? `Show lower values (below ${fmt(vs.start)})` : 'No lower values');
1380
+ chips.high.setAttribute('aria-label', higher ? `Show higher values (above ${fmt(vs.start + vs.span)})` : 'No higher values');
1381
+ chips.low.title = lower ? `Below ${fmt(vs.start)}` : '';
1382
+ chips.high.title = higher ? `Above ${fmt(vs.start + vs.span)}` : '';
1383
+ chips.low.tabIndex = lower ? 0 : -1;
1384
+ chips.high.tabIndex = higher ? 0 : -1;
1385
+ root.classList.toggle('more-low', lower);
1386
+ root.classList.toggle('more-high', higher);
1387
+ root.classList.toggle('always', chipsMode === 'always');
1388
+ root.hidden = false;
1389
+ }
1390
+ /** Re-evaluate value-axis paging. Called on every render, after the category pager. */
1391
+ function valueUpdate(chart) {
1392
+ if (!chart?.container || chart.renderer?.forExport || chart.options?.chart?.forExport)
1393
+ return;
1394
+ const axis = chart.yAxis?.[0];
1395
+ const cfg = axis ? readValueConfig(chart) : null;
1396
+ const eligible = !!cfg &&
1397
+ !chart.polar &&
1398
+ !chart.angular &&
1399
+ !!chart.series?.length &&
1400
+ !chart.series.some((s) => EXCLUDED_TYPES.has(s.type)) &&
1401
+ !isCategoryAxis(axis) &&
1402
+ !isEventAxis(chart, chart.xAxis?.[0]); // timelines have no value axis to page
1403
+ if (!eligible)
1404
+ return valueOff(chart);
1405
+ const dMin = Number(axis.dataMin);
1406
+ const dMax = Number(axis.dataMax);
1407
+ if (!Number.isFinite(dMin) || !Number.isFinite(dMax))
1408
+ return valueOff(chart);
1409
+ const fromZero = chart.series.some((s) => s.yAxis === axis && ZERO_BASED.has(s.type));
1410
+ const lo = fromZero ? Math.min(0, dMin) : dMin;
1411
+ const hi = (fromZero ? Math.max(0, dMax) : dMax) + (dMax - lo) * 0.02;
1412
+ const span = cfg.span;
1413
+ if (span >= hi - lo)
1414
+ return valueOff(chart);
1415
+ const vs = valueState(chart);
1416
+ vs.lo = lo;
1417
+ vs.hi = hi;
1418
+ vs.span = span;
1419
+ // Highcharts panning on the value axis (panning type 'y' / 'xy'): follow it.
1420
+ const extNow = axis.getExtremes();
1421
+ const yPanned = vs.started &&
1422
+ axis.eventArgs?.trigger === 'pan' &&
1423
+ extNow.userMin !== undefined &&
1424
+ Math.abs(extNow.userMin - vs.start) > span * 1e-9;
1425
+ if (yPanned) {
1426
+ vs.nextDirection = extNow.userMin > vs.start ? 'higher' : 'lower';
1427
+ vs.nextSource = 'pan';
1428
+ vs.start = extNow.userMin;
1429
+ }
1430
+ if (!vs.started) {
1431
+ vs.started = true;
1432
+ // Default window: from the bottom of the data, or centred on the zero line when
1433
+ // the data crosses it (so a +/- chart doesn't open on an empty far-negative band).
1434
+ vs.start = cfg.start ?? (lo < 0 && hi > 0 ? -span / 2 : lo);
1435
+ }
1436
+ vs.start = Math.max(lo, Math.min(hi - span, vs.start));
1437
+ vs.active = true;
1438
+ // Continuous window: don't let Highcharts snap the ends out to the next tick.
1439
+ let dirty = false;
1440
+ if (axis.options.startOnTick !== false || axis.options.endOnTick !== false) {
1441
+ axis.options.startOnTick = false;
1442
+ axis.options.endOnTick = false;
1443
+ axis.isDirty = true;
1444
+ dirty = true;
1445
+ }
1446
+ // Horizontal value axis: while ‹ is showing it takes the first number's place,
1447
+ // so hide that label; at the bottom of the range (no ‹) the label comes back.
1448
+ const showFirst = vs.start <= lo + span * 1e-6;
1449
+ if ((axis.options.showFirstLabel !== false) !== showFirst) {
1450
+ axis.options.showFirstLabel = showFirst;
1451
+ axis.isDirty = true;
1452
+ dirty = true;
1453
+ }
1454
+ // Make room past the last number for the higher-values chevron.
1455
+ if (axis.horiz) {
1456
+ const need = Math.ceil(CHIP_ROOM - (chart.chartWidth - (axis.left + axis.width)));
1457
+ if (need > 0) {
1458
+ vs.reservedRight += need;
1459
+ const spacingRight = (chart.spacing?.[1] ?? 10) + need;
1460
+ queueMicrotask(() => chart.container && chart.update({ chart: { spacingRight } }, true, false, false));
1461
+ }
1462
+ }
1463
+ else if (!axis.reversed) {
1464
+ const need = Math.ceil(CHIP_ROOM - axis.top);
1465
+ if (need > 0) {
1466
+ vs.reservedTop += need;
1467
+ const spacingTop = (chart.spacing?.[0] ?? 10) + need;
1468
+ queueMicrotask(() => chart.container && chart.update({ chart: { spacingTop } }, true, false, false));
1469
+ }
1470
+ }
1471
+ const ext = axis.getExtremes();
1472
+ if (!yPanned && (dirty || ext.userMin !== vs.start || ext.userMax !== vs.start + span))
1473
+ valueApplySoon(chart, vs);
1474
+ valueLayout(chart, axis, vs, cfg.chips);
1475
+ emitValueChange(chart, vs);
1476
+ }
1477
+ function emitValueChange(chart, vs) {
1478
+ const key = `${vs.start}|${vs.span}|${vs.lo}|${vs.hi}`;
1479
+ if (key === vs.lastEmitted)
1480
+ return;
1481
+ const first = vs.lastEmitted === '';
1482
+ vs.lastEmitted = key;
1483
+ const source = vs.nextSource ?? (first ? 'init' : 'auto');
1484
+ const direction = vs.nextSource ? vs.nextDirection : undefined;
1485
+ vs.nextSource = null;
1486
+ vs.nextDirection = undefined;
1487
+ const eps = vs.span * 1e-6;
1488
+ const detail = {
1489
+ chart,
1490
+ min: vs.start,
1491
+ max: vs.start + vs.span,
1492
+ span: vs.span,
1493
+ dataMin: vs.lo,
1494
+ dataMax: vs.hi,
1495
+ source,
1496
+ ...(direction ? { direction } : {}),
1497
+ hasLower: vs.start > vs.lo + eps,
1498
+ hasHigher: vs.start + vs.span < vs.hi - eps,
1499
+ };
1500
+ chart.container?.dispatchEvent(new CustomEvent(NILE_CHART_VALUE_PAGE_CHANGE, { bubbles: true, composed: true, detail }));
1501
+ }
1502
+ //# sourceMappingURL=chart-pagination.js.map