@crysound/crychart 1.0.6 → 1.0.8

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.
package/dist/crychart.js CHANGED
@@ -844,6 +844,262 @@ function readPagedValue(view, absoluteIndex) {
844
844
  return page[absoluteIndex - pageIndex * view.pageSize];
845
845
  }
846
846
 
847
+ // src/data-order.ts
848
+ var caches = /* @__PURE__ */ new WeakMap();
849
+ function resetContent(state) {
850
+ state.epoch = -1;
851
+ state.first = 0;
852
+ state.next = 0;
853
+ state.lastIndex = -1;
854
+ state.lastValue = NaN;
855
+ state.invalid = -1;
856
+ state.decrease = -1;
857
+ state.nonIncrease = -1;
858
+ state.lastScanned = 0;
859
+ state.lastFast = 0;
860
+ state.lastEndpoints = 0;
861
+ }
862
+ function createState() {
863
+ return {
864
+ epoch: -1,
865
+ first: 0,
866
+ next: 0,
867
+ lastIndex: -1,
868
+ lastValue: NaN,
869
+ invalid: -1,
870
+ decrease: -1,
871
+ nonIncrease: -1,
872
+ scanned: 0,
873
+ lastScanned: 0,
874
+ fast: 0,
875
+ lastFast: 0,
876
+ endpoints: 0,
877
+ lastEndpoints: 0,
878
+ cacheHits: 0,
879
+ rebuilds: 0
880
+ };
881
+ }
882
+ function cacheFor(dataSet) {
883
+ let cache = caches.get(dataSet);
884
+ if (!cache) {
885
+ cache = { epoch: dataSet.getContentEpoch(), columns: /* @__PURE__ */ new Map() };
886
+ caches.set(dataSet, cache);
887
+ const owned2 = cache;
888
+ dataSet.onChange((current) => {
889
+ if (current.isDisposed()) {
890
+ owned2.columns.clear();
891
+ caches.delete(current);
892
+ return;
893
+ }
894
+ const epoch = current.getContentEpoch();
895
+ if (owned2.epoch !== epoch) {
896
+ for (const state of owned2.columns.values()) resetContent(state);
897
+ owned2.epoch = epoch;
898
+ }
899
+ });
900
+ }
901
+ return cache;
902
+ }
903
+ function accept(state, index, value, first) {
904
+ if (!Number.isFinite(value)) state.invalid = index;
905
+ if (index > first && state.lastIndex === index - 1) {
906
+ if (value < state.lastValue) state.decrease = index;
907
+ if (value <= state.lastValue) state.nonIncrease = index;
908
+ }
909
+ state.lastValue = value;
910
+ state.lastIndex = index;
911
+ }
912
+ function certifiedIncreasing(run, firstOffset, lastOffset, a, b) {
913
+ if (!(run.step > 0) || !Number.isFinite(run.step) || !Number.isFinite(run.start) || !Number.isFinite(a) || !Number.isFinite(b) || !(b > a)) return false;
914
+ const magnitude = Math.max(Math.abs(run.start), Math.abs(firstOffset * run.step), Math.abs(lastOffset * run.step), Math.abs(a), Math.abs(b));
915
+ const separation = magnitude * Number.EPSILON * 8 + Number.MIN_VALUE * 8;
916
+ return run.step > separation;
917
+ }
918
+ function scanAffine(state, view, from, next) {
919
+ let low = view.runStart, high = view.runs.length;
920
+ while (low < high) {
921
+ const middle = low + Math.floor((high - low) / 2), run = view.runs[middle];
922
+ if (run.firstIndex + run.count <= from) low = middle + 1;
923
+ else high = middle;
924
+ }
925
+ for (let r = low; r < view.runs.length; r++) {
926
+ const run = view.runs[r], first = Math.max(from, run.firstIndex), end = Math.min(next, run.firstIndex + run.count);
927
+ if (first >= end) continue;
928
+ if (end - first > 1) {
929
+ const firstOffset = first - run.firstIndex, lastOffset = end - 1 - run.firstIndex;
930
+ const a = run.start + firstOffset * run.step, b = run.start + lastOffset * run.step;
931
+ state.endpoints += 2;
932
+ state.lastEndpoints += 2;
933
+ if (certifiedIncreasing(run, firstOffset, lastOffset, a, b)) {
934
+ accept(state, first, a, view.firstIndex);
935
+ state.lastIndex = end - 1;
936
+ state.lastValue = b;
937
+ state.fast += end - first;
938
+ state.lastFast += end - first;
939
+ continue;
940
+ }
941
+ }
942
+ for (let index = first; index < end; index++) accept(state, index, run.start + (index - run.firstIndex) * run.step, view.firstIndex);
943
+ state.scanned += end - first;
944
+ state.lastScanned += end - first;
945
+ }
946
+ }
947
+ function result(state, first, next, epoch) {
948
+ const finite2 = state.invalid < first;
949
+ return {
950
+ finite: finite2,
951
+ monotonic: finite2 && state.decrease <= first,
952
+ strict: finite2 && state.nonIncrease <= first,
953
+ sampleCount: next - first,
954
+ firstIndex: first,
955
+ nextIndex: next,
956
+ contentEpoch: epoch,
957
+ lastInvalidPointIndex: state.invalid,
958
+ lastDecreaseEdgeIndex: state.decrease,
959
+ lastNonIncreaseEdgeIndex: state.nonIncrease,
960
+ scannedSamples: state.scanned,
961
+ lastScannedSamples: state.lastScanned,
962
+ affineFastSamples: state.fast,
963
+ lastAffineFastSamples: state.lastFast,
964
+ affineEndpointEvaluations: state.endpoints,
965
+ lastAffineEndpointEvaluations: state.lastEndpoints,
966
+ cacheHits: state.cacheHits,
967
+ rebuilds: state.rebuilds
968
+ };
969
+ }
970
+ function getColumnOrder(dataSet, name) {
971
+ if (!(dataSet.hasColumn?.(name) ?? Object.prototype.hasOwnProperty.call(dataSet.schema, name))) throw new RangeError(`Unknown data column: ${name}`);
972
+ const epoch = dataSet.getContentEpoch(), next = dataSet.getNextSampleIndex(), first = next - dataSet.getSampleCount();
973
+ if (dataSet.isDisposed()) return result(createState(), first, next, epoch);
974
+ const cache = cacheFor(dataSet);
975
+ let state = cache.columns.get(name);
976
+ if (!state) {
977
+ state = createState();
978
+ cache.columns.set(name, state);
979
+ }
980
+ state.lastScanned = 0;
981
+ state.lastFast = 0;
982
+ state.lastEndpoints = 0;
983
+ if (state.epoch === epoch && state.first === first && state.next === next) {
984
+ state.cacheHits++;
985
+ return result(state, first, next, epoch);
986
+ }
987
+ if (state.epoch !== epoch || next < state.next || first < state.first) {
988
+ resetContent(state);
989
+ state.rebuilds++;
990
+ }
991
+ const from = Math.max(first, state.next);
992
+ if (from < next) {
993
+ const view = dataSet.getColumnRuns(name);
994
+ if (view.kind === "affine") scanAffine(state, view, from, next);
995
+ else if (view.kind === "paged") {
996
+ const cursor = new PagedColumnCursor(view, from);
997
+ while (cursor.values) {
998
+ const values = cursor.values, base = cursor.absoluteIndex - cursor.offset;
999
+ for (let i = cursor.offset, end = i + cursor.length; i < end; i++) accept(state, base + i, values[i], first);
1000
+ cursor.next();
1001
+ }
1002
+ state.scanned += next - from;
1003
+ state.lastScanned += next - from;
1004
+ } else {
1005
+ let absolute = view.firstIndex;
1006
+ for (const values of view.slices) {
1007
+ const start = Math.max(0, from - absolute);
1008
+ for (let i = start; i < values.length; i++) accept(state, absolute + i, values[i], first);
1009
+ absolute += values.length;
1010
+ }
1011
+ state.scanned += next - from;
1012
+ state.lastScanned += next - from;
1013
+ }
1014
+ }
1015
+ state.epoch = epoch;
1016
+ state.first = first;
1017
+ state.next = next;
1018
+ return result(state, first, next, epoch);
1019
+ }
1020
+ var finiteCaches = /* @__PURE__ */ new WeakMap();
1021
+ function getColumnFinite(dataSet, name) {
1022
+ if (!(dataSet.hasColumn?.(name) ?? Object.prototype.hasOwnProperty.call(dataSet.schema, name))) throw new RangeError(`Unknown data column: ${name}`);
1023
+ const epoch = dataSet.getContentEpoch(), next = dataSet.getNextSampleIndex(), first = next - dataSet.getSampleCount();
1024
+ const expected2 = { revision: dataSet.revision, epoch, first, next };
1025
+ let columns = finiteCaches.get(dataSet);
1026
+ if (!columns && !dataSet.isDisposed()) {
1027
+ columns = /* @__PURE__ */ new Map();
1028
+ finiteCaches.set(dataSet, columns);
1029
+ const owned2 = columns;
1030
+ dataSet.onChange((current) => {
1031
+ if (current.isDisposed()) {
1032
+ owned2.clear();
1033
+ finiteCaches.delete(current);
1034
+ }
1035
+ });
1036
+ }
1037
+ let state = columns?.get(name);
1038
+ if (!state) {
1039
+ state = { invalid: -1, scanned: 0, fullScans: 0, incrementalScans: 0, cacheHits: 0 };
1040
+ columns?.set(name, state);
1041
+ }
1042
+ const before = readSourceCertificate(dataSet, expected2);
1043
+ const delta = !before?.tainted && state.certificate ? certifySourceDelta(dataSet, state.certificate, expected2).delta : void 0;
1044
+ state.certificate = void 0;
1045
+ let from = first, scanned = 0;
1046
+ if (delta) {
1047
+ from = Math.max(first, delta.previous.next);
1048
+ if (delta.kind === "unchanged") state.cacheHits++;
1049
+ else state.incrementalScans++;
1050
+ } else {
1051
+ state.invalid = -1;
1052
+ state.fullScans++;
1053
+ }
1054
+ if (from < next && !dataSet.isDisposed()) {
1055
+ const view = dataSet.getColumnRuns(name);
1056
+ if (view.firstIndex !== first || view.count !== next - first) throw new RangeError("Finite source does not cover the retained window");
1057
+ if (view.kind === "dense") {
1058
+ let absolute = first;
1059
+ for (const values of view.slices) {
1060
+ const start = Math.max(0, from - absolute), end = Math.min(values.length, next - absolute);
1061
+ for (let i = start; i < end; i++) if (!Number.isFinite(values[i])) state.invalid = absolute + i;
1062
+ scanned += Math.max(0, end - start);
1063
+ absolute += values.length;
1064
+ }
1065
+ } else if (view.kind === "paged") {
1066
+ for (let index = from; index < next; ) {
1067
+ const pageIndex = Math.floor(index / view.pageSize), base = pageIndex * view.pageSize;
1068
+ const values = view.getPage(pageIndex), end = Math.min(next, base + view.pageSize);
1069
+ for (; index < end; index++) {
1070
+ if (!Number.isFinite(values?.[index - base])) state.invalid = index;
1071
+ scanned++;
1072
+ }
1073
+ }
1074
+ } else {
1075
+ for (let r = view.runStart; r < view.runs.length; r++) {
1076
+ const run = view.runs[r], begin = Math.max(from, run.firstIndex), end = Math.min(next, run.firstIndex + run.count);
1077
+ for (let index = begin; index < end; index++) if (!Number.isFinite(run.start + (index - run.firstIndex) * run.step)) state.invalid = index;
1078
+ scanned += Math.max(0, end - begin);
1079
+ }
1080
+ }
1081
+ if (scanned !== next - from) throw new RangeError("Finite source omitted retained values");
1082
+ }
1083
+ state.scanned += scanned;
1084
+ const after = readSourceCertificate(dataSet, expected2);
1085
+ const verifiedCurrent = dataSet.revision === expected2.revision && dataSet.getContentEpoch() === epoch && dataSet.getNextSampleIndex() === next && dataSet.getSampleCount() === next - first && before === after;
1086
+ state.certificate = verifiedCurrent && after && !after.tainted ? after : void 0;
1087
+ return {
1088
+ finite: verifiedCurrent && state.invalid < first,
1089
+ verifiedCurrent,
1090
+ sampleCount: next - first,
1091
+ firstIndex: first,
1092
+ nextIndex: next,
1093
+ contentEpoch: epoch,
1094
+ lastInvalidPointIndex: state.invalid,
1095
+ scannedSamples: state.scanned,
1096
+ lastScannedSamples: scanned,
1097
+ fullScans: state.fullScans,
1098
+ incrementalScans: state.incrementalScans,
1099
+ cacheHits: state.cacheHits
1100
+ };
1101
+ }
1102
+
847
1103
  // src/core/data.ts
848
1104
  function positiveInteger(value, name) {
849
1105
  if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive safe integer`);
@@ -1332,7 +1588,7 @@ var DataSetXY = class _DataSetXY {
1332
1588
  const name = range.key === void 0 ? [...this.columns].find(([, c]) => c.schema.pattern === "progressive" || c.schema.pattern === "regressive")?.[0] ?? (this.columns.has("xValues") ? "xValues" : "x") : String(range.key);
1333
1589
  const column = this.columns.get(name);
1334
1590
  if (!column) throw new RangeError(`Unknown data column: ${name}`);
1335
- [from, to] = this.findRange(column, Math.min(range.start, range.end), Math.max(range.start, range.end));
1591
+ [from, to] = this.findRange(name, column, Math.min(range.start, range.end), Math.max(range.start, range.end));
1336
1592
  }
1337
1593
  const data = {};
1338
1594
  const allocated = this.pagedOptions ? /* @__PURE__ */ new Set() : void 0;
@@ -1577,11 +1833,34 @@ var DataSetXY = class _DataSetXY {
1577
1833
  column.runStart = 0;
1578
1834
  invalidateSourceCertificate(this, this.deltaSourceHeader(), "column-materialized");
1579
1835
  }
1580
- findRange(column, min, max) {
1836
+ findRange(name, column, min, max) {
1581
1837
  let from = this.count, to = this.count;
1582
- if (Number.isNaN(min) || Number.isNaN(max)) return [from, to];
1838
+ if (this.count === 0 || Number.isNaN(min) || Number.isNaN(max)) return [from, to];
1839
+ const monotonic = getColumnOrder(this, name).monotonic;
1583
1840
  if (column.paged !== void 0) {
1584
1841
  const view = this.paged.getColumnView(column.paged), firstIndex = view.firstIndex, endIndex = firstIndex + view.count;
1842
+ if (monotonic) {
1843
+ const pageSize = view.pageSize;
1844
+ const valueAt = (index) => {
1845
+ const pageIndex = Math.floor(index / pageSize), page = view.getPage(pageIndex);
1846
+ if (!page) throw new Error("Missing retained page");
1847
+ return page[index - pageIndex * pageSize];
1848
+ };
1849
+ let low = firstIndex, high = endIndex;
1850
+ while (low < high) {
1851
+ const middle = low + Math.floor((high - low) / 2);
1852
+ if (valueAt(middle) < min) low = middle + 1;
1853
+ else high = middle;
1854
+ }
1855
+ const matchStart = low;
1856
+ high = endIndex;
1857
+ while (low < high) {
1858
+ const middle = low + Math.floor((high - low) / 2);
1859
+ if (valueAt(middle) <= max) low = middle + 1;
1860
+ else high = middle;
1861
+ }
1862
+ return matchStart < low ? [matchStart - firstIndex, low - firstIndex] : [this.count, this.count];
1863
+ }
1585
1864
  for (let index = firstIndex; index < endIndex; ) {
1586
1865
  const pageIndex = Math.floor(index / view.pageSize), page = view.getPage(pageIndex);
1587
1866
  if (!page) throw new Error("Missing retained page");
@@ -1596,6 +1875,47 @@ var DataSetXY = class _DataSetXY {
1596
1875
  }
1597
1876
  } else if (column.runs) {
1598
1877
  const firstIndex = this.nextIndex - this.count;
1878
+ if (monotonic) {
1879
+ let rFirst = this.findRun(column, firstIndex);
1880
+ const rEnd = column.runs.length;
1881
+ const runBounds = (r) => {
1882
+ const run = column.runs[r];
1883
+ const start = Math.max(firstIndex, run.firstIndex), end = Math.min(this.nextIndex, run.firstIndex + run.count);
1884
+ return { run, start, end, firstVal: run.start + (start - run.firstIndex) * run.step, lastVal: run.start + (end - 1 - run.firstIndex) * run.step };
1885
+ };
1886
+ let low = rFirst, high = rEnd;
1887
+ while (low < high) {
1888
+ const mid = low + Math.floor((high - low) / 2);
1889
+ if (runBounds(mid).lastVal < min) low = mid + 1;
1890
+ else high = mid;
1891
+ }
1892
+ const startRunIndex = low;
1893
+ if (startRunIndex >= rEnd) return [this.count, this.count];
1894
+ low = startRunIndex;
1895
+ high = rEnd;
1896
+ while (low < high) {
1897
+ const mid = low + Math.floor((high - low) / 2);
1898
+ if (runBounds(mid).firstVal <= max) low = mid + 1;
1899
+ else high = mid;
1900
+ }
1901
+ const endRunIndex = low - 1;
1902
+ if (endRunIndex < startRunIndex) return [this.count, this.count];
1903
+ const firstB = runBounds(startRunIndex);
1904
+ let sLow = firstB.start, sHigh = firstB.end;
1905
+ while (sLow < sHigh) {
1906
+ const mid = sLow + Math.floor((sHigh - sLow) / 2);
1907
+ if (firstB.run.start + (mid - firstB.run.firstIndex) * firstB.run.step < min) sLow = mid + 1;
1908
+ else sHigh = mid;
1909
+ }
1910
+ const lastB = runBounds(endRunIndex);
1911
+ let eLow = startRunIndex === endRunIndex ? sLow : lastB.start, eHigh = lastB.end;
1912
+ while (eLow < eHigh) {
1913
+ const mid = eLow + Math.floor((eHigh - eLow) / 2);
1914
+ if (lastB.run.start + (mid - lastB.run.firstIndex) * lastB.run.step <= max) eLow = mid + 1;
1915
+ else eHigh = mid;
1916
+ }
1917
+ return sLow < eLow ? [sLow - firstIndex, eLow - firstIndex] : [this.count, this.count];
1918
+ }
1599
1919
  for (let r = column.runStart; r < column.runs.length; r++) {
1600
1920
  const run = column.runs[r];
1601
1921
  const start = Math.max(firstIndex, run.firstIndex), end = Math.min(this.nextIndex, run.firstIndex + run.count);
@@ -1630,6 +1950,23 @@ var DataSetXY = class _DataSetXY {
1630
1950
  }
1631
1951
  } else {
1632
1952
  const first = Math.min(this.count, this.allocation - this.head);
1953
+ if (monotonic) {
1954
+ const denseAt = (i) => column.values[i < first ? this.head + i : i - first];
1955
+ let low = 0, high = this.count;
1956
+ while (low < high) {
1957
+ const middle = low + Math.floor((high - low) / 2);
1958
+ if (denseAt(middle) < min) low = middle + 1;
1959
+ else high = middle;
1960
+ }
1961
+ const matchStart = low;
1962
+ high = this.count;
1963
+ while (low < high) {
1964
+ const middle = low + Math.floor((high - low) / 2);
1965
+ if (denseAt(middle) <= max) low = middle + 1;
1966
+ else high = middle;
1967
+ }
1968
+ return matchStart < low ? [matchStart, low] : [this.count, this.count];
1969
+ }
1633
1970
  for (let i = 0; i < first; i++) {
1634
1971
  const value = column.values[this.head + i];
1635
1972
  if (value >= min && value <= max) {
@@ -4410,296 +4747,40 @@ var PolarAxisRadial = class extends Axis {
4410
4747
  const offset = strategy.getFormattingOffset(), degrees = offset === void 0 ? value : value + offset;
4411
4748
  return Number.isFinite(degrees) ? degrees.toFixed(0) : String(degrees);
4412
4749
  }
4413
- setNorth(degrees) {
4414
- if (!Number.isFinite(degrees)) throw new RangeError("North angle must be finite");
4415
- this.polarChart.setAngleOrigin(90 - (this.polarChart.getClockwise() ? -degrees : degrees));
4416
- return this;
4417
- }
4418
- getNorth(_unused) {
4419
- const angle = (90 - this.polarChart.getAngleOrigin()) * (this.polarChart.getClockwise() ? -1 : 1);
4420
- return angle === 0 ? 0 : angle;
4421
- }
4422
- setClockwise(value) {
4423
- const north = this.getNorth();
4424
- this.polarChart.setClockwise(value);
4425
- return this.setNorth(north);
4426
- }
4427
- getClockwise() {
4428
- return this.polarChart.getClockwise();
4429
- }
4430
- setTickStyle(value) {
4431
- this.tickStrategy.setMajorTickStyle(value);
4432
- return this;
4433
- }
4434
- getTickStyle() {
4435
- return this.tickStrategy.getMajorTickStyle();
4436
- }
4437
- setTickFormattingFunction(value) {
4438
- if (typeof value !== "function") throw new TypeError("Polar tick formatter must be a function");
4439
- this.tickFormattingFunction = value;
4440
- this.chart.invalidate();
4441
- return this;
4442
- }
4443
- getTickFormattingFunction() {
4444
- return this.tickFormattingFunction;
4445
- }
4446
- };
4447
-
4448
- // src/data-order.ts
4449
- var caches = /* @__PURE__ */ new WeakMap();
4450
- function resetContent(state) {
4451
- state.epoch = -1;
4452
- state.first = 0;
4453
- state.next = 0;
4454
- state.lastIndex = -1;
4455
- state.lastValue = NaN;
4456
- state.invalid = -1;
4457
- state.decrease = -1;
4458
- state.nonIncrease = -1;
4459
- state.lastScanned = 0;
4460
- state.lastFast = 0;
4461
- state.lastEndpoints = 0;
4462
- }
4463
- function createState() {
4464
- return {
4465
- epoch: -1,
4466
- first: 0,
4467
- next: 0,
4468
- lastIndex: -1,
4469
- lastValue: NaN,
4470
- invalid: -1,
4471
- decrease: -1,
4472
- nonIncrease: -1,
4473
- scanned: 0,
4474
- lastScanned: 0,
4475
- fast: 0,
4476
- lastFast: 0,
4477
- endpoints: 0,
4478
- lastEndpoints: 0,
4479
- cacheHits: 0,
4480
- rebuilds: 0
4481
- };
4482
- }
4483
- function cacheFor(dataSet) {
4484
- let cache = caches.get(dataSet);
4485
- if (!cache) {
4486
- cache = { epoch: dataSet.getContentEpoch(), columns: /* @__PURE__ */ new Map() };
4487
- caches.set(dataSet, cache);
4488
- const owned2 = cache;
4489
- dataSet.onChange((current) => {
4490
- if (current.isDisposed()) {
4491
- owned2.columns.clear();
4492
- caches.delete(current);
4493
- return;
4494
- }
4495
- const epoch = current.getContentEpoch();
4496
- if (owned2.epoch !== epoch) {
4497
- for (const state of owned2.columns.values()) resetContent(state);
4498
- owned2.epoch = epoch;
4499
- }
4500
- });
4501
- }
4502
- return cache;
4503
- }
4504
- function accept(state, index, value, first) {
4505
- if (!Number.isFinite(value)) state.invalid = index;
4506
- if (index > first && state.lastIndex === index - 1) {
4507
- if (value < state.lastValue) state.decrease = index;
4508
- if (value <= state.lastValue) state.nonIncrease = index;
4509
- }
4510
- state.lastValue = value;
4511
- state.lastIndex = index;
4512
- }
4513
- function certifiedIncreasing(run, firstOffset, lastOffset, a, b) {
4514
- if (!(run.step > 0) || !Number.isFinite(run.step) || !Number.isFinite(run.start) || !Number.isFinite(a) || !Number.isFinite(b) || !(b > a)) return false;
4515
- const magnitude = Math.max(Math.abs(run.start), Math.abs(firstOffset * run.step), Math.abs(lastOffset * run.step), Math.abs(a), Math.abs(b));
4516
- const separation = magnitude * Number.EPSILON * 8 + Number.MIN_VALUE * 8;
4517
- return run.step > separation;
4518
- }
4519
- function scanAffine(state, view, from, next) {
4520
- let low = view.runStart, high = view.runs.length;
4521
- while (low < high) {
4522
- const middle = low + Math.floor((high - low) / 2), run = view.runs[middle];
4523
- if (run.firstIndex + run.count <= from) low = middle + 1;
4524
- else high = middle;
4525
- }
4526
- for (let r = low; r < view.runs.length; r++) {
4527
- const run = view.runs[r], first = Math.max(from, run.firstIndex), end = Math.min(next, run.firstIndex + run.count);
4528
- if (first >= end) continue;
4529
- if (end - first > 1) {
4530
- const firstOffset = first - run.firstIndex, lastOffset = end - 1 - run.firstIndex;
4531
- const a = run.start + firstOffset * run.step, b = run.start + lastOffset * run.step;
4532
- state.endpoints += 2;
4533
- state.lastEndpoints += 2;
4534
- if (certifiedIncreasing(run, firstOffset, lastOffset, a, b)) {
4535
- accept(state, first, a, view.firstIndex);
4536
- state.lastIndex = end - 1;
4537
- state.lastValue = b;
4538
- state.fast += end - first;
4539
- state.lastFast += end - first;
4540
- continue;
4541
- }
4542
- }
4543
- for (let index = first; index < end; index++) accept(state, index, run.start + (index - run.firstIndex) * run.step, view.firstIndex);
4544
- state.scanned += end - first;
4545
- state.lastScanned += end - first;
4546
- }
4547
- }
4548
- function result(state, first, next, epoch) {
4549
- const finite2 = state.invalid < first;
4550
- return {
4551
- finite: finite2,
4552
- monotonic: finite2 && state.decrease <= first,
4553
- strict: finite2 && state.nonIncrease <= first,
4554
- sampleCount: next - first,
4555
- firstIndex: first,
4556
- nextIndex: next,
4557
- contentEpoch: epoch,
4558
- lastInvalidPointIndex: state.invalid,
4559
- lastDecreaseEdgeIndex: state.decrease,
4560
- lastNonIncreaseEdgeIndex: state.nonIncrease,
4561
- scannedSamples: state.scanned,
4562
- lastScannedSamples: state.lastScanned,
4563
- affineFastSamples: state.fast,
4564
- lastAffineFastSamples: state.lastFast,
4565
- affineEndpointEvaluations: state.endpoints,
4566
- lastAffineEndpointEvaluations: state.lastEndpoints,
4567
- cacheHits: state.cacheHits,
4568
- rebuilds: state.rebuilds
4569
- };
4570
- }
4571
- function getColumnOrder(dataSet, name) {
4572
- if (!(dataSet.hasColumn?.(name) ?? Object.prototype.hasOwnProperty.call(dataSet.schema, name))) throw new RangeError(`Unknown data column: ${name}`);
4573
- const epoch = dataSet.getContentEpoch(), next = dataSet.getNextSampleIndex(), first = next - dataSet.getSampleCount();
4574
- if (dataSet.isDisposed()) return result(createState(), first, next, epoch);
4575
- const cache = cacheFor(dataSet);
4576
- let state = cache.columns.get(name);
4577
- if (!state) {
4578
- state = createState();
4579
- cache.columns.set(name, state);
4580
- }
4581
- state.lastScanned = 0;
4582
- state.lastFast = 0;
4583
- state.lastEndpoints = 0;
4584
- if (state.epoch === epoch && state.first === first && state.next === next) {
4585
- state.cacheHits++;
4586
- return result(state, first, next, epoch);
4587
- }
4588
- if (state.epoch !== epoch || next < state.next || first < state.first) {
4589
- resetContent(state);
4590
- state.rebuilds++;
4591
- }
4592
- const from = Math.max(first, state.next);
4593
- if (from < next) {
4594
- const view = dataSet.getColumnRuns(name);
4595
- if (view.kind === "affine") scanAffine(state, view, from, next);
4596
- else if (view.kind === "paged") {
4597
- const cursor = new PagedColumnCursor(view, from);
4598
- while (cursor.values) {
4599
- const values = cursor.values, base = cursor.absoluteIndex - cursor.offset;
4600
- for (let i = cursor.offset, end = i + cursor.length; i < end; i++) accept(state, base + i, values[i], first);
4601
- cursor.next();
4602
- }
4603
- state.scanned += next - from;
4604
- state.lastScanned += next - from;
4605
- } else {
4606
- let absolute = view.firstIndex;
4607
- for (const values of view.slices) {
4608
- const start = Math.max(0, from - absolute);
4609
- for (let i = start; i < values.length; i++) accept(state, absolute + i, values[i], first);
4610
- absolute += values.length;
4611
- }
4612
- state.scanned += next - from;
4613
- state.lastScanned += next - from;
4614
- }
4750
+ setNorth(degrees) {
4751
+ if (!Number.isFinite(degrees)) throw new RangeError("North angle must be finite");
4752
+ this.polarChart.setAngleOrigin(90 - (this.polarChart.getClockwise() ? -degrees : degrees));
4753
+ return this;
4615
4754
  }
4616
- state.epoch = epoch;
4617
- state.first = first;
4618
- state.next = next;
4619
- return result(state, first, next, epoch);
4620
- }
4621
- var finiteCaches = /* @__PURE__ */ new WeakMap();
4622
- function getColumnFinite(dataSet, name) {
4623
- if (!(dataSet.hasColumn?.(name) ?? Object.prototype.hasOwnProperty.call(dataSet.schema, name))) throw new RangeError(`Unknown data column: ${name}`);
4624
- const epoch = dataSet.getContentEpoch(), next = dataSet.getNextSampleIndex(), first = next - dataSet.getSampleCount();
4625
- const expected2 = { revision: dataSet.revision, epoch, first, next };
4626
- let columns = finiteCaches.get(dataSet);
4627
- if (!columns && !dataSet.isDisposed()) {
4628
- columns = /* @__PURE__ */ new Map();
4629
- finiteCaches.set(dataSet, columns);
4630
- const owned2 = columns;
4631
- dataSet.onChange((current) => {
4632
- if (current.isDisposed()) {
4633
- owned2.clear();
4634
- finiteCaches.delete(current);
4635
- }
4636
- });
4755
+ getNorth(_unused) {
4756
+ const angle = (90 - this.polarChart.getAngleOrigin()) * (this.polarChart.getClockwise() ? -1 : 1);
4757
+ return angle === 0 ? 0 : angle;
4637
4758
  }
4638
- let state = columns?.get(name);
4639
- if (!state) {
4640
- state = { invalid: -1, scanned: 0, fullScans: 0, incrementalScans: 0, cacheHits: 0 };
4641
- columns?.set(name, state);
4759
+ setClockwise(value) {
4760
+ const north = this.getNorth();
4761
+ this.polarChart.setClockwise(value);
4762
+ return this.setNorth(north);
4642
4763
  }
4643
- const before = readSourceCertificate(dataSet, expected2);
4644
- const delta = !before?.tainted && state.certificate ? certifySourceDelta(dataSet, state.certificate, expected2).delta : void 0;
4645
- state.certificate = void 0;
4646
- let from = first, scanned = 0;
4647
- if (delta) {
4648
- from = Math.max(first, delta.previous.next);
4649
- if (delta.kind === "unchanged") state.cacheHits++;
4650
- else state.incrementalScans++;
4651
- } else {
4652
- state.invalid = -1;
4653
- state.fullScans++;
4764
+ getClockwise() {
4765
+ return this.polarChart.getClockwise();
4654
4766
  }
4655
- if (from < next && !dataSet.isDisposed()) {
4656
- const view = dataSet.getColumnRuns(name);
4657
- if (view.firstIndex !== first || view.count !== next - first) throw new RangeError("Finite source does not cover the retained window");
4658
- if (view.kind === "dense") {
4659
- let absolute = first;
4660
- for (const values of view.slices) {
4661
- const start = Math.max(0, from - absolute), end = Math.min(values.length, next - absolute);
4662
- for (let i = start; i < end; i++) if (!Number.isFinite(values[i])) state.invalid = absolute + i;
4663
- scanned += Math.max(0, end - start);
4664
- absolute += values.length;
4665
- }
4666
- } else if (view.kind === "paged") {
4667
- for (let index = from; index < next; ) {
4668
- const pageIndex = Math.floor(index / view.pageSize), base = pageIndex * view.pageSize;
4669
- const values = view.getPage(pageIndex), end = Math.min(next, base + view.pageSize);
4670
- for (; index < end; index++) {
4671
- if (!Number.isFinite(values?.[index - base])) state.invalid = index;
4672
- scanned++;
4673
- }
4674
- }
4675
- } else {
4676
- for (let r = view.runStart; r < view.runs.length; r++) {
4677
- const run = view.runs[r], begin = Math.max(from, run.firstIndex), end = Math.min(next, run.firstIndex + run.count);
4678
- for (let index = begin; index < end; index++) if (!Number.isFinite(run.start + (index - run.firstIndex) * run.step)) state.invalid = index;
4679
- scanned += Math.max(0, end - begin);
4680
- }
4681
- }
4682
- if (scanned !== next - from) throw new RangeError("Finite source omitted retained values");
4767
+ setTickStyle(value) {
4768
+ this.tickStrategy.setMajorTickStyle(value);
4769
+ return this;
4683
4770
  }
4684
- state.scanned += scanned;
4685
- const after = readSourceCertificate(dataSet, expected2);
4686
- const verifiedCurrent = dataSet.revision === expected2.revision && dataSet.getContentEpoch() === epoch && dataSet.getNextSampleIndex() === next && dataSet.getSampleCount() === next - first && before === after;
4687
- state.certificate = verifiedCurrent && after && !after.tainted ? after : void 0;
4688
- return {
4689
- finite: verifiedCurrent && state.invalid < first,
4690
- verifiedCurrent,
4691
- sampleCount: next - first,
4692
- firstIndex: first,
4693
- nextIndex: next,
4694
- contentEpoch: epoch,
4695
- lastInvalidPointIndex: state.invalid,
4696
- scannedSamples: state.scanned,
4697
- lastScannedSamples: scanned,
4698
- fullScans: state.fullScans,
4699
- incrementalScans: state.incrementalScans,
4700
- cacheHits: state.cacheHits
4701
- };
4702
- }
4771
+ getTickStyle() {
4772
+ return this.tickStrategy.getMajorTickStyle();
4773
+ }
4774
+ setTickFormattingFunction(value) {
4775
+ if (typeof value !== "function") throw new TypeError("Polar tick formatter must be a function");
4776
+ this.tickFormattingFunction = value;
4777
+ this.chart.invalidate();
4778
+ return this;
4779
+ }
4780
+ getTickFormattingFunction() {
4781
+ return this.tickFormattingFunction;
4782
+ }
4783
+ };
4703
4784
 
4704
4785
  // src/line-extrema-pair-proof.ts
4705
4786
  var issued2 = /* @__PURE__ */ new WeakSet();
@@ -7687,7 +7768,8 @@ var PointLineAreaSeries = class _PointLineAreaSeries {
7687
7768
  yValues: { storage: Float64Array },
7688
7769
  ...this.axisZ ? { zValues: { storage: Float64Array } } : {}
7689
7770
  },
7690
- includesNaN: options.includesNaN
7771
+ includesNaN: options.includesNaN,
7772
+ columnStorage: options.columnStorage
7691
7773
  });
7692
7774
  const keys = Object.keys(this.dataSet.schema);
7693
7775
  const implicitX = keys.length === 1 && !this.axisZ && keys[0] !== "x" && keys[0] !== "xValues";
@@ -15496,6 +15578,38 @@ var LineCoverageRenderer = class {
15496
15578
  this.frameState = this.saveState();
15497
15579
  this.capturedFrameActive = true;
15498
15580
  }
15581
+ /** Shared-context all-coverage batch after SharedWebGLContext established its
15582
+ * exact clean default-target baseline: avoids 28 synchronous GL state queries
15583
+ * while preserving identical restoreState semantics for both draw and frame scopes. */
15584
+ beginKnownCapturedFrame(program, viewport) {
15585
+ if (this.disposed || this.frameState) throw new Error("Captured coverage frame requires a fresh frame");
15586
+ const gl = this.gl;
15587
+ this.frameState = {
15588
+ drawFramebuffer: null,
15589
+ readFramebuffer: null,
15590
+ viewport: Int32Array.from(viewport),
15591
+ scissor: Int32Array.from(viewport),
15592
+ clearColor: new Float32Array(4),
15593
+ colorMask: [true, true, true, true],
15594
+ program,
15595
+ vao: null,
15596
+ arrayBuffer: null,
15597
+ activeTexture: gl.TEXTURE0,
15598
+ texture0: null,
15599
+ sampler0: null,
15600
+ enabled: [[gl.SCISSOR_TEST, true], [gl.BLEND, true], [gl.DEPTH_TEST, false], [gl.STENCIL_TEST, false], [gl.CULL_FACE, false], [gl.RASTERIZER_DISCARD, false], [gl.SAMPLE_ALPHA_TO_COVERAGE, false], [gl.SAMPLE_COVERAGE, false], [gl.DITHER, true]],
15601
+ blendSourceRGB: gl.SRC_ALPHA,
15602
+ blendSourceAlpha: gl.ONE,
15603
+ blendDestinationRGB: gl.ONE_MINUS_SRC_ALPHA,
15604
+ blendDestinationAlpha: gl.ONE_MINUS_SRC_ALPHA,
15605
+ blendEquationRGB: gl.FUNC_ADD,
15606
+ blendEquationAlpha: gl.FUNC_ADD
15607
+ };
15608
+ this.capturedFrameActive = true;
15609
+ this.ownedMaskStateReady = false;
15610
+ this.knownFrameActive = true;
15611
+ this.stats.knownFrameBaselines++;
15612
+ }
15499
15613
  /** Internal capability, only after DataRenderer established this exact private
15500
15614
  * default-target baseline. Standalone draw()/frame users keep full capture.
15501
15615
  * This record is ephemeral and cleared by every flush/end/context/dispose. */
@@ -16003,6 +16117,10 @@ var LineStripRenderer = class {
16003
16117
  if (!this.coverage) throw new Error("Captured frame requires coverage rendering");
16004
16118
  this.coverage.beginCapturedFrame();
16005
16119
  }
16120
+ beginKnownCapturedCoverageFrame(program, viewport) {
16121
+ if (!this.coverage) throw new Error("Captured frame requires coverage rendering");
16122
+ this.coverage.beginKnownCapturedFrame(program, viewport);
16123
+ }
16006
16124
  canDraw(packet) {
16007
16125
  if (this.coverage) return this.coverage.canDraw(packet);
16008
16126
  return !this.disposed && packet.strictlyMonotonicX === true && packet.mode === "line" && packet.dimensions === 2 && packet.count >= 2 && packet.thickness > 0 && !packet.colors && !packet.dashPattern?.length && packet.positions.length >= packet.count * 2;
@@ -16209,6 +16327,307 @@ var LineStripRenderer = class {
16209
16327
  }
16210
16328
  };
16211
16329
 
16330
+ // src/shared-webgl-context.ts
16331
+ var cores = /* @__PURE__ */ new WeakMap();
16332
+ var claimedCanvases = /* @__PURE__ */ new WeakMap();
16333
+ function sharedContextCore(context) {
16334
+ const core = cores.get(context);
16335
+ if (!core) throw new TypeError("Expected a valid SharedWebGLContext");
16336
+ return core;
16337
+ }
16338
+ function resetSharedBaseline(gl, width, height, maxVertexAttribs) {
16339
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
16340
+ gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
16341
+ gl.drawBuffers([gl.BACK]);
16342
+ gl.readBuffer(gl.BACK);
16343
+ gl.bindVertexArray(null);
16344
+ for (let i = 0; i < maxVertexAttribs; i++) {
16345
+ gl.disableVertexAttribArray(i);
16346
+ gl.vertexAttribDivisor(i, 0);
16347
+ }
16348
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
16349
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
16350
+ gl.bindBuffer(gl.PIXEL_UNPACK_BUFFER, null);
16351
+ gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
16352
+ gl.bindBuffer(gl.COPY_READ_BUFFER, null);
16353
+ gl.bindBuffer(gl.COPY_WRITE_BUFFER, null);
16354
+ gl.bindBuffer(gl.UNIFORM_BUFFER, null);
16355
+ gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
16356
+ for (let unit = 2; unit >= 0; unit--) {
16357
+ gl.activeTexture(gl.TEXTURE0 + unit);
16358
+ gl.bindTexture(gl.TEXTURE_2D, null);
16359
+ gl.bindSampler(unit, null);
16360
+ }
16361
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
16362
+ gl.pixelStorei(gl.PACK_ALIGNMENT, 4);
16363
+ gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
16364
+ gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
16365
+ gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
16366
+ gl.pixelStorei(gl.UNPACK_IMAGE_HEIGHT, 0);
16367
+ gl.pixelStorei(gl.UNPACK_SKIP_IMAGES, 0);
16368
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
16369
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
16370
+ gl.useProgram(null);
16371
+ gl.colorMask(true, true, true, true);
16372
+ gl.depthMask(true);
16373
+ gl.stencilMask(255);
16374
+ for (const capability of [
16375
+ gl.DEPTH_TEST,
16376
+ gl.STENCIL_TEST,
16377
+ gl.CULL_FACE,
16378
+ gl.RASTERIZER_DISCARD,
16379
+ gl.SAMPLE_ALPHA_TO_COVERAGE,
16380
+ gl.SAMPLE_COVERAGE,
16381
+ gl.SCISSOR_TEST,
16382
+ gl.POLYGON_OFFSET_FILL
16383
+ ]) {
16384
+ gl.disable(capability);
16385
+ }
16386
+ gl.enable(gl.BLEND);
16387
+ gl.enable(gl.DITHER);
16388
+ gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
16389
+ gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
16390
+ gl.viewport(0, 0, width, height);
16391
+ gl.scissor(0, 0, width, height);
16392
+ }
16393
+ var SharedContextCore = class {
16394
+ canvas;
16395
+ cullOffscreen;
16396
+ antialias;
16397
+ ownsCanvas;
16398
+ clients = /* @__PURE__ */ new Set();
16399
+ observer;
16400
+ observedRoots = /* @__PURE__ */ new Map();
16401
+ offscreenClients = /* @__PURE__ */ new Set();
16402
+ gl = null;
16403
+ attempted = false;
16404
+ disposed = false;
16405
+ maxVertexAttribs = 0;
16406
+ pendingPresent;
16407
+ baselineClean = false;
16408
+ chartDraws = 0;
16409
+ blits = 0;
16410
+ backingResizes = 0;
16411
+ contextLosses = 0;
16412
+ contextRestores = 0;
16413
+ onLost = (event) => {
16414
+ event.preventDefault();
16415
+ this.baselineClean = false;
16416
+ this.contextLosses++;
16417
+ };
16418
+ onRestore = () => {
16419
+ this.baselineClean = false;
16420
+ this.contextRestores++;
16421
+ };
16422
+ constructor(options) {
16423
+ if (options !== void 0 && (typeof options !== "object" || options === null)) {
16424
+ throw new TypeError("SharedWebGLContext options must be an object");
16425
+ }
16426
+ if (options?.canvas !== void 0) {
16427
+ if (typeof options.canvas !== "object" || options.canvas === null || typeof options.canvas.getContext !== "function") {
16428
+ throw new TypeError("SharedWebGLContext canvas must provide getContext");
16429
+ }
16430
+ if (claimedCanvases.has(options.canvas)) {
16431
+ throw new Error("Canvas is already bound to an active SharedWebGLContext");
16432
+ }
16433
+ this.canvas = options.canvas;
16434
+ this.ownsCanvas = false;
16435
+ claimedCanvases.set(options.canvas, this);
16436
+ } else if (typeof document !== "undefined") {
16437
+ this.canvas = document.createElement("canvas");
16438
+ this.ownsCanvas = true;
16439
+ } else {
16440
+ this.canvas = void 0;
16441
+ this.ownsCanvas = false;
16442
+ }
16443
+ this.antialias = options?.antialias === true;
16444
+ this.cullOffscreen = options?.cullOffscreen !== false;
16445
+ }
16446
+ acquire() {
16447
+ this.baselineClean = false;
16448
+ if (this.disposed) return null;
16449
+ if (this.attempted) return this.gl;
16450
+ this.attempted = true;
16451
+ if (!this.canvas) return null;
16452
+ let gl = null;
16453
+ try {
16454
+ gl = this.canvas.getContext("webgl2", {
16455
+ alpha: true,
16456
+ antialias: this.antialias,
16457
+ depth: false,
16458
+ stencil: false,
16459
+ premultipliedAlpha: true,
16460
+ preserveDrawingBuffer: false
16461
+ });
16462
+ } catch {
16463
+ gl = null;
16464
+ }
16465
+ if (gl) {
16466
+ this.gl = gl;
16467
+ const maxAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
16468
+ this.maxVertexAttribs = typeof maxAttribs === "number" && maxAttribs > 0 ? maxAttribs : 0;
16469
+ this.canvas.addEventListener("webglcontextlost", this.onLost);
16470
+ this.canvas.addEventListener("webglcontextrestored", this.onRestore);
16471
+ }
16472
+ return this.gl;
16473
+ }
16474
+ isAvailable() {
16475
+ const gl = this.acquire();
16476
+ return gl !== null && !this.disposed && !gl.isContextLost();
16477
+ }
16478
+ isDisposed() {
16479
+ return this.disposed;
16480
+ }
16481
+ getChartCount() {
16482
+ return this.clients.size;
16483
+ }
16484
+ getStats() {
16485
+ const active2 = this.gl !== null && !this.disposed;
16486
+ return {
16487
+ available: active2 && !this.gl.isContextLost(),
16488
+ disposed: this.disposed,
16489
+ registeredCharts: this.clients.size,
16490
+ offscreenCharts: this.offscreenClients.size,
16491
+ backingWidth: active2 && this.canvas ? this.canvas.width : 0,
16492
+ backingHeight: active2 && this.canvas ? this.canvas.height : 0,
16493
+ chartDraws: this.chartDraws,
16494
+ blits: this.blits,
16495
+ backingResizes: this.backingResizes,
16496
+ contextLosses: this.contextLosses,
16497
+ contextRestores: this.contextRestores
16498
+ };
16499
+ }
16500
+ register(client) {
16501
+ if (this.disposed) throw new Error("SharedWebGLContext has been disposed");
16502
+ if (this.clients.has(client)) return;
16503
+ this.clients.add(client);
16504
+ if (this.cullOffscreen && typeof IntersectionObserver === "function") {
16505
+ if (!this.observer) {
16506
+ this.observer = new IntersectionObserver(
16507
+ (entries) => {
16508
+ for (const entry of entries) {
16509
+ const targetClient = this.observedRoots.get(entry.target);
16510
+ if (!targetClient) continue;
16511
+ const offscreen = !entry.isIntersecting;
16512
+ if (offscreen) this.offscreenClients.add(targetClient);
16513
+ else this.offscreenClients.delete(targetClient);
16514
+ targetClient.setOffscreen?.(offscreen);
16515
+ }
16516
+ },
16517
+ { threshold: 0 }
16518
+ );
16519
+ }
16520
+ this.observedRoots.set(client.root, client);
16521
+ this.observer.observe(client.root);
16522
+ }
16523
+ }
16524
+ unregister(client) {
16525
+ this.clients.delete(client);
16526
+ this.offscreenClients.delete(client);
16527
+ if (this.observedRoots.delete(client.root)) {
16528
+ this.observer?.unobserve(client.root);
16529
+ }
16530
+ }
16531
+ beginChartDraw(pixelWidth, pixelHeight) {
16532
+ this.pendingPresent = void 0;
16533
+ const gl = this.acquire();
16534
+ if (!gl || this.disposed || gl.isContextLost()) return false;
16535
+ const canvas = this.canvas;
16536
+ const width = Math.max(1, Math.round(pixelWidth));
16537
+ const height = Math.max(1, Math.round(pixelHeight));
16538
+ let resized = false;
16539
+ if (canvas.width !== width) {
16540
+ canvas.width = width;
16541
+ resized = true;
16542
+ }
16543
+ if (canvas.height !== height) {
16544
+ canvas.height = height;
16545
+ resized = true;
16546
+ }
16547
+ if (resized) this.backingResizes++;
16548
+ resetSharedBaseline(gl, width, height, this.maxVertexAttribs);
16549
+ gl.disable(gl.SCISSOR_TEST);
16550
+ gl.clearColor(0, 0, 0, 0);
16551
+ gl.clear(gl.COLOR_BUFFER_BIT);
16552
+ this.pendingPresent = { width, height };
16553
+ this.baselineClean = true;
16554
+ this.chartDraws++;
16555
+ return true;
16556
+ }
16557
+ /** Consume the clean baseline established by beginChartDraw() for the first drawGPU() in this chart frame. */
16558
+ consumeCleanBaseline() {
16559
+ if (!this.baselineClean || this.disposed || !this.pendingPresent) return false;
16560
+ this.baselineClean = false;
16561
+ return true;
16562
+ }
16563
+ present(target, pixelWidth, pixelHeight) {
16564
+ const pending = this.pendingPresent;
16565
+ this.pendingPresent = void 0;
16566
+ this.baselineClean = false;
16567
+ const width = Math.max(1, Math.round(pixelWidth));
16568
+ const height = Math.max(1, Math.round(pixelHeight));
16569
+ if (!pending || !target || !this.canvas || pending.width !== width || pending.height !== height) {
16570
+ return;
16571
+ }
16572
+ target.save();
16573
+ target.setTransform(1, 0, 0, 1, 0, 0);
16574
+ target.globalAlpha = 1;
16575
+ target.globalCompositeOperation = "copy";
16576
+ target.imageSmoothingEnabled = false;
16577
+ target.drawImage(this.canvas, 0, 0);
16578
+ target.restore();
16579
+ this.blits++;
16580
+ }
16581
+ dispose() {
16582
+ if (this.disposed) return;
16583
+ this.disposed = true;
16584
+ this.pendingPresent = void 0;
16585
+ this.baselineClean = false;
16586
+ this.observer?.disconnect();
16587
+ this.observer = void 0;
16588
+ this.observedRoots.clear();
16589
+ this.offscreenClients.clear();
16590
+ this.clients.clear();
16591
+ if (this.canvas) {
16592
+ if (this.gl) {
16593
+ this.canvas.removeEventListener("webglcontextlost", this.onLost);
16594
+ this.canvas.removeEventListener("webglcontextrestored", this.onRestore);
16595
+ }
16596
+ if (this.ownsCanvas) {
16597
+ this.gl?.getExtension("WEBGL_lose_context")?.loseContext();
16598
+ this.canvas.width = 1;
16599
+ this.canvas.height = 1;
16600
+ } else {
16601
+ claimedCanvases.delete(this.canvas);
16602
+ }
16603
+ }
16604
+ this.gl = null;
16605
+ }
16606
+ };
16607
+ var SharedWebGLContext = class {
16608
+ constructor(options) {
16609
+ cores.set(this, new SharedContextCore(options));
16610
+ }
16611
+ /** Lazily acquires the shared WebGL2 context on first call and caches the result without retrying. */
16612
+ isAvailable() {
16613
+ return sharedContextCore(this).isAvailable();
16614
+ }
16615
+ isDisposed() {
16616
+ return sharedContextCore(this).isDisposed();
16617
+ }
16618
+ /** Number of charts currently registered with this shared context. */
16619
+ getChartCount() {
16620
+ return sharedContextCore(this).getChartCount();
16621
+ }
16622
+ getStats() {
16623
+ return sharedContextCore(this).getStats();
16624
+ }
16625
+ /** Idempotently disposes the shared context. Dispose all registered charts first. */
16626
+ dispose() {
16627
+ sharedContextCore(this).dispose();
16628
+ }
16629
+ };
16630
+
16212
16631
  // src/render.ts
16213
16632
  var iconVertex = `#version 300 es
16214
16633
  precision highp float;
@@ -16354,7 +16773,15 @@ var DataRenderer = class {
16354
16773
  this.ownedCoverageFrame = options.ownedCoverageFrame === true;
16355
16774
  this.gpuClipPolicy = options.gpuClipPolicy ?? "legacy";
16356
16775
  let gl = null;
16357
- try {
16776
+ let contextEvents = canvas;
16777
+ if (options.renderer !== "canvas2d" && options.sharedContext) {
16778
+ const core = sharedContextCore(options.sharedContext);
16779
+ gl = core.acquire();
16780
+ if (gl && core.canvas) {
16781
+ this.sharedContext = options.sharedContext;
16782
+ contextEvents = core.canvas;
16783
+ }
16784
+ } else try {
16358
16785
  if (options.renderer !== "canvas2d") gl = canvas.getContext("webgl2", {
16359
16786
  alpha: true,
16360
16787
  antialias: options.antialias ?? false,
@@ -16365,11 +16792,12 @@ var DataRenderer = class {
16365
16792
  }
16366
16793
  if (options.renderer === "webgl2" && !gl) throw new Error("CRYChart WebGL2 renderer is unavailable");
16367
16794
  this.gl = gl;
16795
+ this.contextEvents = contextEvents;
16368
16796
  this.backend = gl ? "webgl2" : "canvas2d";
16369
16797
  if (gl) {
16370
16798
  this.init(gl);
16371
- canvas.addEventListener("webglcontextlost", this.onLost);
16372
- canvas.addEventListener("webglcontextrestored", this.onRestore);
16799
+ this.contextEvents.addEventListener("webglcontextlost", this.onLost);
16800
+ this.contextEvents.addEventListener("webglcontextrestored", this.onRestore);
16373
16801
  } else
16374
16802
  try {
16375
16803
  this.ctx = canvas.getContext("2d");
@@ -16401,6 +16829,8 @@ var DataRenderer = class {
16401
16829
  lost = false;
16402
16830
  iconPipeline;
16403
16831
  iconTextures = /* @__PURE__ */ new Map();
16832
+ sharedContext;
16833
+ contextEvents;
16404
16834
  stats = {
16405
16835
  frames: 0,
16406
16836
  uploads: 0,
@@ -16685,8 +17115,12 @@ var DataRenderer = class {
16685
17115
  const gl = this.gl;
16686
17116
  const owned2 = this.canUseKnownOwnedFrame(packets, clear, this.gpuClipPolicy === "contained" && rasterTarget?.framebuffer !== null);
16687
17117
  if (owned2 && !this.lineStrip) this.lineStrip = new LineStripRenderer(gl, { coverageUnion: true, coverageStateScope: "frame", clipPolicy: this.gpuClipPolicy });
16688
- const coverageBatch = !owned2 && !rasterTarget && packets.length > 0 && packets.every((p) => p.strictlyMonotonicX === true && p.mode === "line" && p.dimensions === 2 && Number.isSafeInteger(p.count) && p.count >= 2 && p.positions.length >= p.count * 2 && Number.isFinite(p.thickness) && p.thickness > 0 && !p.colors && !p.dashPattern?.length && !p.pointSizes && !p.pointRotations) && gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING) === null;
16689
- if (coverageBatch && !this.lineStrip) this.lineStrip = new LineStripRenderer(gl, { coverageUnion: this.lineCoverageUnion, coverageStateScope: this.lineCoverageStateScope, clipPolicy: this.gpuClipPolicy });
17118
+ const sharedBaselineWasClean = this.sharedContext !== void 0 ? sharedContextCore(this.sharedContext).consumeCleanBaseline() : false;
17119
+ const sharedCleanBaseline = !owned2 && !rasterTarget && clear && sharedBaselineWasClean;
17120
+ const compatibleCoveragePackets = !owned2 && !rasterTarget && packets.length > 0 && packets.every((p) => p.strictlyMonotonicX === true && p.mode === "line" && p.dimensions === 2 && Number.isSafeInteger(p.count) && p.count >= 2 && p.positions.length >= p.count * 2 && Number.isFinite(p.thickness) && p.thickness > 0 && !p.colors && !p.dashPattern?.length && !p.pointSizes && !p.pointRotations);
17121
+ const sharedKnownCoverageBatch = sharedCleanBaseline && compatibleCoveragePackets;
17122
+ const coverageBatch = !sharedKnownCoverageBatch && compatibleCoveragePackets && gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING) === null;
17123
+ if ((sharedKnownCoverageBatch || coverageBatch) && !this.lineStrip) this.lineStrip = new LineStripRenderer(gl, { coverageUnion: this.lineCoverageUnion, coverageStateScope: this.lineCoverageStateScope, clipPolicy: this.gpuClipPolicy });
16690
17124
  const stripBefore = { uploads: this.lineStrip?.stats.uploads ?? 0, bytes: this.lineStrip?.stats.uploadedBytes ?? 0 };
16691
17125
  this.lineStrip?.beginFrame();
16692
17126
  let frameEnded = false;
@@ -16714,6 +17148,10 @@ var DataRenderer = class {
16714
17148
  gl.uniform2f(this.uniforms.plotOrigin, x, y);
16715
17149
  gl.uniform1f(this.uniforms.dpr, dpr);
16716
17150
  if (owned2) this.lineStrip.beginKnownOwnedFrame(this.program, [x, y, w, h]);
17151
+ else if (sharedKnownCoverageBatch) {
17152
+ this.lineStrip.beginKnownCapturedCoverageFrame(this.program, [x, y, w, h]);
17153
+ capturedCoverageBatch = true;
17154
+ }
16717
17155
  let clipX = x, clipY = y, clipW = w, clipH = h;
16718
17156
  const live = /* @__PURE__ */ new Set();
16719
17157
  const liveAttributes = /* @__PURE__ */ new Set();
@@ -17125,8 +17563,8 @@ var DataRenderer = class {
17125
17563
  this.attributeBuffers.clear();
17126
17564
  if (this.program) this.gl.deleteProgram(this.program);
17127
17565
  }
17128
- this.canvas.removeEventListener("webglcontextlost", this.onLost);
17129
- this.canvas.removeEventListener("webglcontextrestored", this.onRestore);
17566
+ this.contextEvents.removeEventListener("webglcontextlost", this.onLost);
17567
+ this.contextEvents.removeEventListener("webglcontextrestored", this.onRestore);
17130
17568
  }
17131
17569
  };
17132
17570
  function appendPointPath(ctx, x, y, size, shape, rotation) {
@@ -18004,8 +18442,9 @@ var DataRendererHeatmap = class {
18004
18442
  this.canvas = canvas;
18005
18443
  this.options = options;
18006
18444
  this.initialize();
18007
- canvas.addEventListener("webglcontextlost", this.contextLost);
18008
- canvas.addEventListener("webglcontextrestored", this.contextRestored);
18445
+ const events = this.options.contextEvents ?? this.canvas;
18446
+ events.addEventListener("webglcontextlost", this.contextLost);
18447
+ events.addEventListener("webglcontextrestored", this.contextRestored);
18009
18448
  }
18010
18449
  stats = { frames: 0, uploads: 0, textureUploads: 0, paletteUploads: 0, uploadedBytes: 0, drawCalls: 0, cells: 0, renderTimeMs: 0, cachedTextures: 0, cacheBytes: 0, contextRestores: 0 };
18011
18450
  entries = /* @__PURE__ */ new Map();
@@ -18296,8 +18735,9 @@ var DataRendererHeatmap = class {
18296
18735
  this.program = void 0;
18297
18736
  this.stats.cachedTextures = 0;
18298
18737
  this.stats.cacheBytes = 0;
18299
- this.canvas.removeEventListener("webglcontextlost", this.contextLost);
18300
- this.canvas.removeEventListener("webglcontextrestored", this.contextRestored);
18738
+ const events = this.options.contextEvents ?? this.canvas;
18739
+ events.removeEventListener("webglcontextlost", this.contextLost);
18740
+ events.removeEventListener("webglcontextrestored", this.contextRestored);
18301
18741
  }
18302
18742
  };
18303
18743
 
@@ -19820,30 +20260,73 @@ function fitEllipsoid3D(input, options = {}) {
19820
20260
  // src/axis-canvas.ts
19821
20261
  var color = (fill, fallback) => fill?.kind === "empty" ? ColorRGBA(0, 0, 0, 0) : fill?.getColor?.() ?? fallback;
19822
20262
  var validFont = (font2) => font2.toCSS?.() ?? `${font2.getSize()}px sans-serif`;
20263
+ var TEXT_METRICS_CACHE_MAX = 1024;
20264
+ var fontCacheEpoch = 0;
20265
+ var fontCacheListening = false;
20266
+ var persistentTextCaches = /* @__PURE__ */ new WeakMap();
20267
+ function ensureFontCacheListener() {
20268
+ if (fontCacheListening) return;
20269
+ try {
20270
+ const fonts = globalThis.document?.fonts;
20271
+ if (typeof fonts?.addEventListener === "function") {
20272
+ fonts.addEventListener("loadingdone", () => {
20273
+ fontCacheEpoch++;
20274
+ });
20275
+ fontCacheListening = true;
20276
+ }
20277
+ } catch {
20278
+ }
20279
+ }
20280
+ function getAxisTextMetricsCache(ctx) {
20281
+ if (!ctx) return void 0;
20282
+ ensureFontCacheListener();
20283
+ let entry = persistentTextCaches.get(ctx);
20284
+ if (!entry || entry.epoch !== fontCacheEpoch) {
20285
+ entry = { epoch: fontCacheEpoch, map: /* @__PURE__ */ new Map() };
20286
+ persistentTextCaches.set(ctx, entry);
20287
+ } else if (entry.map.size >= TEXT_METRICS_CACHE_MAX) {
20288
+ entry.map.clear();
20289
+ }
20290
+ return entry.map;
20291
+ }
19823
20292
  var lineBoxHeight = (font2) => font2.getSize() * 0.8;
19824
20293
  function lineBoxBaseline(metrics2, font2) {
19825
20294
  const size = font2.getSize();
19826
20295
  return ((metrics2?.fontBoundingBoxAscent ?? size * 0.8) - (metrics2?.fontBoundingBoxDescent ?? size * 0.2)) / 2;
19827
20296
  }
19828
- function textMetrics(ctx, text, font2, cache) {
19829
- const key = validFont(font2) + "\0" + text, cached = cache?.get(key);
20297
+ function textMetrics(ctx, text, font2, cache, align) {
20298
+ const fontCss = validFont(font2);
20299
+ const key = fontCss + "\0" + (align ?? "") + "\0" + text, cached = cache?.get(key);
19830
20300
  if (cached) return cached;
19831
- const previous = ctx?.font, previousBaseline = ctx?.textBaseline;
19832
- if (ctx) {
19833
- ctx.font = validFont(font2);
19834
- ctx.textBaseline = "alphabetic";
19835
- }
20301
+ const previous = ctx?.font, previousBaseline = ctx?.textBaseline, previousAlign = ctx?.textAlign;
19836
20302
  let measured;
19837
20303
  try {
20304
+ if (ctx) {
20305
+ ctx.font = fontCss;
20306
+ ctx.textBaseline = "alphabetic";
20307
+ if (align !== void 0) ctx.textAlign = align;
20308
+ }
19838
20309
  measured = ctx?.measureText?.(text);
19839
20310
  } finally {
19840
20311
  if (ctx) {
19841
20312
  if (previous !== void 0) ctx.font = previous;
19842
20313
  if (previousBaseline !== void 0) ctx.textBaseline = previousBaseline;
20314
+ if (align !== void 0 && previousAlign !== void 0) ctx.textAlign = previousAlign;
19843
20315
  }
19844
20316
  }
19845
- const result2 = { width: measured?.width ?? text.length * font2.getSize() * 0.6, ascent: measured?.actualBoundingBoxAscent ?? font2.getSize() * 0.75, descent: measured?.actualBoundingBoxDescent ?? font2.getSize() * 0.25, baseline: lineBoxBaseline(measured, font2) };
19846
- cache?.set(key, result2);
20317
+ const result2 = {
20318
+ width: measured?.width ?? text.length * font2.getSize() * 0.6,
20319
+ ascent: measured?.actualBoundingBoxAscent ?? font2.getSize() * 0.75,
20320
+ descent: measured?.actualBoundingBoxDescent ?? font2.getSize() * 0.25,
20321
+ baseline: lineBoxBaseline(measured, font2),
20322
+ actualBoundingBoxAscent: measured?.actualBoundingBoxAscent,
20323
+ actualBoundingBoxDescent: measured?.actualBoundingBoxDescent,
20324
+ ...align !== void 0 ? { actualBoundingBoxLeft: measured?.actualBoundingBoxLeft, actualBoundingBoxRight: measured?.actualBoundingBoxRight } : {}
20325
+ };
20326
+ if (cache) {
20327
+ if (cache.size >= TEXT_METRICS_CACHE_MAX) cache.clear();
20328
+ cache.set(key, result2);
20329
+ }
19847
20330
  return result2;
19848
20331
  }
19849
20332
  function measureChartTitleContent(ctx, text, font2, dpr = 1) {
@@ -19927,9 +20410,9 @@ function metrics(axis, ctx, cache, theme, resolveFont) {
19927
20410
  const laneSize = extent > 0 ? Math.ceil(extent + (horizontal ? 2 : 4)) : 0;
19928
20411
  return { measured: true, labelFont, titleFont, lane: 0, laneOffset: 0, laneSize, labelOffset, titleOffset, tickLength, labelWidth, labelAscent, labelDescent, titleWidth: title.width, titleAscent: title.ascent, titleDescent: title.descent, rotation };
19929
20412
  }
19930
- function measureAxisCanvasLayout(ctx, axesX, axesY, theme, resolveFont) {
20413
+ function measureAxisCanvasLayout(ctx, axesX, axesY, theme, resolveFont, persistentCache) {
19931
20414
  const result2 = { contentMargins: { left: 0, right: 0, top: 0, bottom: 0 }, extraMargins: { left: 0, right: 0, top: 0, bottom: 0 }, axes: /* @__PURE__ */ new Map() };
19932
- const textCache = /* @__PURE__ */ new Map();
20415
+ const textCache = persistentCache ?? /* @__PURE__ */ new Map();
19933
20416
  for (const [horizontal, list] of [[true, axesX], [false, axesY]]) for (const opposite of [false, true]) {
19934
20417
  const groups = /* @__PURE__ */ new Map();
19935
20418
  for (const axis of list) if (axis.visible && !axis.disposed && axis.opposite === opposite) {
@@ -20004,14 +20487,15 @@ function paintAxisLabels(ctx, labels, axisLength, selectedTimeMinor = false) {
20004
20487
  }
20005
20488
  }
20006
20489
  function drawAxisCanvas(ctx, options) {
20007
- const { plot: r, axesX, axesY, light = false, theme, resolveFont } = options, layout = options.layout ?? measureAxisCanvasLayout(ctx, axesX, axesY, theme, resolveFont);
20490
+ const textCache = getAxisTextMetricsCache(ctx);
20491
+ const { plot: r, axesX, axesY, light = false, theme, resolveFont } = options, layout = options.layout ?? measureAxisCanvasLayout(ctx, axesX, axesY, theme, resolveFont, textCache);
20008
20492
  const baselines = [];
20009
20493
  ctx.save();
20010
20494
  try {
20011
20495
  ctx.textBaseline = "alphabetic";
20012
20496
  for (const axis of [...axesX, ...axesY]) {
20013
20497
  if (!axis.visible || axis.disposed) continue;
20014
- const m = layout.axes.get(axis) ?? metrics(axis, ctx, void 0, theme, resolveFont), horizontal = axis.direction === "x", outward = axis.opposite ? horizontal ? -1 : 1 : horizontal ? 1 : -1;
20498
+ const m = layout.axes.get(axis) ?? metrics(axis, ctx, textCache, theme, resolveFont), horizontal = axis.direction === "x", outward = axis.opposite ? horizontal ? -1 : 1 : horizontal ? 1 : -1;
20015
20499
  const linePosition = horizontal ? axis.opposite ? r.top - m.laneOffset : r.top + r.height + m.laneOffset : axis.opposite ? r.left + r.width + m.laneOffset : r.left - m.laneOffset;
20016
20500
  const range = axis.getScreenRange(), axisLength = Math.abs(range.end - range.start) * (horizontal ? r.width : r.height), strategy = axis.tickStrategy;
20017
20501
  const lineFrom = horizontal ? { x: r.left + range.start * r.width, y: linePosition } : { x: linePosition, y: r.top + (1 - range.start) * r.height };
@@ -20026,7 +20510,7 @@ function drawAxisCanvas(ctx, options) {
20026
20510
  if (options.paintFrame) {
20027
20511
  if (axis.stroke?.getThickness?.() > 0) baselines.push({ stroke: axis.stroke, from: lineFrom, to: lineTo });
20028
20512
  } else paintStroke(ctx, axis.stroke, lineFrom, lineTo);
20029
- const ticks = measuredTickLayout(axis, ctx, axisLength, strategy.kind === "datetime" || strategy.kind === "time" ? /* @__PURE__ */ new Map() : void 0, theme, resolveFont), labels = [], interval = axis.getInterval();
20513
+ const ticks = measuredTickLayout(axis, ctx, axisLength, textCache, theme, resolveFont), labels = [], interval = axis.getInterval();
20030
20514
  for (const level of ["minor", "major", "great"]) {
20031
20515
  const style = tickStyle(strategy, level);
20032
20516
  if (!style) continue;
@@ -20041,17 +20525,18 @@ function drawAxisCanvas(ctx, options) {
20041
20525
  const labelFill = resolvedTickFill(axis, level, style, theme, true);
20042
20526
  const labelColor = labelFill !== void 0 ? color(labelFill, ColorRGBA(0, 0, 0, 0)) : light ? ColorRGBA(82, 97, 118) : color(style.getLabelFillStyle(), ColorRGBA(150, 164, 185));
20043
20527
  if (labelColor.a > 0 && tick.label.length) {
20528
+ const align = horizontal ? level === "great" ? "left" : "center" : axis.opposite ? "left" : "right";
20044
20529
  ctx.font = validFont(labelFont);
20045
20530
  ctx.fillStyle = labelColor.toCSS();
20046
- ctx.textAlign = horizontal ? level === "great" ? "left" : "center" : axis.opposite ? "left" : "right";
20047
- const measured = ctx.measureText(tick.label), width = Number.isFinite(measured.width) ? measured.width : 0;
20531
+ ctx.textAlign = align;
20532
+ const measured = textMetrics(ctx, tick.label, labelFont, textCache, align), width = Number.isFinite(measured.width) ? measured.width : 0;
20048
20533
  const anchor = level === "great" && "anchor" in tick ? axis.valueToScreenFraction(tick.anchor) : fraction2;
20049
20534
  const anchorX = horizontal ? r.left + anchor * r.width + (level === "great" ? 2 : 0) : x;
20050
20535
  const anchorY = horizontal ? y : r.top + r.height - anchor * r.height;
20051
20536
  const labelX = horizontal ? boundAxisLabelX(ctx, tick.label, anchorX, lineFrom.x, lineTo.x, measured) : x + outward * m.labelOffset;
20052
20537
  let labelY = anchorY + (horizontal ? outward * m.labelOffset : 4);
20053
20538
  if (m.lineBoxTitleBaseline !== void 0) {
20054
- const baseline = lineBoxBaseline(measured, labelFont), halfLine = lineBoxHeight(labelFont) / 2;
20539
+ const baseline = measured.baseline, halfLine = lineBoxHeight(labelFont) / 2;
20055
20540
  labelY = anchorY + baseline + (horizontal ? outward * (m.labelOffset + halfLine) : 0);
20056
20541
  if (!horizontal) {
20057
20542
  const first = Math.min(lineFrom.y, lineTo.y) + Math.max(halfLine + baseline, measured.actualBoundingBoxAscent ?? labelFont.getSize() * 0.75);
@@ -20607,6 +21092,11 @@ var ChartXY = class {
20607
21092
  observer;
20608
21093
  overlayContext;
20609
21094
  underlayContext;
21095
+ sharedCore;
21096
+ sharedPresent = null;
21097
+ sharedClient;
21098
+ sharedOffscreen = false;
21099
+ sharedDeferred = false;
20610
21100
  heatmapRenderer;
20611
21101
  heatmapPalettes = /* @__PURE__ */ new Map();
20612
21102
  heatCache = /* @__PURE__ */ new Map();
@@ -20693,7 +21183,7 @@ var ChartXY = class {
20693
21183
  this.underlay = underlay;
20694
21184
  this.overlay = overlay;
20695
21185
  try {
20696
- this.renderer = new DataRenderer(data, { antialias: options.antialias, renderer: options.renderer, lineCoverageUnion: options.experimentalLineCoverage === true, ownedCoverageFrame: options.experimentalOwnedCoverageFrame === true, gpuClipPolicy: this.gpuClipPolicy });
21186
+ this.renderer = new DataRenderer(data, { antialias: options.antialias, renderer: options.renderer, lineCoverageUnion: options.experimentalLineCoverage === true, ownedCoverageFrame: options.experimentalOwnedCoverageFrame === true, gpuClipPolicy: this.gpuClipPolicy, sharedContext: options.sharedContext ?? void 0 });
20697
21187
  } catch (error) {
20698
21188
  this.cssTextFonts?.dispose();
20699
21189
  root.remove();
@@ -20713,6 +21203,18 @@ var ChartXY = class {
20713
21203
  });
20714
21204
  this.observer.observe(container);
20715
21205
  }
21206
+ if (this.renderer?.sharedContext) {
21207
+ const sharedCore = sharedContextCore(this.renderer.sharedContext);
21208
+ this.sharedCore = sharedCore;
21209
+ this.sharedPresent = data.getContext("2d");
21210
+ const client = {
21211
+ root,
21212
+ setOffscreen: (offscreen) => this.setSharedOffscreen(offscreen)
21213
+ };
21214
+ this.sharedClient = client;
21215
+ sharedCore.register(client);
21216
+ this.cleanups.push(() => sharedCore.unregister(client));
21217
+ }
20716
21218
  }
20717
21219
  this.engine = {
20718
21220
  container: this.root ?? this.container,
@@ -21312,7 +21814,7 @@ var ChartXY = class {
21312
21814
  this.prepareCustomTickPlacementLengths(axesX, axesY);
21313
21815
  const layoutAxesX = axesX.filter((axis) => this.hasAxisLaneContent(axis));
21314
21816
  const layoutAxesY = axesY.filter((axis) => this.hasAxisLaneContent(axis));
21315
- this.axisCanvasLayout = this.kind === "xy" ? measureAxisCanvasLayout(this.overlayContext ?? void 0, layoutAxesX, layoutAxesY, this.theme, this.resolveTextFont) : void 0;
21817
+ this.axisCanvasLayout = this.kind === "xy" ? measureAxisCanvasLayout(this.overlayContext ?? void 0, layoutAxesX, layoutAxesY, this.theme, this.resolveTextFont, getAxisTextMetricsCache(this.overlayContext ?? void 0)) : void 0;
21316
21818
  const axisExtra = this.axisCanvasLayout?.extraMargins ?? { left: 0, right: 0, top: 0, bottom: 0 };
21317
21819
  const legendMargin = this.overlayContext ? this.legend.getLayout(this.overlayContext, this.legendArea()).margin : { left: 0, right: 0, top: 0, bottom: 0 };
21318
21820
  if (this.kind === "polar") {
@@ -21458,8 +21960,26 @@ var ChartXY = class {
21458
21960
  this.cancelAxisScrollAnimations();
21459
21961
  for (const series of this.series) series.cancelHighlightAnimation?.();
21460
21962
  }
21963
+ setSharedOffscreen(offscreen) {
21964
+ if (offscreen === this.sharedOffscreen || this.disposed) return;
21965
+ this.sharedOffscreen = offscreen;
21966
+ if (offscreen) {
21967
+ if (this.frame && typeof cancelAnimationFrame === "function") {
21968
+ cancelAnimationFrame(this.frame);
21969
+ this.frame = 0;
21970
+ this.sharedDeferred = true;
21971
+ }
21972
+ } else if (this.sharedDeferred) {
21973
+ this.sharedDeferred = false;
21974
+ this.invalidate();
21975
+ }
21976
+ }
21461
21977
  invalidate() {
21462
21978
  if (this.disposed || this.frame || this.rendering || !this.root) return;
21979
+ if (this.sharedOffscreen) {
21980
+ this.sharedDeferred = true;
21981
+ return;
21982
+ }
21463
21983
  if (typeof requestAnimationFrame === "function")
21464
21984
  this.frame = requestAnimationFrame((timestamp) => {
21465
21985
  this.frame = 0;
@@ -21913,6 +22433,8 @@ var ChartXY = class {
21913
22433
  ctx.drawImage(cache.canvas, r.left, r.top, r.width, r.height);
21914
22434
  }
21915
22435
  renderData(packets) {
22436
+ const shared = this.sharedCore;
22437
+ if (shared && !shared.beginChartDraw(this.canvas.width, this.canvas.height)) return;
21916
22438
  const grids = [];
21917
22439
  for (const s of this.series) {
21918
22440
  if (!(s instanceof HeatmapSeries) || !s.visible || s.disposed || !this.gpuHeatmap(s))
@@ -21983,7 +22505,7 @@ var ChartXY = class {
21983
22505
  this.heatmapRenderer = new DataRendererHeatmap(
21984
22506
  this.renderer.gl,
21985
22507
  this.canvas,
21986
- { clipPolicy: this.gpuClipPolicy }
22508
+ { clipPolicy: this.gpuClipPolicy, contextEvents: this.renderer.contextEvents }
21987
22509
  );
21988
22510
  const gl = this.renderer?.gl;
21989
22511
  const rasterTarget = this.gpuClipPolicy === "contained" && gl ? rasterTargetForRect(null, gl.drawingBufferWidth, gl.drawingBufferHeight, this.plot, this.dpr) : void 0;
@@ -22000,6 +22522,7 @@ var ChartXY = class {
22000
22522
  clear: grids.length === 0,
22001
22523
  rasterTarget
22002
22524
  });
22525
+ if (shared) shared.present(this.sharedPresent, this.canvas.width, this.canvas.height);
22003
22526
  }
22004
22527
  gpuHeatmap(s) {
22005
22528
  return !!this.renderer?.gl && s.axisX.type !== "logarithmic" && s.axisY.type !== "logarithmic";
@@ -23259,7 +23782,8 @@ var Chart3D = class extends ChartXY {
23259
23782
  gpuPackets = /* @__PURE__ */ new Map();
23260
23783
  gpuRevision = 0;
23261
23784
  constructor(options = {}) {
23262
- super({ ...options, antialias: options.antialias ?? true });
23785
+ if (options.sharedContext) throw new UnsupportedFeatureError("shared WebGL contexts for Chart3D");
23786
+ super({ ...options, sharedContext: null, antialias: options.antialias ?? true });
23263
23787
  this.cameraModel = options.experimental3DCameraModel === "legacy" ? "legacy" : "world";
23264
23788
  this.axesZ.push(new Axis(this, "z", options.defaultAxisZ));
23265
23789
  this.coordsAxis.z = this.axesZ[0];
@@ -24834,7 +25358,8 @@ function createCRYChartAdapter(container, options = {}) {
24834
25358
  const chart = new ChartXY({
24835
25359
  container,
24836
25360
  legend: { visible: false },
24837
- ...options.xScale === "logarithmic" ? { defaultAxisX: { type: "logarithmic", base: 10 } } : {}
25361
+ ...options.xScale === "logarithmic" ? { defaultAxisX: { type: "logarithmic", base: 10 } } : {},
25362
+ ...options.sharedContext ? { sharedContext: options.sharedContext } : {}
24838
25363
  });
24839
25364
  const entries = /* @__PURE__ */ new Map();
24840
25365
  let disposed = false;
@@ -25010,12 +25535,27 @@ function createCRYChartAdapter(container, options = {}) {
25010
25535
  }
25011
25536
 
25012
25537
  // src/index.ts
25013
- function cryChart(_options = {}) {
25538
+ function cryChart(options = {}) {
25539
+ if (options.sharedContext !== void 0 && options.sharedContextOptions !== void 0) {
25540
+ throw new TypeError(
25541
+ "Pass either sharedContext or sharedContextOptions, not both"
25542
+ );
25543
+ }
25544
+ if (options.sharedContext !== void 0 && !(options.sharedContext instanceof SharedWebGLContext)) {
25545
+ throw new TypeError("sharedContext must be a SharedWebGLContext");
25546
+ }
25547
+ if (options.sharedContext?.isDisposed()) {
25548
+ throw new Error("sharedContext has been disposed");
25549
+ }
25550
+ const shared = options.sharedContext ?? (options.sharedContextOptions ? new SharedWebGLContext(options.sharedContextOptions) : void 0);
25551
+ const ownsShared = !options.sharedContext && shared !== void 0;
25014
25552
  const owned2 = /* @__PURE__ */ new Set();
25015
25553
  let disposed = false;
25016
- const create = (ctor, options = {}) => {
25554
+ const create = (ctor, opts = {}) => {
25017
25555
  if (disposed) throw new Error("Chart context has been disposed");
25018
- const chart = new ctor(options);
25556
+ const injects = shared !== void 0 && (ctor === ChartXY || ctor === Polar || ctor === Dashboard) && !("sharedContext" in opts);
25557
+ const finalOptions = injects ? { ...opts, sharedContext: shared } : opts;
25558
+ const chart = new ctor(finalOptions);
25019
25559
  owned2.add(chart);
25020
25560
  chart.onDispose(() => owned2.delete(chart));
25021
25561
  return chart;
@@ -25046,17 +25586,25 @@ function cryChart(_options = {}) {
25046
25586
  } catch (error) {
25047
25587
  errors.push(error);
25048
25588
  }
25589
+ if (ownsShared) try {
25590
+ shared.dispose();
25591
+ } catch (error) {
25592
+ errors.push(error);
25593
+ }
25049
25594
  if (errors.length) throw new AggregateError(errors, "Some chart disposal callbacks failed");
25050
25595
  }
25051
25596
  },
25052
25597
  isDisposed: () => disposed,
25053
25598
  /** Live charts owned by this context; disposed charts are released immediately. */
25054
- getChartCount: () => owned2.size
25599
+ getChartCount: () => owned2.size,
25600
+ /** Shared WebGL2 context used by this context; undefined when not enabled. */
25601
+ getSharedContext: () => shared
25055
25602
  };
25056
25603
  }
25057
- var version = "1.0.6";
25604
+ var version = "1.0.8";
25058
25605
  var Dashboard = class {
25059
25606
  root;
25607
+ sharedContext;
25060
25608
  cells = /* @__PURE__ */ new Map();
25061
25609
  children = /* @__PURE__ */ new Set();
25062
25610
  events = new EventHub();
@@ -25068,6 +25616,7 @@ var Dashboard = class {
25068
25616
  throw new Error("Dashboard requires a DOM");
25069
25617
  const container = typeof options.container === "string" ? document.getElementById(options.container) : options.container ?? document.body;
25070
25618
  if (!container) throw new Error("Dashboard container was not found");
25619
+ this.sharedContext = options.sharedContext;
25071
25620
  this.root = document.createElement("div");
25072
25621
  this.columns = options.numberOfColumns ?? 2;
25073
25622
  this.rows = options.numberOfRows ?? 2;
@@ -25080,8 +25629,13 @@ var Dashboard = class {
25080
25629
  cell.style.cssText = `min-height:0;min-width:0;grid-column:${(options.columnIndex ?? 0) + 1}/span ${options.columnSpan ?? 1};grid-row:${(options.rowIndex ?? 0) + 1}/span ${options.rowSpan ?? 1}`;
25081
25630
  this.root.append(cell);
25082
25631
  let chart;
25632
+ const inject = this.sharedContext && (Ctor === ChartXY || Ctor === Polar) && !("sharedContext" in options);
25083
25633
  try {
25084
- chart = new Ctor({ ...options, container: cell });
25634
+ chart = new Ctor({
25635
+ ...options,
25636
+ ...inject ? { sharedContext: this.sharedContext } : {},
25637
+ container: cell
25638
+ });
25085
25639
  } catch (error) {
25086
25640
  cell.remove();
25087
25641
  throw error;
@@ -25232,6 +25786,7 @@ export {
25232
25786
  SegmentFigure,
25233
25787
  SegmentSeries,
25234
25788
  Series3DBase,
25789
+ SharedWebGLContext,
25235
25790
  SimpleShadingStyle,
25236
25791
  SlicedHierarchyChart,
25237
25792
  SolidFill,