@timeplus/vistral 0.1.1

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/index.js ADDED
@@ -0,0 +1,4850 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var require$$0 = require('react');
6
+ var g2 = require('@antv/g2');
7
+
8
+ var jsxRuntime = {exports: {}};
9
+
10
+ var reactJsxRuntime_production_min = {};
11
+
12
+ /**
13
+ * @license React
14
+ * react-jsx-runtime.production.min.js
15
+ *
16
+ * Copyright (c) Facebook, Inc. and its affiliates.
17
+ *
18
+ * This source code is licensed under the MIT license found in the
19
+ * LICENSE file in the root directory of this source tree.
20
+ */
21
+
22
+ var hasRequiredReactJsxRuntime_production_min;
23
+
24
+ function requireReactJsxRuntime_production_min () {
25
+ if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
26
+ hasRequiredReactJsxRuntime_production_min = 1;
27
+ var f=require$$0,k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};
28
+ function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return {$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}reactJsxRuntime_production_min.Fragment=l;reactJsxRuntime_production_min.jsx=q;reactJsxRuntime_production_min.jsxs=q;
29
+ return reactJsxRuntime_production_min;
30
+ }
31
+
32
+ var reactJsxRuntime_development = {};
33
+
34
+ /**
35
+ * @license React
36
+ * react-jsx-runtime.development.js
37
+ *
38
+ * Copyright (c) Facebook, Inc. and its affiliates.
39
+ *
40
+ * This source code is licensed under the MIT license found in the
41
+ * LICENSE file in the root directory of this source tree.
42
+ */
43
+
44
+ var hasRequiredReactJsxRuntime_development;
45
+
46
+ function requireReactJsxRuntime_development () {
47
+ if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
48
+ hasRequiredReactJsxRuntime_development = 1;
49
+
50
+ if (process.env.NODE_ENV !== "production") {
51
+ (function() {
52
+
53
+ var React = require$$0;
54
+
55
+ // ATTENTION
56
+ // When adding new symbols to this file,
57
+ // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
58
+ // The Symbol used to tag the ReactElement-like types.
59
+ var REACT_ELEMENT_TYPE = Symbol.for('react.element');
60
+ var REACT_PORTAL_TYPE = Symbol.for('react.portal');
61
+ var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
62
+ var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
63
+ var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
64
+ var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
65
+ var REACT_CONTEXT_TYPE = Symbol.for('react.context');
66
+ var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
67
+ var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
68
+ var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
69
+ var REACT_MEMO_TYPE = Symbol.for('react.memo');
70
+ var REACT_LAZY_TYPE = Symbol.for('react.lazy');
71
+ var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
72
+ var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
73
+ var FAUX_ITERATOR_SYMBOL = '@@iterator';
74
+ function getIteratorFn(maybeIterable) {
75
+ if (maybeIterable === null || typeof maybeIterable !== 'object') {
76
+ return null;
77
+ }
78
+
79
+ var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
80
+
81
+ if (typeof maybeIterator === 'function') {
82
+ return maybeIterator;
83
+ }
84
+
85
+ return null;
86
+ }
87
+
88
+ var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
89
+
90
+ function error(format) {
91
+ {
92
+ {
93
+ for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
94
+ args[_key2 - 1] = arguments[_key2];
95
+ }
96
+
97
+ printWarning('error', format, args);
98
+ }
99
+ }
100
+ }
101
+
102
+ function printWarning(level, format, args) {
103
+ // When changing this logic, you might want to also
104
+ // update consoleWithStackDev.www.js as well.
105
+ {
106
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
107
+ var stack = ReactDebugCurrentFrame.getStackAddendum();
108
+
109
+ if (stack !== '') {
110
+ format += '%s';
111
+ args = args.concat([stack]);
112
+ } // eslint-disable-next-line react-internal/safe-string-coercion
113
+
114
+
115
+ var argsWithFormat = args.map(function (item) {
116
+ return String(item);
117
+ }); // Careful: RN currently depends on this prefix
118
+
119
+ argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
120
+ // breaks IE9: https://github.com/facebook/react/issues/13610
121
+ // eslint-disable-next-line react-internal/no-production-logging
122
+
123
+ Function.prototype.apply.call(console[level], console, argsWithFormat);
124
+ }
125
+ }
126
+
127
+ // -----------------------------------------------------------------------------
128
+
129
+ var enableScopeAPI = false; // Experimental Create Event Handle API.
130
+ var enableCacheElement = false;
131
+ var enableTransitionTracing = false; // No known bugs, but needs performance testing
132
+
133
+ var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
134
+ // stuff. Intended to enable React core members to more easily debug scheduling
135
+ // issues in DEV builds.
136
+
137
+ var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
138
+
139
+ var REACT_MODULE_REFERENCE;
140
+
141
+ {
142
+ REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
143
+ }
144
+
145
+ function isValidElementType(type) {
146
+ if (typeof type === 'string' || typeof type === 'function') {
147
+ return true;
148
+ } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
149
+
150
+
151
+ if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {
152
+ return true;
153
+ }
154
+
155
+ if (typeof type === 'object' && type !== null) {
156
+ if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
157
+ // types supported by any Flight configuration anywhere since
158
+ // we don't know which Flight build this will end up being used
159
+ // with.
160
+ type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
161
+ return true;
162
+ }
163
+ }
164
+
165
+ return false;
166
+ }
167
+
168
+ function getWrappedName(outerType, innerType, wrapperName) {
169
+ var displayName = outerType.displayName;
170
+
171
+ if (displayName) {
172
+ return displayName;
173
+ }
174
+
175
+ var functionName = innerType.displayName || innerType.name || '';
176
+ return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
177
+ } // Keep in sync with react-reconciler/getComponentNameFromFiber
178
+
179
+
180
+ function getContextName(type) {
181
+ return type.displayName || 'Context';
182
+ } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
183
+
184
+
185
+ function getComponentNameFromType(type) {
186
+ if (type == null) {
187
+ // Host root, text node or just invalid type.
188
+ return null;
189
+ }
190
+
191
+ {
192
+ if (typeof type.tag === 'number') {
193
+ error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
194
+ }
195
+ }
196
+
197
+ if (typeof type === 'function') {
198
+ return type.displayName || type.name || null;
199
+ }
200
+
201
+ if (typeof type === 'string') {
202
+ return type;
203
+ }
204
+
205
+ switch (type) {
206
+ case REACT_FRAGMENT_TYPE:
207
+ return 'Fragment';
208
+
209
+ case REACT_PORTAL_TYPE:
210
+ return 'Portal';
211
+
212
+ case REACT_PROFILER_TYPE:
213
+ return 'Profiler';
214
+
215
+ case REACT_STRICT_MODE_TYPE:
216
+ return 'StrictMode';
217
+
218
+ case REACT_SUSPENSE_TYPE:
219
+ return 'Suspense';
220
+
221
+ case REACT_SUSPENSE_LIST_TYPE:
222
+ return 'SuspenseList';
223
+
224
+ }
225
+
226
+ if (typeof type === 'object') {
227
+ switch (type.$$typeof) {
228
+ case REACT_CONTEXT_TYPE:
229
+ var context = type;
230
+ return getContextName(context) + '.Consumer';
231
+
232
+ case REACT_PROVIDER_TYPE:
233
+ var provider = type;
234
+ return getContextName(provider._context) + '.Provider';
235
+
236
+ case REACT_FORWARD_REF_TYPE:
237
+ return getWrappedName(type, type.render, 'ForwardRef');
238
+
239
+ case REACT_MEMO_TYPE:
240
+ var outerName = type.displayName || null;
241
+
242
+ if (outerName !== null) {
243
+ return outerName;
244
+ }
245
+
246
+ return getComponentNameFromType(type.type) || 'Memo';
247
+
248
+ case REACT_LAZY_TYPE:
249
+ {
250
+ var lazyComponent = type;
251
+ var payload = lazyComponent._payload;
252
+ var init = lazyComponent._init;
253
+
254
+ try {
255
+ return getComponentNameFromType(init(payload));
256
+ } catch (x) {
257
+ return null;
258
+ }
259
+ }
260
+
261
+ // eslint-disable-next-line no-fallthrough
262
+ }
263
+ }
264
+
265
+ return null;
266
+ }
267
+
268
+ var assign = Object.assign;
269
+
270
+ // Helpers to patch console.logs to avoid logging during side-effect free
271
+ // replaying on render function. This currently only patches the object
272
+ // lazily which won't cover if the log function was extracted eagerly.
273
+ // We could also eagerly patch the method.
274
+ var disabledDepth = 0;
275
+ var prevLog;
276
+ var prevInfo;
277
+ var prevWarn;
278
+ var prevError;
279
+ var prevGroup;
280
+ var prevGroupCollapsed;
281
+ var prevGroupEnd;
282
+
283
+ function disabledLog() {}
284
+
285
+ disabledLog.__reactDisabledLog = true;
286
+ function disableLogs() {
287
+ {
288
+ if (disabledDepth === 0) {
289
+ /* eslint-disable react-internal/no-production-logging */
290
+ prevLog = console.log;
291
+ prevInfo = console.info;
292
+ prevWarn = console.warn;
293
+ prevError = console.error;
294
+ prevGroup = console.group;
295
+ prevGroupCollapsed = console.groupCollapsed;
296
+ prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
297
+
298
+ var props = {
299
+ configurable: true,
300
+ enumerable: true,
301
+ value: disabledLog,
302
+ writable: true
303
+ }; // $FlowFixMe Flow thinks console is immutable.
304
+
305
+ Object.defineProperties(console, {
306
+ info: props,
307
+ log: props,
308
+ warn: props,
309
+ error: props,
310
+ group: props,
311
+ groupCollapsed: props,
312
+ groupEnd: props
313
+ });
314
+ /* eslint-enable react-internal/no-production-logging */
315
+ }
316
+
317
+ disabledDepth++;
318
+ }
319
+ }
320
+ function reenableLogs() {
321
+ {
322
+ disabledDepth--;
323
+
324
+ if (disabledDepth === 0) {
325
+ /* eslint-disable react-internal/no-production-logging */
326
+ var props = {
327
+ configurable: true,
328
+ enumerable: true,
329
+ writable: true
330
+ }; // $FlowFixMe Flow thinks console is immutable.
331
+
332
+ Object.defineProperties(console, {
333
+ log: assign({}, props, {
334
+ value: prevLog
335
+ }),
336
+ info: assign({}, props, {
337
+ value: prevInfo
338
+ }),
339
+ warn: assign({}, props, {
340
+ value: prevWarn
341
+ }),
342
+ error: assign({}, props, {
343
+ value: prevError
344
+ }),
345
+ group: assign({}, props, {
346
+ value: prevGroup
347
+ }),
348
+ groupCollapsed: assign({}, props, {
349
+ value: prevGroupCollapsed
350
+ }),
351
+ groupEnd: assign({}, props, {
352
+ value: prevGroupEnd
353
+ })
354
+ });
355
+ /* eslint-enable react-internal/no-production-logging */
356
+ }
357
+
358
+ if (disabledDepth < 0) {
359
+ error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
360
+ }
361
+ }
362
+ }
363
+
364
+ var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
365
+ var prefix;
366
+ function describeBuiltInComponentFrame(name, source, ownerFn) {
367
+ {
368
+ if (prefix === undefined) {
369
+ // Extract the VM specific prefix used by each line.
370
+ try {
371
+ throw Error();
372
+ } catch (x) {
373
+ var match = x.stack.trim().match(/\n( *(at )?)/);
374
+ prefix = match && match[1] || '';
375
+ }
376
+ } // We use the prefix to ensure our stacks line up with native stack frames.
377
+
378
+
379
+ return '\n' + prefix + name;
380
+ }
381
+ }
382
+ var reentry = false;
383
+ var componentFrameCache;
384
+
385
+ {
386
+ var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
387
+ componentFrameCache = new PossiblyWeakMap();
388
+ }
389
+
390
+ function describeNativeComponentFrame(fn, construct) {
391
+ // If something asked for a stack inside a fake render, it should get ignored.
392
+ if ( !fn || reentry) {
393
+ return '';
394
+ }
395
+
396
+ {
397
+ var frame = componentFrameCache.get(fn);
398
+
399
+ if (frame !== undefined) {
400
+ return frame;
401
+ }
402
+ }
403
+
404
+ var control;
405
+ reentry = true;
406
+ var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
407
+
408
+ Error.prepareStackTrace = undefined;
409
+ var previousDispatcher;
410
+
411
+ {
412
+ previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
413
+ // for warnings.
414
+
415
+ ReactCurrentDispatcher.current = null;
416
+ disableLogs();
417
+ }
418
+
419
+ try {
420
+ // This should throw.
421
+ if (construct) {
422
+ // Something should be setting the props in the constructor.
423
+ var Fake = function () {
424
+ throw Error();
425
+ }; // $FlowFixMe
426
+
427
+
428
+ Object.defineProperty(Fake.prototype, 'props', {
429
+ set: function () {
430
+ // We use a throwing setter instead of frozen or non-writable props
431
+ // because that won't throw in a non-strict mode function.
432
+ throw Error();
433
+ }
434
+ });
435
+
436
+ if (typeof Reflect === 'object' && Reflect.construct) {
437
+ // We construct a different control for this case to include any extra
438
+ // frames added by the construct call.
439
+ try {
440
+ Reflect.construct(Fake, []);
441
+ } catch (x) {
442
+ control = x;
443
+ }
444
+
445
+ Reflect.construct(fn, [], Fake);
446
+ } else {
447
+ try {
448
+ Fake.call();
449
+ } catch (x) {
450
+ control = x;
451
+ }
452
+
453
+ fn.call(Fake.prototype);
454
+ }
455
+ } else {
456
+ try {
457
+ throw Error();
458
+ } catch (x) {
459
+ control = x;
460
+ }
461
+
462
+ fn();
463
+ }
464
+ } catch (sample) {
465
+ // This is inlined manually because closure doesn't do it for us.
466
+ if (sample && control && typeof sample.stack === 'string') {
467
+ // This extracts the first frame from the sample that isn't also in the control.
468
+ // Skipping one frame that we assume is the frame that calls the two.
469
+ var sampleLines = sample.stack.split('\n');
470
+ var controlLines = control.stack.split('\n');
471
+ var s = sampleLines.length - 1;
472
+ var c = controlLines.length - 1;
473
+
474
+ while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
475
+ // We expect at least one stack frame to be shared.
476
+ // Typically this will be the root most one. However, stack frames may be
477
+ // cut off due to maximum stack limits. In this case, one maybe cut off
478
+ // earlier than the other. We assume that the sample is longer or the same
479
+ // and there for cut off earlier. So we should find the root most frame in
480
+ // the sample somewhere in the control.
481
+ c--;
482
+ }
483
+
484
+ for (; s >= 1 && c >= 0; s--, c--) {
485
+ // Next we find the first one that isn't the same which should be the
486
+ // frame that called our sample function and the control.
487
+ if (sampleLines[s] !== controlLines[c]) {
488
+ // In V8, the first line is describing the message but other VMs don't.
489
+ // If we're about to return the first line, and the control is also on the same
490
+ // line, that's a pretty good indicator that our sample threw at same line as
491
+ // the control. I.e. before we entered the sample frame. So we ignore this result.
492
+ // This can happen if you passed a class to function component, or non-function.
493
+ if (s !== 1 || c !== 1) {
494
+ do {
495
+ s--;
496
+ c--; // We may still have similar intermediate frames from the construct call.
497
+ // The next one that isn't the same should be our match though.
498
+
499
+ if (c < 0 || sampleLines[s] !== controlLines[c]) {
500
+ // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
501
+ var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
502
+ // but we have a user-provided "displayName"
503
+ // splice it in to make the stack more readable.
504
+
505
+
506
+ if (fn.displayName && _frame.includes('<anonymous>')) {
507
+ _frame = _frame.replace('<anonymous>', fn.displayName);
508
+ }
509
+
510
+ {
511
+ if (typeof fn === 'function') {
512
+ componentFrameCache.set(fn, _frame);
513
+ }
514
+ } // Return the line we found.
515
+
516
+
517
+ return _frame;
518
+ }
519
+ } while (s >= 1 && c >= 0);
520
+ }
521
+
522
+ break;
523
+ }
524
+ }
525
+ }
526
+ } finally {
527
+ reentry = false;
528
+
529
+ {
530
+ ReactCurrentDispatcher.current = previousDispatcher;
531
+ reenableLogs();
532
+ }
533
+
534
+ Error.prepareStackTrace = previousPrepareStackTrace;
535
+ } // Fallback to just using the name if we couldn't make it throw.
536
+
537
+
538
+ var name = fn ? fn.displayName || fn.name : '';
539
+ var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
540
+
541
+ {
542
+ if (typeof fn === 'function') {
543
+ componentFrameCache.set(fn, syntheticFrame);
544
+ }
545
+ }
546
+
547
+ return syntheticFrame;
548
+ }
549
+ function describeFunctionComponentFrame(fn, source, ownerFn) {
550
+ {
551
+ return describeNativeComponentFrame(fn, false);
552
+ }
553
+ }
554
+
555
+ function shouldConstruct(Component) {
556
+ var prototype = Component.prototype;
557
+ return !!(prototype && prototype.isReactComponent);
558
+ }
559
+
560
+ function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
561
+
562
+ if (type == null) {
563
+ return '';
564
+ }
565
+
566
+ if (typeof type === 'function') {
567
+ {
568
+ return describeNativeComponentFrame(type, shouldConstruct(type));
569
+ }
570
+ }
571
+
572
+ if (typeof type === 'string') {
573
+ return describeBuiltInComponentFrame(type);
574
+ }
575
+
576
+ switch (type) {
577
+ case REACT_SUSPENSE_TYPE:
578
+ return describeBuiltInComponentFrame('Suspense');
579
+
580
+ case REACT_SUSPENSE_LIST_TYPE:
581
+ return describeBuiltInComponentFrame('SuspenseList');
582
+ }
583
+
584
+ if (typeof type === 'object') {
585
+ switch (type.$$typeof) {
586
+ case REACT_FORWARD_REF_TYPE:
587
+ return describeFunctionComponentFrame(type.render);
588
+
589
+ case REACT_MEMO_TYPE:
590
+ // Memo may contain any component type so we recursively resolve it.
591
+ return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
592
+
593
+ case REACT_LAZY_TYPE:
594
+ {
595
+ var lazyComponent = type;
596
+ var payload = lazyComponent._payload;
597
+ var init = lazyComponent._init;
598
+
599
+ try {
600
+ // Lazy may contain any component type so we recursively resolve it.
601
+ return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
602
+ } catch (x) {}
603
+ }
604
+ }
605
+ }
606
+
607
+ return '';
608
+ }
609
+
610
+ var hasOwnProperty = Object.prototype.hasOwnProperty;
611
+
612
+ var loggedTypeFailures = {};
613
+ var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
614
+
615
+ function setCurrentlyValidatingElement(element) {
616
+ {
617
+ if (element) {
618
+ var owner = element._owner;
619
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
620
+ ReactDebugCurrentFrame.setExtraStackFrame(stack);
621
+ } else {
622
+ ReactDebugCurrentFrame.setExtraStackFrame(null);
623
+ }
624
+ }
625
+ }
626
+
627
+ function checkPropTypes(typeSpecs, values, location, componentName, element) {
628
+ {
629
+ // $FlowFixMe This is okay but Flow doesn't know it.
630
+ var has = Function.call.bind(hasOwnProperty);
631
+
632
+ for (var typeSpecName in typeSpecs) {
633
+ if (has(typeSpecs, typeSpecName)) {
634
+ var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
635
+ // fail the render phase where it didn't fail before. So we log it.
636
+ // After these have been cleaned up, we'll let them throw.
637
+
638
+ try {
639
+ // This is intentionally an invariant that gets caught. It's the same
640
+ // behavior as without this statement except with a better message.
641
+ if (typeof typeSpecs[typeSpecName] !== 'function') {
642
+ // eslint-disable-next-line react-internal/prod-error-codes
643
+ var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
644
+ err.name = 'Invariant Violation';
645
+ throw err;
646
+ }
647
+
648
+ error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
649
+ } catch (ex) {
650
+ error$1 = ex;
651
+ }
652
+
653
+ if (error$1 && !(error$1 instanceof Error)) {
654
+ setCurrentlyValidatingElement(element);
655
+
656
+ error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
657
+
658
+ setCurrentlyValidatingElement(null);
659
+ }
660
+
661
+ if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
662
+ // Only monitor this failure once because there tends to be a lot of the
663
+ // same error.
664
+ loggedTypeFailures[error$1.message] = true;
665
+ setCurrentlyValidatingElement(element);
666
+
667
+ error('Failed %s type: %s', location, error$1.message);
668
+
669
+ setCurrentlyValidatingElement(null);
670
+ }
671
+ }
672
+ }
673
+ }
674
+ }
675
+
676
+ var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
677
+
678
+ function isArray(a) {
679
+ return isArrayImpl(a);
680
+ }
681
+
682
+ /*
683
+ * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
684
+ * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
685
+ *
686
+ * The functions in this module will throw an easier-to-understand,
687
+ * easier-to-debug exception with a clear errors message message explaining the
688
+ * problem. (Instead of a confusing exception thrown inside the implementation
689
+ * of the `value` object).
690
+ */
691
+ // $FlowFixMe only called in DEV, so void return is not possible.
692
+ function typeName(value) {
693
+ {
694
+ // toStringTag is needed for namespaced types like Temporal.Instant
695
+ var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
696
+ var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
697
+ return type;
698
+ }
699
+ } // $FlowFixMe only called in DEV, so void return is not possible.
700
+
701
+
702
+ function willCoercionThrow(value) {
703
+ {
704
+ try {
705
+ testStringCoercion(value);
706
+ return false;
707
+ } catch (e) {
708
+ return true;
709
+ }
710
+ }
711
+ }
712
+
713
+ function testStringCoercion(value) {
714
+ // If you ended up here by following an exception call stack, here's what's
715
+ // happened: you supplied an object or symbol value to React (as a prop, key,
716
+ // DOM attribute, CSS property, string ref, etc.) and when React tried to
717
+ // coerce it to a string using `'' + value`, an exception was thrown.
718
+ //
719
+ // The most common types that will cause this exception are `Symbol` instances
720
+ // and Temporal objects like `Temporal.Instant`. But any object that has a
721
+ // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
722
+ // exception. (Library authors do this to prevent users from using built-in
723
+ // numeric operators like `+` or comparison operators like `>=` because custom
724
+ // methods are needed to perform accurate arithmetic or comparison.)
725
+ //
726
+ // To fix the problem, coerce this object or symbol value to a string before
727
+ // passing it to React. The most reliable way is usually `String(value)`.
728
+ //
729
+ // To find which value is throwing, check the browser or debugger console.
730
+ // Before this exception was thrown, there should be `console.error` output
731
+ // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
732
+ // problem and how that type was used: key, atrribute, input value prop, etc.
733
+ // In most cases, this console output also shows the component and its
734
+ // ancestor components where the exception happened.
735
+ //
736
+ // eslint-disable-next-line react-internal/safe-string-coercion
737
+ return '' + value;
738
+ }
739
+ function checkKeyStringCoercion(value) {
740
+ {
741
+ if (willCoercionThrow(value)) {
742
+ error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
743
+
744
+ return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
745
+ }
746
+ }
747
+ }
748
+
749
+ var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
750
+ var RESERVED_PROPS = {
751
+ key: true,
752
+ ref: true,
753
+ __self: true,
754
+ __source: true
755
+ };
756
+ var specialPropKeyWarningShown;
757
+ var specialPropRefWarningShown;
758
+ var didWarnAboutStringRefs;
759
+
760
+ {
761
+ didWarnAboutStringRefs = {};
762
+ }
763
+
764
+ function hasValidRef(config) {
765
+ {
766
+ if (hasOwnProperty.call(config, 'ref')) {
767
+ var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
768
+
769
+ if (getter && getter.isReactWarning) {
770
+ return false;
771
+ }
772
+ }
773
+ }
774
+
775
+ return config.ref !== undefined;
776
+ }
777
+
778
+ function hasValidKey(config) {
779
+ {
780
+ if (hasOwnProperty.call(config, 'key')) {
781
+ var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
782
+
783
+ if (getter && getter.isReactWarning) {
784
+ return false;
785
+ }
786
+ }
787
+ }
788
+
789
+ return config.key !== undefined;
790
+ }
791
+
792
+ function warnIfStringRefCannotBeAutoConverted(config, self) {
793
+ {
794
+ if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
795
+ var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
796
+
797
+ if (!didWarnAboutStringRefs[componentName]) {
798
+ error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);
799
+
800
+ didWarnAboutStringRefs[componentName] = true;
801
+ }
802
+ }
803
+ }
804
+ }
805
+
806
+ function defineKeyPropWarningGetter(props, displayName) {
807
+ {
808
+ var warnAboutAccessingKey = function () {
809
+ if (!specialPropKeyWarningShown) {
810
+ specialPropKeyWarningShown = true;
811
+
812
+ error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
813
+ }
814
+ };
815
+
816
+ warnAboutAccessingKey.isReactWarning = true;
817
+ Object.defineProperty(props, 'key', {
818
+ get: warnAboutAccessingKey,
819
+ configurable: true
820
+ });
821
+ }
822
+ }
823
+
824
+ function defineRefPropWarningGetter(props, displayName) {
825
+ {
826
+ var warnAboutAccessingRef = function () {
827
+ if (!specialPropRefWarningShown) {
828
+ specialPropRefWarningShown = true;
829
+
830
+ error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
831
+ }
832
+ };
833
+
834
+ warnAboutAccessingRef.isReactWarning = true;
835
+ Object.defineProperty(props, 'ref', {
836
+ get: warnAboutAccessingRef,
837
+ configurable: true
838
+ });
839
+ }
840
+ }
841
+ /**
842
+ * Factory method to create a new React element. This no longer adheres to
843
+ * the class pattern, so do not use new to call it. Also, instanceof check
844
+ * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
845
+ * if something is a React Element.
846
+ *
847
+ * @param {*} type
848
+ * @param {*} props
849
+ * @param {*} key
850
+ * @param {string|object} ref
851
+ * @param {*} owner
852
+ * @param {*} self A *temporary* helper to detect places where `this` is
853
+ * different from the `owner` when React.createElement is called, so that we
854
+ * can warn. We want to get rid of owner and replace string `ref`s with arrow
855
+ * functions, and as long as `this` and owner are the same, there will be no
856
+ * change in behavior.
857
+ * @param {*} source An annotation object (added by a transpiler or otherwise)
858
+ * indicating filename, line number, and/or other information.
859
+ * @internal
860
+ */
861
+
862
+
863
+ var ReactElement = function (type, key, ref, self, source, owner, props) {
864
+ var element = {
865
+ // This tag allows us to uniquely identify this as a React Element
866
+ $$typeof: REACT_ELEMENT_TYPE,
867
+ // Built-in properties that belong on the element
868
+ type: type,
869
+ key: key,
870
+ ref: ref,
871
+ props: props,
872
+ // Record the component responsible for creating this element.
873
+ _owner: owner
874
+ };
875
+
876
+ {
877
+ // The validation flag is currently mutative. We put it on
878
+ // an external backing store so that we can freeze the whole object.
879
+ // This can be replaced with a WeakMap once they are implemented in
880
+ // commonly used development environments.
881
+ element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
882
+ // the validation flag non-enumerable (where possible, which should
883
+ // include every environment we run tests in), so the test framework
884
+ // ignores it.
885
+
886
+ Object.defineProperty(element._store, 'validated', {
887
+ configurable: false,
888
+ enumerable: false,
889
+ writable: true,
890
+ value: false
891
+ }); // self and source are DEV only properties.
892
+
893
+ Object.defineProperty(element, '_self', {
894
+ configurable: false,
895
+ enumerable: false,
896
+ writable: false,
897
+ value: self
898
+ }); // Two elements created in two different places should be considered
899
+ // equal for testing purposes and therefore we hide it from enumeration.
900
+
901
+ Object.defineProperty(element, '_source', {
902
+ configurable: false,
903
+ enumerable: false,
904
+ writable: false,
905
+ value: source
906
+ });
907
+
908
+ if (Object.freeze) {
909
+ Object.freeze(element.props);
910
+ Object.freeze(element);
911
+ }
912
+ }
913
+
914
+ return element;
915
+ };
916
+ /**
917
+ * https://github.com/reactjs/rfcs/pull/107
918
+ * @param {*} type
919
+ * @param {object} props
920
+ * @param {string} key
921
+ */
922
+
923
+ function jsxDEV(type, config, maybeKey, source, self) {
924
+ {
925
+ var propName; // Reserved names are extracted
926
+
927
+ var props = {};
928
+ var key = null;
929
+ var ref = null; // Currently, key can be spread in as a prop. This causes a potential
930
+ // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
931
+ // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
932
+ // but as an intermediary step, we will use jsxDEV for everything except
933
+ // <div {...props} key="Hi" />, because we aren't currently able to tell if
934
+ // key is explicitly declared to be undefined or not.
935
+
936
+ if (maybeKey !== undefined) {
937
+ {
938
+ checkKeyStringCoercion(maybeKey);
939
+ }
940
+
941
+ key = '' + maybeKey;
942
+ }
943
+
944
+ if (hasValidKey(config)) {
945
+ {
946
+ checkKeyStringCoercion(config.key);
947
+ }
948
+
949
+ key = '' + config.key;
950
+ }
951
+
952
+ if (hasValidRef(config)) {
953
+ ref = config.ref;
954
+ warnIfStringRefCannotBeAutoConverted(config, self);
955
+ } // Remaining properties are added to a new props object
956
+
957
+
958
+ for (propName in config) {
959
+ if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
960
+ props[propName] = config[propName];
961
+ }
962
+ } // Resolve default props
963
+
964
+
965
+ if (type && type.defaultProps) {
966
+ var defaultProps = type.defaultProps;
967
+
968
+ for (propName in defaultProps) {
969
+ if (props[propName] === undefined) {
970
+ props[propName] = defaultProps[propName];
971
+ }
972
+ }
973
+ }
974
+
975
+ if (key || ref) {
976
+ var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
977
+
978
+ if (key) {
979
+ defineKeyPropWarningGetter(props, displayName);
980
+ }
981
+
982
+ if (ref) {
983
+ defineRefPropWarningGetter(props, displayName);
984
+ }
985
+ }
986
+
987
+ return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
988
+ }
989
+ }
990
+
991
+ var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
992
+ var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
993
+
994
+ function setCurrentlyValidatingElement$1(element) {
995
+ {
996
+ if (element) {
997
+ var owner = element._owner;
998
+ var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
999
+ ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
1000
+ } else {
1001
+ ReactDebugCurrentFrame$1.setExtraStackFrame(null);
1002
+ }
1003
+ }
1004
+ }
1005
+
1006
+ var propTypesMisspellWarningShown;
1007
+
1008
+ {
1009
+ propTypesMisspellWarningShown = false;
1010
+ }
1011
+ /**
1012
+ * Verifies the object is a ReactElement.
1013
+ * See https://reactjs.org/docs/react-api.html#isvalidelement
1014
+ * @param {?object} object
1015
+ * @return {boolean} True if `object` is a ReactElement.
1016
+ * @final
1017
+ */
1018
+
1019
+
1020
+ function isValidElement(object) {
1021
+ {
1022
+ return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1023
+ }
1024
+ }
1025
+
1026
+ function getDeclarationErrorAddendum() {
1027
+ {
1028
+ if (ReactCurrentOwner$1.current) {
1029
+ var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
1030
+
1031
+ if (name) {
1032
+ return '\n\nCheck the render method of `' + name + '`.';
1033
+ }
1034
+ }
1035
+
1036
+ return '';
1037
+ }
1038
+ }
1039
+
1040
+ function getSourceInfoErrorAddendum(source) {
1041
+ {
1042
+ if (source !== undefined) {
1043
+ var fileName = source.fileName.replace(/^.*[\\\/]/, '');
1044
+ var lineNumber = source.lineNumber;
1045
+ return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
1046
+ }
1047
+
1048
+ return '';
1049
+ }
1050
+ }
1051
+ /**
1052
+ * Warn if there's no key explicitly set on dynamic arrays of children or
1053
+ * object keys are not valid. This allows us to keep track of children between
1054
+ * updates.
1055
+ */
1056
+
1057
+
1058
+ var ownerHasKeyUseWarning = {};
1059
+
1060
+ function getCurrentComponentErrorInfo(parentType) {
1061
+ {
1062
+ var info = getDeclarationErrorAddendum();
1063
+
1064
+ if (!info) {
1065
+ var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
1066
+
1067
+ if (parentName) {
1068
+ info = "\n\nCheck the top-level render call using <" + parentName + ">.";
1069
+ }
1070
+ }
1071
+
1072
+ return info;
1073
+ }
1074
+ }
1075
+ /**
1076
+ * Warn if the element doesn't have an explicit key assigned to it.
1077
+ * This element is in an array. The array could grow and shrink or be
1078
+ * reordered. All children that haven't already been validated are required to
1079
+ * have a "key" property assigned to it. Error statuses are cached so a warning
1080
+ * will only be shown once.
1081
+ *
1082
+ * @internal
1083
+ * @param {ReactElement} element Element that requires a key.
1084
+ * @param {*} parentType element's parent's type.
1085
+ */
1086
+
1087
+
1088
+ function validateExplicitKey(element, parentType) {
1089
+ {
1090
+ if (!element._store || element._store.validated || element.key != null) {
1091
+ return;
1092
+ }
1093
+
1094
+ element._store.validated = true;
1095
+ var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
1096
+
1097
+ if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
1098
+ return;
1099
+ }
1100
+
1101
+ ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
1102
+ // property, it may be the creator of the child that's responsible for
1103
+ // assigning it a key.
1104
+
1105
+ var childOwner = '';
1106
+
1107
+ if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
1108
+ // Give the component that originally created this child.
1109
+ childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
1110
+ }
1111
+
1112
+ setCurrentlyValidatingElement$1(element);
1113
+
1114
+ error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
1115
+
1116
+ setCurrentlyValidatingElement$1(null);
1117
+ }
1118
+ }
1119
+ /**
1120
+ * Ensure that every element either is passed in a static location, in an
1121
+ * array with an explicit keys property defined, or in an object literal
1122
+ * with valid key property.
1123
+ *
1124
+ * @internal
1125
+ * @param {ReactNode} node Statically passed child of any type.
1126
+ * @param {*} parentType node's parent's type.
1127
+ */
1128
+
1129
+
1130
+ function validateChildKeys(node, parentType) {
1131
+ {
1132
+ if (typeof node !== 'object') {
1133
+ return;
1134
+ }
1135
+
1136
+ if (isArray(node)) {
1137
+ for (var i = 0; i < node.length; i++) {
1138
+ var child = node[i];
1139
+
1140
+ if (isValidElement(child)) {
1141
+ validateExplicitKey(child, parentType);
1142
+ }
1143
+ }
1144
+ } else if (isValidElement(node)) {
1145
+ // This element was passed in a valid location.
1146
+ if (node._store) {
1147
+ node._store.validated = true;
1148
+ }
1149
+ } else if (node) {
1150
+ var iteratorFn = getIteratorFn(node);
1151
+
1152
+ if (typeof iteratorFn === 'function') {
1153
+ // Entry iterators used to provide implicit keys,
1154
+ // but now we print a separate warning for them later.
1155
+ if (iteratorFn !== node.entries) {
1156
+ var iterator = iteratorFn.call(node);
1157
+ var step;
1158
+
1159
+ while (!(step = iterator.next()).done) {
1160
+ if (isValidElement(step.value)) {
1161
+ validateExplicitKey(step.value, parentType);
1162
+ }
1163
+ }
1164
+ }
1165
+ }
1166
+ }
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Given an element, validate that its props follow the propTypes definition,
1171
+ * provided by the type.
1172
+ *
1173
+ * @param {ReactElement} element
1174
+ */
1175
+
1176
+
1177
+ function validatePropTypes(element) {
1178
+ {
1179
+ var type = element.type;
1180
+
1181
+ if (type === null || type === undefined || typeof type === 'string') {
1182
+ return;
1183
+ }
1184
+
1185
+ var propTypes;
1186
+
1187
+ if (typeof type === 'function') {
1188
+ propTypes = type.propTypes;
1189
+ } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
1190
+ // Inner props are checked in the reconciler.
1191
+ type.$$typeof === REACT_MEMO_TYPE)) {
1192
+ propTypes = type.propTypes;
1193
+ } else {
1194
+ return;
1195
+ }
1196
+
1197
+ if (propTypes) {
1198
+ // Intentionally inside to avoid triggering lazy initializers:
1199
+ var name = getComponentNameFromType(type);
1200
+ checkPropTypes(propTypes, element.props, 'prop', name, element);
1201
+ } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
1202
+ propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
1203
+
1204
+ var _name = getComponentNameFromType(type);
1205
+
1206
+ error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
1207
+ }
1208
+
1209
+ if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
1210
+ error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
1211
+ }
1212
+ }
1213
+ }
1214
+ /**
1215
+ * Given a fragment, validate that it can only be provided with fragment props
1216
+ * @param {ReactElement} fragment
1217
+ */
1218
+
1219
+
1220
+ function validateFragmentProps(fragment) {
1221
+ {
1222
+ var keys = Object.keys(fragment.props);
1223
+
1224
+ for (var i = 0; i < keys.length; i++) {
1225
+ var key = keys[i];
1226
+
1227
+ if (key !== 'children' && key !== 'key') {
1228
+ setCurrentlyValidatingElement$1(fragment);
1229
+
1230
+ error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
1231
+
1232
+ setCurrentlyValidatingElement$1(null);
1233
+ break;
1234
+ }
1235
+ }
1236
+
1237
+ if (fragment.ref !== null) {
1238
+ setCurrentlyValidatingElement$1(fragment);
1239
+
1240
+ error('Invalid attribute `ref` supplied to `React.Fragment`.');
1241
+
1242
+ setCurrentlyValidatingElement$1(null);
1243
+ }
1244
+ }
1245
+ }
1246
+
1247
+ var didWarnAboutKeySpread = {};
1248
+ function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
1249
+ {
1250
+ var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
1251
+ // succeed and there will likely be errors in render.
1252
+
1253
+ if (!validType) {
1254
+ var info = '';
1255
+
1256
+ if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
1257
+ info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
1258
+ }
1259
+
1260
+ var sourceInfo = getSourceInfoErrorAddendum(source);
1261
+
1262
+ if (sourceInfo) {
1263
+ info += sourceInfo;
1264
+ } else {
1265
+ info += getDeclarationErrorAddendum();
1266
+ }
1267
+
1268
+ var typeString;
1269
+
1270
+ if (type === null) {
1271
+ typeString = 'null';
1272
+ } else if (isArray(type)) {
1273
+ typeString = 'array';
1274
+ } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
1275
+ typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
1276
+ info = ' Did you accidentally export a JSX literal instead of a component?';
1277
+ } else {
1278
+ typeString = typeof type;
1279
+ }
1280
+
1281
+ error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
1282
+ }
1283
+
1284
+ var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
1285
+ // TODO: Drop this when these are no longer allowed as the type argument.
1286
+
1287
+ if (element == null) {
1288
+ return element;
1289
+ } // Skip key warning if the type isn't valid since our key validation logic
1290
+ // doesn't expect a non-string/function type and can throw confusing errors.
1291
+ // We don't want exception behavior to differ between dev and prod.
1292
+ // (Rendering will throw with a helpful message and as soon as the type is
1293
+ // fixed, the key warnings will appear.)
1294
+
1295
+
1296
+ if (validType) {
1297
+ var children = props.children;
1298
+
1299
+ if (children !== undefined) {
1300
+ if (isStaticChildren) {
1301
+ if (isArray(children)) {
1302
+ for (var i = 0; i < children.length; i++) {
1303
+ validateChildKeys(children[i], type);
1304
+ }
1305
+
1306
+ if (Object.freeze) {
1307
+ Object.freeze(children);
1308
+ }
1309
+ } else {
1310
+ error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
1311
+ }
1312
+ } else {
1313
+ validateChildKeys(children, type);
1314
+ }
1315
+ }
1316
+ }
1317
+
1318
+ {
1319
+ if (hasOwnProperty.call(props, 'key')) {
1320
+ var componentName = getComponentNameFromType(type);
1321
+ var keys = Object.keys(props).filter(function (k) {
1322
+ return k !== 'key';
1323
+ });
1324
+ var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';
1325
+
1326
+ if (!didWarnAboutKeySpread[componentName + beforeExample]) {
1327
+ var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
1328
+
1329
+ error('A props object containing a "key" prop is being spread into JSX:\n' + ' let props = %s;\n' + ' <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + ' let props = %s;\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
1330
+
1331
+ didWarnAboutKeySpread[componentName + beforeExample] = true;
1332
+ }
1333
+ }
1334
+ }
1335
+
1336
+ if (type === REACT_FRAGMENT_TYPE) {
1337
+ validateFragmentProps(element);
1338
+ } else {
1339
+ validatePropTypes(element);
1340
+ }
1341
+
1342
+ return element;
1343
+ }
1344
+ } // These two functions exist to still get child warnings in dev
1345
+ // even with the prod transform. This means that jsxDEV is purely
1346
+ // opt-in behavior for better messages but that we won't stop
1347
+ // giving you warnings if you use production apis.
1348
+
1349
+ function jsxWithValidationStatic(type, props, key) {
1350
+ {
1351
+ return jsxWithValidation(type, props, key, true);
1352
+ }
1353
+ }
1354
+ function jsxWithValidationDynamic(type, props, key) {
1355
+ {
1356
+ return jsxWithValidation(type, props, key, false);
1357
+ }
1358
+ }
1359
+
1360
+ var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
1361
+ // for now we can ship identical prod functions
1362
+
1363
+ var jsxs = jsxWithValidationStatic ;
1364
+
1365
+ reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
1366
+ reactJsxRuntime_development.jsx = jsx;
1367
+ reactJsxRuntime_development.jsxs = jsxs;
1368
+ })();
1369
+ }
1370
+ return reactJsxRuntime_development;
1371
+ }
1372
+
1373
+ if (process.env.NODE_ENV === 'production') {
1374
+ jsxRuntime.exports = requireReactJsxRuntime_production_min();
1375
+ } else {
1376
+ jsxRuntime.exports = requireReactJsxRuntime_development();
1377
+ }
1378
+
1379
+ var jsxRuntimeExports = jsxRuntime.exports;
1380
+
1381
+ /**
1382
+ * Color palettes for stream visualization
1383
+ */
1384
+ // Single color palettes (monochromatic)
1385
+ const singleColorPalettes = [
1386
+ {
1387
+ label: 'red',
1388
+ keyColor: 5,
1389
+ keyColorValue: '#FF3B65',
1390
+ values: [
1391
+ '#FFD2D9',
1392
+ '#FFB0BF',
1393
+ '#FF90A2',
1394
+ '#FF6780',
1395
+ '#FF3B65',
1396
+ '#D12D50',
1397
+ '#A31E3B',
1398
+ '#751025',
1399
+ '#470110',
1400
+ '#35010E',
1401
+ ],
1402
+ },
1403
+ {
1404
+ label: 'pink',
1405
+ keyColor: 5,
1406
+ keyColorValue: '#D53C97',
1407
+ values: [
1408
+ '#F5D2E3',
1409
+ '#EDB0CF',
1410
+ '#E590BD',
1411
+ '#D967A4',
1412
+ '#D53C97',
1413
+ '#B52D7F',
1414
+ '#961F68',
1415
+ '#761050',
1416
+ '#560238',
1417
+ '#330124',
1418
+ ],
1419
+ },
1420
+ {
1421
+ label: 'purple',
1422
+ keyColor: 5,
1423
+ keyColorValue: '#AC1BB5',
1424
+ values: [
1425
+ '#EACAEA',
1426
+ '#DAA6DA',
1427
+ '#CB81CC',
1428
+ '#B553BA',
1429
+ '#AC1BB5',
1430
+ '#911698',
1431
+ '#75127C',
1432
+ '#5A0E5F',
1433
+ '#3E0942',
1434
+ '#250528',
1435
+ ],
1436
+ },
1437
+ {
1438
+ label: 'blue',
1439
+ keyColor: 5,
1440
+ keyColorValue: '#664CFC',
1441
+ values: [
1442
+ '#D9D3FC',
1443
+ '#BEB4F9',
1444
+ '#A395F8',
1445
+ '#806DF4',
1446
+ '#664CFC',
1447
+ '#523DCE',
1448
+ '#3F2F9F',
1449
+ '#2B2171',
1450
+ '#171242',
1451
+ '#0E0E35',
1452
+ ],
1453
+ },
1454
+ {
1455
+ label: 'green',
1456
+ keyColor: 5,
1457
+ keyColorValue: '#52FFDB',
1458
+ values: [
1459
+ '#D5FFF6',
1460
+ '#B8FFF0',
1461
+ '#99FEE9',
1462
+ '#73FEE0',
1463
+ '#52FFDB',
1464
+ '#43D2B4',
1465
+ '#34A68D',
1466
+ '#23AD8F',
1467
+ '#1F8D77',
1468
+ '#113027',
1469
+ ],
1470
+ },
1471
+ {
1472
+ label: 'orange',
1473
+ keyColor: 2,
1474
+ keyColorValue: '#F97316',
1475
+ values: ['#FDBA74', '#FB923C', '#F97316'],
1476
+ },
1477
+ {
1478
+ label: 'yellow',
1479
+ keyColor: 2,
1480
+ keyColorValue: '#EAB308',
1481
+ values: ['#FDE047', '#FACC15', '#EAB308'],
1482
+ },
1483
+ {
1484
+ label: 'cyan',
1485
+ keyColor: 2,
1486
+ keyColorValue: '#06B6D4',
1487
+ values: ['#67E8F9', '#22D3EE', '#06B6D4'],
1488
+ },
1489
+ {
1490
+ label: 'gray',
1491
+ keyColor: 2,
1492
+ keyColorValue: '#71717A',
1493
+ values: ['#A1A1AA', '#71717A', '#52525B'],
1494
+ },
1495
+ ];
1496
+ // Multi-color palettes for categorical data
1497
+ const multiColorPalettes = [
1498
+ {
1499
+ label: 'Dawn',
1500
+ keyColor: 0,
1501
+ keyColorValue: '#EC4899',
1502
+ values: [
1503
+ '#EC4899', // pink-400
1504
+ '#FACC15', // yellow-400
1505
+ '#DA4B36',
1506
+ '#9A1563',
1507
+ '#F87171', // red-400
1508
+ '#EF4444', // red-500
1509
+ '#A855F7', // purple-500
1510
+ '#DB2777', // pink-500
1511
+ '#F7775A',
1512
+ '#8B5CF6', // purple-500
1513
+ ],
1514
+ },
1515
+ {
1516
+ label: 'Morning',
1517
+ keyColor: 0,
1518
+ keyColorValue: '#3B82F6',
1519
+ values: [
1520
+ '#3B82F6', // blue-500
1521
+ '#FB923C', // orange-400
1522
+ '#F87171', // red-400
1523
+ '#22D3EE', // cyan-400
1524
+ '#C084FC', // purple-400
1525
+ '#FACC15', // yellow-400
1526
+ '#F472B6', // pink-400
1527
+ '#4ADE80', // green-400
1528
+ '#EC4899', // pink-500
1529
+ '#4E5ADF',
1530
+ ],
1531
+ },
1532
+ {
1533
+ label: 'Midnight',
1534
+ keyColor: 0,
1535
+ keyColorValue: '#4E5ADF',
1536
+ values: [
1537
+ '#4E5ADF',
1538
+ '#A855F7', // purple-500
1539
+ '#3B82F6', // blue-500
1540
+ '#084B8A',
1541
+ '#22C55E', // green-500
1542
+ '#C084FC', // purple-400
1543
+ '#244E47',
1544
+ '#0891B2', // cyan-600
1545
+ '#6626A3',
1546
+ '#2563EB', // blue-600
1547
+ ],
1548
+ },
1549
+ {
1550
+ label: 'Ocean',
1551
+ keyColor: 0,
1552
+ keyColorValue: '#0EA5E9',
1553
+ values: [
1554
+ '#0EA5E9', // sky-500
1555
+ '#06B6D4', // cyan-500
1556
+ '#14B8A6', // teal-500
1557
+ '#22C55E', // green-500
1558
+ '#3B82F6', // blue-500
1559
+ '#6366F1', // indigo-500
1560
+ '#8B5CF6', // violet-500
1561
+ '#0284C7', // sky-600
1562
+ '#0891B2', // cyan-600
1563
+ '#0D9488', // teal-600
1564
+ ],
1565
+ },
1566
+ {
1567
+ label: 'Sunset',
1568
+ keyColor: 0,
1569
+ keyColorValue: '#F97316',
1570
+ values: [
1571
+ '#F97316', // orange-500
1572
+ '#EF4444', // red-500
1573
+ '#EC4899', // pink-500
1574
+ '#F59E0B', // amber-500
1575
+ '#FACC15', // yellow-500
1576
+ '#FB923C', // orange-400
1577
+ '#F87171', // red-400
1578
+ '#F472B6', // pink-400
1579
+ '#FBBF24', // amber-400
1580
+ '#FDE047', // yellow-400
1581
+ ],
1582
+ },
1583
+ ];
1584
+ // All palettes combined
1585
+ const allPalettes = [...multiColorPalettes, ...singleColorPalettes];
1586
+ // Default palette
1587
+ const DEFAULT_PALETTE = multiColorPalettes[0];
1588
+ /**
1589
+ * Find a color palette by its values array
1590
+ */
1591
+ function findPaletteByValues(values, defaultPalette = DEFAULT_PALETTE) {
1592
+ return (allPalettes.find((palette) => palette.values.join(',') === values.join(',')) || defaultPalette);
1593
+ }
1594
+ /**
1595
+ * Find a color palette by label
1596
+ */
1597
+ function findPaletteByLabel(label, defaultPalette = DEFAULT_PALETTE) {
1598
+ return allPalettes.find((palette) => palette.label === label) || defaultPalette;
1599
+ }
1600
+ /**
1601
+ * Get the key color from a palette with optional opacity
1602
+ */
1603
+ function getPaletteKeyColor(label, opacity = 1) {
1604
+ const palette = findPaletteByLabel(label);
1605
+ if (!palette)
1606
+ return '';
1607
+ if (opacity === 1)
1608
+ return palette.keyColorValue;
1609
+ const hex = palette.keyColorValue;
1610
+ const alpha = Math.floor(opacity * 255)
1611
+ .toString(16)
1612
+ .padStart(2, '0');
1613
+ return `${hex}${alpha}`;
1614
+ }
1615
+ /**
1616
+ * Generate colors for a given number of series from a palette
1617
+ */
1618
+ function getSeriesColors(palette, count) {
1619
+ const colors = [];
1620
+ for (let i = 0; i < count; i++) {
1621
+ colors.push(palette.values[i % palette.values.length]);
1622
+ }
1623
+ return colors;
1624
+ }
1625
+ const darkTheme = {
1626
+ backgroundColor: 'transparent',
1627
+ textColor: '#E5E5E5',
1628
+ gridColor: '#374151',
1629
+ axisColor: '#6B7280',
1630
+ tooltipBackground: '#1F2937',
1631
+ tooltipTextColor: '#E5E5E5',
1632
+ fontFamily: 'Inter, system-ui, sans-serif',
1633
+ };
1634
+ const lightTheme = {
1635
+ backgroundColor: 'transparent',
1636
+ textColor: '#1F2937',
1637
+ gridColor: '#E5E7EB',
1638
+ axisColor: '#9CA3AF',
1639
+ tooltipBackground: '#FFFFFF',
1640
+ tooltipTextColor: '#1F2937',
1641
+ fontFamily: 'Inter, system-ui, sans-serif',
1642
+ };
1643
+ function getTheme(name) {
1644
+ return name === 'dark' ? darkTheme : lightTheme;
1645
+ }
1646
+
1647
+ /**
1648
+ * VistralSpec — declarative grammar types for streaming visualizations.
1649
+ *
1650
+ * These types define a renderer-agnostic specification that can be compiled
1651
+ * down to AntV G2 options (or other backends in the future).
1652
+ */
1653
+ // ---------------------------------------------------------------------------
1654
+ // Streaming
1655
+ // ---------------------------------------------------------------------------
1656
+ /** Default maximum number of data items kept in memory for streaming charts. */
1657
+ const DEFAULT_MAX_ITEMS = 1000;
1658
+
1659
+ /**
1660
+ * Utility functions for stream visualization
1661
+ */
1662
+ // Type detection constants
1663
+ const NUMBER_TYPES = [
1664
+ 'int8', 'int16', 'int32', 'int64', 'int128', 'int256',
1665
+ 'uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'uint256',
1666
+ 'float32', 'float64', 'float', 'double',
1667
+ 'decimal', 'decimal32', 'decimal64', 'decimal128', 'decimal256',
1668
+ 'number'
1669
+ ];
1670
+ const DATETIME_TYPES = ['datetime', 'datetime64', 'date', 'date32', 'timestamp'];
1671
+ const STRING_TYPES = ['string', 'fixedstring', 'text', 'varchar', 'char'];
1672
+ /**
1673
+ * Check if a column type is numeric
1674
+ */
1675
+ function isNumericColumn(type) {
1676
+ const upperType = type.toUpperCase();
1677
+ return NUMBER_TYPES.some((t) => upperType.startsWith(t.toUpperCase()));
1678
+ }
1679
+ /**
1680
+ * Check if a column type is datetime
1681
+ */
1682
+ function isDateTimeColumn(type) {
1683
+ const upperType = type.toUpperCase();
1684
+ return DATETIME_TYPES.some((t) => upperType.startsWith(t.toUpperCase()));
1685
+ }
1686
+ /**
1687
+ * Check if a column type is string
1688
+ */
1689
+ function isStringColumn(type) {
1690
+ const upperType = type.toUpperCase();
1691
+ return STRING_TYPES.some((t) => upperType.startsWith(t.toUpperCase()));
1692
+ }
1693
+ /**
1694
+ * Check if a column type is boolean
1695
+ */
1696
+ function isBooleanColumn(type) {
1697
+ const upperType = type.toUpperCase();
1698
+ return upperType === 'BOOL' || upperType === 'BOOLEAN';
1699
+ }
1700
+ /**
1701
+ * Determine automatic time format mask based on domain range
1702
+ */
1703
+ function getTimeMask(domainMin, domainMax) {
1704
+ const date1 = new Date(domainMin);
1705
+ const date2 = new Date(domainMax);
1706
+ const y1 = date1.getFullYear();
1707
+ const m1 = date1.getMonth();
1708
+ const d1 = date1.getDate();
1709
+ const h1 = date1.getHours();
1710
+ const min1 = date1.getMinutes();
1711
+ const s1 = date1.getSeconds();
1712
+ const y2 = date2.getFullYear();
1713
+ const m2 = date2.getMonth();
1714
+ const d2 = date2.getDate();
1715
+ const h2 = date2.getHours();
1716
+ const min2 = date2.getMinutes();
1717
+ const s2 = date2.getSeconds();
1718
+ if (y1 !== y2)
1719
+ return 'YY/MM/DD';
1720
+ if (m1 !== m2)
1721
+ return 'MM/DD';
1722
+ if (d1 !== d2) {
1723
+ return Math.abs(d1 - d2) > 1 ? 'MM/DD' : 'MM/DD HH:mm:ss';
1724
+ }
1725
+ if (h1 !== h2 || min1 !== min2 || s1 !== s2)
1726
+ return 'HH:mm:ss';
1727
+ return 'HH:mm:ss';
1728
+ }
1729
+ /**
1730
+ * Clamp a number between min and max values
1731
+ */
1732
+ function clamp(value, min, max) {
1733
+ return Math.min(Math.max(value, min), max);
1734
+ }
1735
+ /**
1736
+ * Truncate a string with ellipsis if too long
1737
+ */
1738
+ function truncateWithEllipsis(str, maxLength) {
1739
+ if (!str || str.length <= maxLength)
1740
+ return str;
1741
+ return `${str.slice(0, maxLength)}...`;
1742
+ }
1743
+ /**
1744
+ * Format a number with locale formatting
1745
+ */
1746
+ function formatNumber(num, digits = 2) {
1747
+ if (isNaN(num))
1748
+ return '-';
1749
+ return num.toLocaleString('en-US', { maximumFractionDigits: digits });
1750
+ }
1751
+ /**
1752
+ * Format a large number with abbreviation (k, m, b, t)
1753
+ */
1754
+ function abbreviateNumber(num, decPlaces = 2) {
1755
+ if (isNaN(num))
1756
+ return '-';
1757
+ const abbrev = ['', 'k', 'm', 'b', 't'];
1758
+ let tier = 0;
1759
+ let scaledNum = num;
1760
+ while (Math.abs(scaledNum) >= 1000 && tier < abbrev.length - 1) {
1761
+ scaledNum /= 1000;
1762
+ tier++;
1763
+ }
1764
+ return `${scaledNum.toFixed(tier > 0 ? decPlaces : 0)}${abbrev[tier]}`;
1765
+ }
1766
+ /**
1767
+ * Format duration from milliseconds to human readable
1768
+ */
1769
+ function formatDuration(ms) {
1770
+ if (ms < 1000)
1771
+ return `${Math.round(ms)}ms`;
1772
+ if (ms < 60000)
1773
+ return `${(ms / 1000).toFixed(1)}s`;
1774
+ if (ms < 3600000)
1775
+ return `${(ms / 60000).toFixed(1)}m`;
1776
+ return `${(ms / 3600000).toFixed(1)}h`;
1777
+ }
1778
+ /**
1779
+ * Format bytes to human readable size
1780
+ */
1781
+ function formatBytes(bytes, decimals = 2) {
1782
+ if (bytes === 0)
1783
+ return '0 B';
1784
+ if (isNaN(bytes))
1785
+ return '-';
1786
+ const k = 1024;
1787
+ const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
1788
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1789
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
1790
+ }
1791
+ /**
1792
+ * Debounce function execution
1793
+ */
1794
+ function debounce(func, wait) {
1795
+ let timeout = null;
1796
+ return function (...args) {
1797
+ if (timeout)
1798
+ clearTimeout(timeout);
1799
+ timeout = setTimeout(() => func(...args), wait);
1800
+ };
1801
+ }
1802
+ /**
1803
+ * Get value from a data row by column index or name
1804
+ */
1805
+ function getRowValue(row, column) {
1806
+ if (Array.isArray(row)) {
1807
+ return typeof column === 'number' ? row[column] : row[parseInt(column, 10)];
1808
+ }
1809
+ return row[column];
1810
+ }
1811
+ /**
1812
+ * Convert a row to array format if it's an object
1813
+ */
1814
+ function rowToArray(row, columns) {
1815
+ if (Array.isArray(row))
1816
+ return row;
1817
+ return columns.map((col) => row[col.name]);
1818
+ }
1819
+ /**
1820
+ * Find column index by name
1821
+ */
1822
+ function findColumnIndex(columns, name) {
1823
+ return columns.findIndex((col) => col.name === name);
1824
+ }
1825
+ /**
1826
+ * Get filtered columns by type
1827
+ */
1828
+ function getColumnsByType(columns, filter) {
1829
+ switch (filter) {
1830
+ case 'numeric':
1831
+ return columns.filter((col) => isNumericColumn(col.type));
1832
+ case 'datetime':
1833
+ return columns.filter((col) => isDateTimeColumn(col.type));
1834
+ case 'string':
1835
+ return columns.filter((col) => isStringColumn(col.type));
1836
+ case 'boolean':
1837
+ return columns.filter((col) => isBooleanColumn(col.type));
1838
+ default:
1839
+ return columns;
1840
+ }
1841
+ }
1842
+ /**
1843
+ * Calculate statistics for a numeric column
1844
+ */
1845
+ function calculateColumnStats(data, columnIndex) {
1846
+ let min = Infinity;
1847
+ let max = -Infinity;
1848
+ let sum = 0;
1849
+ let count = 0;
1850
+ for (const row of data) {
1851
+ const value = Array.isArray(row) ? row[columnIndex] : Object.values(row)[columnIndex];
1852
+ if (typeof value === 'number' && !isNaN(value)) {
1853
+ min = Math.min(min, value);
1854
+ max = Math.max(max, value);
1855
+ sum += value;
1856
+ count++;
1857
+ }
1858
+ }
1859
+ return {
1860
+ min: min === Infinity ? 0 : min,
1861
+ max: max === -Infinity ? 0 : max,
1862
+ sum,
1863
+ count,
1864
+ avg: count > 0 ? sum / count : 0,
1865
+ };
1866
+ }
1867
+ /**
1868
+ * Get unique values for a column (for categorical data)
1869
+ */
1870
+ function getUniqueValues(data, columnIndex) {
1871
+ const values = new Set();
1872
+ for (const row of data) {
1873
+ const value = Array.isArray(row) ? row[columnIndex] : Object.values(row)[columnIndex];
1874
+ if (value !== null && value !== undefined) {
1875
+ values.add(String(value));
1876
+ }
1877
+ }
1878
+ return Array.from(values);
1879
+ }
1880
+ /**
1881
+ * Parse datetime value to timestamp
1882
+ */
1883
+ function parseDateTime(value) {
1884
+ if (typeof value === 'number')
1885
+ return value;
1886
+ if (value instanceof Date)
1887
+ return value.getTime();
1888
+ if (typeof value === 'string') {
1889
+ const parsed = Date.parse(value);
1890
+ return isNaN(parsed) ? 0 : parsed;
1891
+ }
1892
+ return 0;
1893
+ }
1894
+ /**
1895
+ * Process data source into internal format for charts
1896
+ */
1897
+ function processDataSource(source, xKey, yKey, zKey) {
1898
+ const { columns, data } = source;
1899
+ const xIndex = findColumnIndex(columns, xKey);
1900
+ const yIndex = findColumnIndex(columns, yKey);
1901
+ const zIndex = zKey ? findColumnIndex(columns, zKey) : -1;
1902
+ const isXTime = xIndex >= 0 && isDateTimeColumn(columns[xIndex].type);
1903
+ // Calculate statistics
1904
+ let xMin = Infinity;
1905
+ let xMax = -Infinity;
1906
+ let yMin = Infinity;
1907
+ let yMax = -Infinity;
1908
+ const zValues = [];
1909
+ for (const row of data) {
1910
+ const arr = rowToArray(row, columns);
1911
+ // X stats
1912
+ if (xIndex >= 0) {
1913
+ const xVal = isXTime ? parseDateTime(arr[xIndex]) : Number(arr[xIndex]);
1914
+ if (!isNaN(xVal)) {
1915
+ xMin = Math.min(xMin, xVal);
1916
+ xMax = Math.max(xMax, xVal);
1917
+ }
1918
+ }
1919
+ // Y stats
1920
+ if (yIndex >= 0) {
1921
+ const yVal = Number(arr[yIndex]);
1922
+ if (!isNaN(yVal)) {
1923
+ yMin = Math.min(yMin, yVal);
1924
+ yMax = Math.max(yMax, yVal);
1925
+ }
1926
+ }
1927
+ // Z categories
1928
+ if (zIndex >= 0) {
1929
+ const zVal = String(arr[zIndex] ?? '');
1930
+ if (zVal && !zValues.includes(zVal)) {
1931
+ zValues.push(zVal);
1932
+ }
1933
+ }
1934
+ }
1935
+ // Transform function for x-axis
1936
+ const xTransform = isXTime ? (v) => parseDateTime(v) : (v) => v;
1937
+ return {
1938
+ data: data.map((row) => rowToArray(row, columns)),
1939
+ header: columns,
1940
+ x: {
1941
+ index: xIndex,
1942
+ isTime: isXTime,
1943
+ min: xMin === Infinity ? 0 : xMin,
1944
+ max: xMax === -Infinity ? 0 : xMax,
1945
+ offset: 0,
1946
+ },
1947
+ y: {
1948
+ index: yIndex,
1949
+ min: yMin === Infinity ? 0 : yMin,
1950
+ max: yMax === -Infinity ? 0 : yMax,
1951
+ },
1952
+ z: {
1953
+ index: zIndex,
1954
+ values: zValues,
1955
+ },
1956
+ xTransform,
1957
+ };
1958
+ }
1959
+ /**
1960
+ * Merge deep objects (like lodash merge)
1961
+ */
1962
+ function mergeDeep(target, ...sources) {
1963
+ if (!sources.length)
1964
+ return target;
1965
+ const source = sources.shift();
1966
+ if (!source)
1967
+ return target;
1968
+ for (const key in source) {
1969
+ const sourceValue = source[key];
1970
+ const targetValue = target[key];
1971
+ if (isObject(sourceValue) && isObject(targetValue)) {
1972
+ target[key] = mergeDeep({ ...targetValue }, sourceValue);
1973
+ }
1974
+ else if (sourceValue !== undefined) {
1975
+ target[key] = sourceValue;
1976
+ }
1977
+ }
1978
+ return mergeDeep(target, ...sources);
1979
+ }
1980
+ function isObject(item) {
1981
+ return item !== null && typeof item === 'object' && !Array.isArray(item);
1982
+ }
1983
+ /**
1984
+ * Generate unique ID
1985
+ */
1986
+ function generateId(prefix = 'stream-viz') {
1987
+ return `${prefix}-${Math.random().toString(36).substr(2, 9)}`;
1988
+ }
1989
+ // ============================================================
1990
+ // Temporal Binding Utilities
1991
+ // ============================================================
1992
+ /**
1993
+ * Filter data by latest timestamp (frame-bound mode)
1994
+ * Keeps only rows with the maximum timestamp value
1995
+ */
1996
+ function filterByLatestTimestamp(data, timeIndex) {
1997
+ if (data.length === 0 || timeIndex < 0)
1998
+ return data;
1999
+ // Find the maximum timestamp
2000
+ let maxTimestamp = -Infinity;
2001
+ for (const row of data) {
2002
+ const ts = parseDateTime(row[timeIndex]);
2003
+ if (ts > maxTimestamp) {
2004
+ maxTimestamp = ts;
2005
+ }
2006
+ }
2007
+ // Filter to only rows with the max timestamp
2008
+ return data.filter((row) => parseDateTime(row[timeIndex]) === maxTimestamp);
2009
+ }
2010
+ /**
2011
+ * Filter data by unique key (key-bound mode)
2012
+ * Keeps only the latest row for each unique key value
2013
+ */
2014
+ /**
2015
+ * Filter data by unique key (key-bound mode)
2016
+ * Keeps only the latest row for each unique key value
2017
+ */
2018
+ function filterByKey(data, keyIndex) {
2019
+ const indices = Array.isArray(keyIndex) ? keyIndex : [keyIndex];
2020
+ if (data.length === 0 || indices.some(idx => idx < 0))
2021
+ return data;
2022
+ // Use a map to keep the latest value for each key
2023
+ const groups = new Map();
2024
+ for (const row of data) {
2025
+ // specific composite key generation
2026
+ const key = indices.map(idx => String(row[idx] ?? '')).join('::');
2027
+ groups.set(key, row);
2028
+ }
2029
+ return Array.from(groups.values());
2030
+ }
2031
+ /**
2032
+ * Apply temporal filtering based on configuration
2033
+ */
2034
+ function applyTemporalFilter(data, columns, temporal) {
2035
+ // Handle single or multiple fields
2036
+ const fields = Array.isArray(temporal.field) ? temporal.field : [temporal.field];
2037
+ const fieldIndices = fields.map(f => findColumnIndex(columns, f));
2038
+ // If any field is not found, return original data
2039
+ if (fieldIndices.some(idx => idx < 0))
2040
+ return data;
2041
+ const primaryIndex = fieldIndices[0]; // Used for frame/axis checking usually, but frame mode handles single index
2042
+ switch (temporal.mode) {
2043
+ case 'frame':
2044
+ // Frame mode currently assumes single time field
2045
+ return filterByLatestTimestamp(data, primaryIndex);
2046
+ case 'key':
2047
+ // Key mode supports multiple fields
2048
+ return filterByKey(data, Array.isArray(temporal.field) ? fieldIndices : primaryIndex);
2049
+ case 'axis':
2050
+ // Axis mode filtering is handled by the chart component itself
2051
+ // (e.g., through domain clamping in TimeSeriesChart)
2052
+ return data;
2053
+ default:
2054
+ return data;
2055
+ }
2056
+ }
2057
+
2058
+ /**
2059
+ * React hooks for stream visualization
2060
+ */
2061
+ /**
2062
+ * Hook to manage AntV G2 chart instance
2063
+ */
2064
+ function useChart(options) {
2065
+ const chartRef = require$$0.useRef(null);
2066
+ const [chart, setChart] = require$$0.useState(null);
2067
+ const [isMouseOver, setIsMouseOver] = require$$0.useState(false);
2068
+ const [activeColor, setActiveColor] = require$$0.useState(-1);
2069
+ require$$0.useEffect(() => {
2070
+ if (!chartRef.current)
2071
+ return;
2072
+ const chartInstance = new g2.Chart({
2073
+ container: chartRef.current,
2074
+ autoFit: true,
2075
+ height: options?.height,
2076
+ padding: options?.padding,
2077
+ marginBottom: 0,
2078
+ });
2079
+ // Set up mouse tracking
2080
+ const container = chartInstance.getContainer();
2081
+ const handleMouseOver = () => setIsMouseOver(true);
2082
+ const handleMouseLeave = () => setIsMouseOver(false);
2083
+ container.addEventListener('mouseover', handleMouseOver);
2084
+ container.addEventListener('mouseleave', handleMouseLeave);
2085
+ // Initialize with empty data
2086
+ chartInstance.data([]);
2087
+ setChart(chartInstance);
2088
+ return () => {
2089
+ container.removeEventListener('mouseover', handleMouseOver);
2090
+ container.removeEventListener('mouseleave', handleMouseLeave);
2091
+ chartInstance.destroy();
2092
+ setChart(null);
2093
+ };
2094
+ }, [options?.height, options?.padding]);
2095
+ return {
2096
+ chart,
2097
+ chartRef,
2098
+ isMouseOver,
2099
+ activeColor,
2100
+ setActiveColor,
2101
+ };
2102
+ }
2103
+ /**
2104
+ * Hook to process streaming data source
2105
+ */
2106
+ function useDataSource(source, xKey, yKey, zKey) {
2107
+ const [processedData, setProcessedData] = require$$0.useState(null);
2108
+ require$$0.useEffect(() => {
2109
+ if (!source || !yKey) {
2110
+ setProcessedData(null);
2111
+ return;
2112
+ }
2113
+ const processed = processDataSource(source, xKey, yKey, zKey);
2114
+ setProcessedData(processed);
2115
+ }, [source, xKey, yKey, zKey]);
2116
+ return processedData;
2117
+ }
2118
+ /**
2119
+ * Hook to track streaming data updates
2120
+ */
2121
+ function useStreamingData(initialData, maxItems = DEFAULT_MAX_ITEMS) {
2122
+ const [data, setData] = require$$0.useState(initialData);
2123
+ const append = require$$0.useCallback((items) => {
2124
+ setData((prev) => {
2125
+ const newItems = Array.isArray(items) ? items : [items];
2126
+ const combined = [...prev, ...newItems];
2127
+ // Keep only the last maxItems
2128
+ return combined.slice(-maxItems);
2129
+ });
2130
+ }, [maxItems]);
2131
+ const replace = require$$0.useCallback((items) => {
2132
+ setData(items.slice(-maxItems));
2133
+ }, [maxItems]);
2134
+ const clear = require$$0.useCallback(() => {
2135
+ setData([]);
2136
+ }, []);
2137
+ return { data, append, replace, clear };
2138
+ }
2139
+ /**
2140
+ * Hook to handle resize detection
2141
+ */
2142
+ function useResizeObserver(callback) {
2143
+ const ref = require$$0.useRef(null);
2144
+ require$$0.useEffect(() => {
2145
+ if (!ref.current)
2146
+ return;
2147
+ let timeout = null;
2148
+ const debouncedCallback = (entry) => {
2149
+ if (timeout)
2150
+ clearTimeout(timeout);
2151
+ timeout = setTimeout(() => callback(entry), 200);
2152
+ };
2153
+ const observer = new ResizeObserver((entries) => {
2154
+ entries.forEach((entry) => debouncedCallback(entry));
2155
+ });
2156
+ observer.observe(ref.current);
2157
+ return () => {
2158
+ if (timeout)
2159
+ clearTimeout(timeout);
2160
+ observer.disconnect();
2161
+ };
2162
+ }, [callback]);
2163
+ return ref;
2164
+ }
2165
+ /**
2166
+ * Hook to manage chart theme
2167
+ */
2168
+ function useChartTheme(theme = 'dark') {
2169
+ const [currentTheme, setCurrentTheme] = require$$0.useState(theme);
2170
+ const toggleTheme = require$$0.useCallback(() => {
2171
+ setCurrentTheme((prev) => (prev === 'dark' ? 'light' : 'dark'));
2172
+ }, []);
2173
+ return {
2174
+ theme: currentTheme,
2175
+ setTheme: setCurrentTheme,
2176
+ toggleTheme,
2177
+ isDark: currentTheme === 'dark',
2178
+ };
2179
+ }
2180
+ /**
2181
+ * Hook to track last update time
2182
+ */
2183
+ function useLastUpdated(data) {
2184
+ const [lastUpdated, setLastUpdated] = require$$0.useState(null);
2185
+ require$$0.useEffect(() => {
2186
+ if (data.length > 0) {
2187
+ setLastUpdated(new Date());
2188
+ }
2189
+ }, [data]);
2190
+ return lastUpdated;
2191
+ }
2192
+ /**
2193
+ * Hook for sparkline data management
2194
+ */
2195
+ function useSparklineData(value, limit = 20) {
2196
+ const [data, setData] = require$$0.useState([]);
2197
+ require$$0.useEffect(() => {
2198
+ if (value === null || isNaN(value))
2199
+ return;
2200
+ setData((prev) => {
2201
+ const next = [...prev, { value }];
2202
+ return next.slice(-limit);
2203
+ });
2204
+ }, [value, limit]);
2205
+ const trend = data.length >= 2
2206
+ ? data[data.length - 1].value > data[data.length - 2].value
2207
+ ? 'up'
2208
+ : data[data.length - 1].value < data[data.length - 2].value
2209
+ ? 'down'
2210
+ : 'stable'
2211
+ : 'stable';
2212
+ return { data, trend };
2213
+ }
2214
+ /**
2215
+ * Hook to manage chart animation state
2216
+ */
2217
+ function useChartAnimation(enabled = true) {
2218
+ const [isAnimating, setIsAnimating] = require$$0.useState(false);
2219
+ const startAnimation = require$$0.useCallback(() => {
2220
+ if (enabled)
2221
+ setIsAnimating(true);
2222
+ }, [enabled]);
2223
+ const stopAnimation = require$$0.useCallback(() => {
2224
+ setIsAnimating(false);
2225
+ }, []);
2226
+ return {
2227
+ isAnimating,
2228
+ startAnimation,
2229
+ stopAnimation,
2230
+ animationEnabled: enabled,
2231
+ };
2232
+ }
2233
+ /**
2234
+ * Hook to debounce a value
2235
+ */
2236
+ function useDebouncedValue(value, delay = 300) {
2237
+ const [debouncedValue, setDebouncedValue] = require$$0.useState(value);
2238
+ require$$0.useEffect(() => {
2239
+ const timer = setTimeout(() => {
2240
+ setDebouncedValue(value);
2241
+ }, delay);
2242
+ return () => {
2243
+ clearTimeout(timer);
2244
+ };
2245
+ }, [value, delay]);
2246
+ return debouncedValue;
2247
+ }
2248
+ /**
2249
+ * Hook to track previous value
2250
+ */
2251
+ function usePrevious(value) {
2252
+ const ref = require$$0.useRef();
2253
+ require$$0.useEffect(() => {
2254
+ ref.current = value;
2255
+ }, [value]);
2256
+ return ref.current;
2257
+ }
2258
+ /**
2259
+ * Hook to determine default chart configuration based on data schema
2260
+ */
2261
+ function useAutoConfig(columns) {
2262
+ return require$$0.useCallback(() => {
2263
+ const dateCol = columns.find((c) => ['datetime', 'datetime64', 'date', 'timestamp'].some((t) => c.type.toLowerCase().includes(t)));
2264
+ const numericCols = columns.filter((c) => ['int', 'float', 'double', 'decimal', 'number'].some((t) => c.type.toLowerCase().includes(t)));
2265
+ const stringCols = columns.filter((c) => ['string', 'varchar', 'text', 'char'].some((t) => c.type.toLowerCase().includes(t)));
2266
+ return {
2267
+ suggestedXAxis: dateCol?.name || stringCols[0]?.name || columns[0]?.name,
2268
+ suggestedYAxis: numericCols[0]?.name || columns[1]?.name,
2269
+ suggestedColor: stringCols[0]?.name,
2270
+ hasTimeSeries: !!dateCol && numericCols.length > 0,
2271
+ hasCategorical: stringCols.length > 0 && numericCols.length > 0,
2272
+ };
2273
+ }, [columns]);
2274
+ }
2275
+
2276
+ /**
2277
+ * Find color palette by name
2278
+ */
2279
+ function findColorByName(name) {
2280
+ return singleColorPalettes.find((c) => c.label === name);
2281
+ }
2282
+ /**
2283
+ * Get default configuration for single value chart
2284
+ */
2285
+ function getSingleValueDefaults(columns) {
2286
+ const numericCol = columns.find(({ type }) => ['int', 'float', 'double', 'decimal', 'number'].some((t) => type.toLowerCase().includes(t)));
2287
+ if (!numericCol)
2288
+ return null;
2289
+ return {
2290
+ chartType: 'singleValue',
2291
+ yAxis: numericCol.name,
2292
+ fontSize: 64,
2293
+ color: 'blue',
2294
+ fractionDigits: 2,
2295
+ sparkline: false,
2296
+ sparklineColor: 'purple',
2297
+ delta: false,
2298
+ increaseColor: 'green',
2299
+ decreaseColor: 'red',
2300
+ unit: { position: 'left', value: '' },
2301
+ };
2302
+ }
2303
+ /**
2304
+ * Animated number display component
2305
+ */
2306
+ const AnimatedNumber = ({ value, decimals, duration = 500 }) => {
2307
+ const [displayValue, setDisplayValue] = require$$0.useState(value);
2308
+ const previousValue = require$$0.useRef(value);
2309
+ require$$0.useEffect(() => {
2310
+ if (isNaN(value))
2311
+ return;
2312
+ const startValue = previousValue.current;
2313
+ const startTime = Date.now();
2314
+ const animate = () => {
2315
+ const elapsed = Date.now() - startTime;
2316
+ const progress = Math.min(elapsed / duration, 1);
2317
+ // Easing function (ease-out)
2318
+ const easeOut = 1 - Math.pow(1 - progress, 3);
2319
+ const current = startValue + (value - startValue) * easeOut;
2320
+ setDisplayValue(current);
2321
+ if (progress < 1) {
2322
+ requestAnimationFrame(animate);
2323
+ }
2324
+ else {
2325
+ previousValue.current = value;
2326
+ }
2327
+ };
2328
+ requestAnimationFrame(animate);
2329
+ }, [value, duration]);
2330
+ return (jsxRuntimeExports.jsx("span", { children: isNaN(displayValue) ? '-' : displayValue.toLocaleString('en-US', {
2331
+ minimumFractionDigits: decimals,
2332
+ maximumFractionDigits: decimals,
2333
+ }) }));
2334
+ };
2335
+ /**
2336
+ * Mini Sparkline Component
2337
+ */
2338
+ const MiniSparkline = ({ data, color, width = 200, height = 60 }) => {
2339
+ const { chart, chartRef } = useChart({ height });
2340
+ require$$0.useEffect(() => {
2341
+ if (!chart || data.length === 0)
2342
+ return;
2343
+ chart.clear();
2344
+ const indexedData = data.map((d, i) => ({ index: i, value: d.value }));
2345
+ chart
2346
+ .line()
2347
+ .data(indexedData)
2348
+ .animate(false)
2349
+ .encode('x', 'index')
2350
+ .encode('y', 'value')
2351
+ .style('stroke', color)
2352
+ .style('lineWidth', 2)
2353
+ .style('shape', 'smooth')
2354
+ .scale({
2355
+ x: { type: 'linear', range: [0, 1] },
2356
+ y: { type: 'linear', nice: true },
2357
+ })
2358
+ .axis(false)
2359
+ .tooltip(false);
2360
+ chart.render();
2361
+ }, [chart, data, color]);
2362
+ return (jsxRuntimeExports.jsx("div", { ref: chartRef, style: { width: `${width}px`, height: `${height}px` } }));
2363
+ };
2364
+ /**
2365
+ * Single Value Chart Component
2366
+ */
2367
+ const SingleValueChart = ({ config: configRaw, data: dataSource, theme = 'dark', className, style, }) => {
2368
+ // Merge with defaults
2369
+ const defaults = getSingleValueDefaults(dataSource.columns);
2370
+ const config = require$$0.useMemo(() => ({
2371
+ ...defaults,
2372
+ ...configRaw,
2373
+ }), [configRaw, defaults]);
2374
+ // Get colors
2375
+ const mainColor = findColorByName(config.color || 'blue')?.keyColorValue || '#3B82F6';
2376
+ const sparklineColor = findColorByName(config.sparklineColor || 'purple')?.keyColorValue || '#8B5CF6';
2377
+ const increaseColor = findColorByName(config.increaseColor || 'green')?.keyColorValue || '#22C55E';
2378
+ const decreaseColor = findColorByName(config.decreaseColor || 'red')?.keyColorValue || '#EF4444';
2379
+ // Process data source
2380
+ const source = useDataSource(dataSource, '', config.yAxis, '');
2381
+ // Get current value
2382
+ const currentValue = require$$0.useMemo(() => {
2383
+ if (!source || source.y.index < 0 || source.data.length === 0)
2384
+ return NaN;
2385
+ const lastRow = source.data[source.data.length - 1];
2386
+ return Number(lastRow[source.y.index]);
2387
+ }, [source]);
2388
+ // Track sparkline data and previous value for delta
2389
+ const { data: sparklineData } = useSparklineData(currentValue, 20);
2390
+ const [previousValue, setPreviousValue] = require$$0.useState(NaN);
2391
+ require$$0.useEffect(() => {
2392
+ if (!isNaN(currentValue)) {
2393
+ const timer = setTimeout(() => {
2394
+ setPreviousValue(currentValue);
2395
+ }, 100);
2396
+ return () => clearTimeout(timer);
2397
+ }
2398
+ }, [currentValue]);
2399
+ // Calculate delta and keep last non-zero value
2400
+ const [displayedDelta, setDisplayedDelta] = require$$0.useState(0);
2401
+ require$$0.useEffect(() => {
2402
+ if (isNaN(currentValue) || isNaN(previousValue))
2403
+ return;
2404
+ const newDelta = currentValue - previousValue;
2405
+ // Only update displayed delta if it's non-zero
2406
+ if (newDelta !== 0) {
2407
+ setDisplayedDelta(newDelta);
2408
+ }
2409
+ }, [currentValue, previousValue]);
2410
+ // Decimal places
2411
+ const decimals = clamp(config.fractionDigits || 0, 0, 10);
2412
+ const fontSize = config.fontSize || 64;
2413
+ // Loading state
2414
+ if (isNaN(currentValue)) {
2415
+ return (jsxRuntimeExports.jsxs("div", { className: className, style: {
2416
+ width: '100%',
2417
+ height: '100%',
2418
+ display: 'flex',
2419
+ alignItems: 'center',
2420
+ justifyContent: 'center',
2421
+ color: theme === 'dark' ? '#9CA3AF' : '#6B7280',
2422
+ ...style,
2423
+ }, "data-testid": "single-value-chart", children: [jsxRuntimeExports.jsxs("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", style: { animation: 'spin 1s linear infinite' }, children: [jsxRuntimeExports.jsx("circle", { cx: "12", cy: "12", r: "10", strokeOpacity: "0.25" }), jsxRuntimeExports.jsx("path", { d: "M12 2a10 10 0 0 1 10 10", strokeLinecap: "round" })] }), jsxRuntimeExports.jsx("style", { children: `@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }` })] }));
2424
+ }
2425
+ // Unit rendering
2426
+ const renderUnit = (position) => {
2427
+ const unit = config.unit;
2428
+ if (!unit?.value || unit.position !== position)
2429
+ return null;
2430
+ return (jsxRuntimeExports.jsx("span", { style: {
2431
+ fontSize: position === 'left' ? fontSize : fontSize / 2,
2432
+ fontWeight: 'bold',
2433
+ fontFamily: 'Menlo, Monaco, monospace',
2434
+ color: mainColor,
2435
+ paddingRight: position === 'left' ? '4px' : 0,
2436
+ paddingLeft: position === 'right' ? '4px' : 0,
2437
+ }, children: unit.value }));
2438
+ };
2439
+ return (jsxRuntimeExports.jsxs("div", { className: className, style: {
2440
+ width: '100%',
2441
+ height: '100%',
2442
+ display: 'flex',
2443
+ flexDirection: 'column',
2444
+ alignItems: 'center',
2445
+ justifyContent: 'center',
2446
+ padding: '16px',
2447
+ ...style,
2448
+ }, "data-testid": "single-value-chart", children: [jsxRuntimeExports.jsxs("div", { style: { display: 'flex', alignItems: 'baseline' }, children: [renderUnit('left'), jsxRuntimeExports.jsx("span", { style: {
2449
+ fontSize: `${fontSize}px`,
2450
+ fontWeight: 'bold',
2451
+ fontFamily: 'Menlo, Monaco, monospace',
2452
+ color: mainColor,
2453
+ }, children: jsxRuntimeExports.jsx(AnimatedNumber, { value: currentValue, decimals: decimals }) }), renderUnit('right')] }), config.delta && (jsxRuntimeExports.jsxs("div", { style: {
2454
+ fontSize: `${Math.ceil(fontSize / 3)}px`,
2455
+ fontWeight: 'bold',
2456
+ fontFamily: 'Menlo, Monaco, monospace',
2457
+ display: 'flex',
2458
+ alignItems: 'center',
2459
+ justifyContent: 'center',
2460
+ gap: '4px',
2461
+ color: displayedDelta > 0 ? increaseColor : displayedDelta < 0 ? decreaseColor : theme === 'dark' ? '#6B7280' : '#9CA3AF',
2462
+ marginTop: '8px',
2463
+ minHeight: `${Math.ceil(fontSize / 3) + 4}px`,
2464
+ }, children: [jsxRuntimeExports.jsx("span", { style: {
2465
+ width: 0,
2466
+ height: 0,
2467
+ borderStyle: 'solid',
2468
+ borderWidth: displayedDelta >= 0 ? '0 4px 8px 4px' : '8px 4px 0 4px',
2469
+ borderColor: displayedDelta >= 0
2470
+ ? `transparent transparent ${displayedDelta > 0 ? increaseColor : (theme === 'dark' ? '#6B7280' : '#9CA3AF')} transparent`
2471
+ : `${decreaseColor} transparent transparent transparent`,
2472
+ } }), jsxRuntimeExports.jsxs("span", { children: [displayedDelta >= 0 ? '+' : '', displayedDelta.toLocaleString('en-US', {
2473
+ minimumFractionDigits: decimals,
2474
+ maximumFractionDigits: decimals,
2475
+ })] })] })), config.sparkline && sparklineData.length > 1 && (jsxRuntimeExports.jsx("div", { style: { marginTop: '16px', width: '80%', maxWidth: '300px' }, children: jsxRuntimeExports.jsx(MiniSparkline, { data: sparklineData, color: sparklineColor, height: 60 }) }))] }));
2476
+ };
2477
+
2478
+ /**
2479
+ * Get default table configuration
2480
+ */
2481
+ function getTableDefaults(columns) {
2482
+ const tableStyles = {};
2483
+ columns.forEach((col) => {
2484
+ tableStyles[col.name] = {
2485
+ name: col.name,
2486
+ show: true,
2487
+ width: 150,
2488
+ miniChart: 'none',
2489
+ color: { type: 'none' },
2490
+ };
2491
+ });
2492
+ return {
2493
+ chartType: 'table',
2494
+ tableStyles,
2495
+ tableWrap: false,
2496
+ };
2497
+ }
2498
+ /**
2499
+ * Mini Sparkline for table cells
2500
+ */
2501
+ const CellSparkline = ({ data, width = 80, height = 30, }) => {
2502
+ const { chart, chartRef } = useChart({ height });
2503
+ require$$0.useEffect(() => {
2504
+ if (!chart || data.length === 0)
2505
+ return;
2506
+ chart.clear();
2507
+ const indexedData = data.map((d, i) => ({ index: i, value: d }));
2508
+ chart
2509
+ .line()
2510
+ .data(indexedData)
2511
+ .animate(false)
2512
+ .encode('x', 'index')
2513
+ .encode('y', 'value')
2514
+ .style('stroke', '#8B5CF6')
2515
+ .style('lineWidth', 1)
2516
+ .style('shape', 'smooth')
2517
+ .scale({
2518
+ x: { type: 'linear', range: [0, 1] },
2519
+ y: { type: 'linear', nice: true },
2520
+ })
2521
+ .axis(false)
2522
+ .tooltip(false);
2523
+ chart.render();
2524
+ }, [chart, data]);
2525
+ return jsxRuntimeExports.jsx("div", { ref: chartRef, style: { width, height } });
2526
+ };
2527
+ /**
2528
+ * Get cell background color based on conditions
2529
+ */
2530
+ function getCellBackgroundColor(value, colorConfig) {
2531
+ if (!colorConfig || colorConfig.type === 'none')
2532
+ return undefined;
2533
+ if (colorConfig.type === 'condition' && colorConfig.conditions) {
2534
+ const numValue = Number(value);
2535
+ if (isNaN(numValue))
2536
+ return undefined;
2537
+ for (const condition of colorConfig.conditions) {
2538
+ let matches = false;
2539
+ switch (condition.operator) {
2540
+ case 'gt':
2541
+ matches = numValue > condition.value;
2542
+ break;
2543
+ case 'lt':
2544
+ matches = numValue < condition.value;
2545
+ break;
2546
+ case 'eq':
2547
+ matches = numValue === condition.value;
2548
+ break;
2549
+ case 'gte':
2550
+ matches = numValue >= condition.value;
2551
+ break;
2552
+ case 'lte':
2553
+ matches = numValue <= condition.value;
2554
+ break;
2555
+ }
2556
+ if (matches)
2557
+ return condition.color;
2558
+ }
2559
+ }
2560
+ return undefined;
2561
+ }
2562
+ /**
2563
+ * Table Cell Component
2564
+ */
2565
+ const TableCell = ({ value, isNumeric, miniChart, sparklineData = [], color, wrap, theme }) => {
2566
+ const bgColor = getCellBackgroundColor(value, color);
2567
+ const displayValue = isNumeric ? formatNumber(Number(value)) : String(value ?? '');
2568
+ return (jsxRuntimeExports.jsx("td", { style: {
2569
+ padding: '8px 12px',
2570
+ borderBottom: `1px solid ${theme === 'dark' ? '#374151' : '#E5E7EB'}`,
2571
+ textAlign: isNumeric ? 'right' : 'left',
2572
+ backgroundColor: bgColor,
2573
+ whiteSpace: wrap ? 'normal' : 'nowrap',
2574
+ overflow: 'hidden',
2575
+ textOverflow: 'ellipsis',
2576
+ maxWidth: '200px',
2577
+ }, title: String(value ?? ''), children: jsxRuntimeExports.jsxs("div", { style: { display: 'flex', alignItems: 'center', gap: '8px' }, children: [miniChart === 'sparkline' && sparklineData.length > 0 && (jsxRuntimeExports.jsx(CellSparkline, { data: sparklineData })), jsxRuntimeExports.jsx("span", { children: displayValue })] }) }));
2578
+ };
2579
+ /**
2580
+ * Table Header Cell Component
2581
+ */
2582
+ const TableHeaderCell = ({ column, displayName, width, onResize, theme }) => {
2583
+ const resizeRef = require$$0.useRef(null);
2584
+ const [isResizing, setIsResizing] = require$$0.useState(false);
2585
+ const handleMouseDown = require$$0.useCallback((e) => {
2586
+ e.preventDefault();
2587
+ setIsResizing(true);
2588
+ const startX = e.clientX;
2589
+ const startWidth = width;
2590
+ const handleMouseMove = (moveEvent) => {
2591
+ const diff = moveEvent.clientX - startX;
2592
+ const newWidth = Math.max(50, startWidth + diff);
2593
+ onResize(newWidth);
2594
+ };
2595
+ const handleMouseUp = () => {
2596
+ setIsResizing(false);
2597
+ document.removeEventListener('mousemove', handleMouseMove);
2598
+ document.removeEventListener('mouseup', handleMouseUp);
2599
+ };
2600
+ document.addEventListener('mousemove', handleMouseMove);
2601
+ document.addEventListener('mouseup', handleMouseUp);
2602
+ }, [width, onResize]);
2603
+ return (jsxRuntimeExports.jsxs("th", { style: {
2604
+ position: 'relative',
2605
+ padding: '12px',
2606
+ borderBottom: `2px solid ${theme === 'dark' ? '#374151' : '#E5E7EB'}`,
2607
+ backgroundColor: theme === 'dark' ? '#1F2937' : '#F3F4F6',
2608
+ textAlign: 'left',
2609
+ fontWeight: 600,
2610
+ width: `${width}px`,
2611
+ minWidth: `${width}px`,
2612
+ userSelect: 'none',
2613
+ }, children: [jsxRuntimeExports.jsxs("div", { style: { display: 'flex', alignItems: 'center', gap: '8px' }, children: [jsxRuntimeExports.jsx("span", { style: {
2614
+ fontSize: '10px',
2615
+ padding: '2px 4px',
2616
+ borderRadius: '4px',
2617
+ backgroundColor: theme === 'dark' ? '#374151' : '#E5E7EB',
2618
+ color: theme === 'dark' ? '#9CA3AF' : '#6B7280',
2619
+ }, children: column.type }), jsxRuntimeExports.jsx("span", { children: displayName || column.name })] }), jsxRuntimeExports.jsx("div", { ref: resizeRef, onMouseDown: handleMouseDown, style: {
2620
+ position: 'absolute',
2621
+ right: 0,
2622
+ top: 0,
2623
+ bottom: 0,
2624
+ width: '8px',
2625
+ cursor: 'col-resize',
2626
+ backgroundColor: isResizing ? (theme === 'dark' ? '#3B82F6' : '#2563EB') : 'transparent',
2627
+ transition: 'background-color 0.2s',
2628
+ }, onMouseEnter: (e) => {
2629
+ if (!isResizing) {
2630
+ e.currentTarget.style.backgroundColor = theme === 'dark' ? '#4B5563' : '#D1D5DB';
2631
+ }
2632
+ }, onMouseLeave: (e) => {
2633
+ if (!isResizing) {
2634
+ e.currentTarget.style.backgroundColor = 'transparent';
2635
+ }
2636
+ } })] }));
2637
+ };
2638
+ /**
2639
+ * Streaming Data Table Component
2640
+ */
2641
+ const DataTable = ({ config: configRaw, data: dataSource, theme = 'dark', className, style, onConfigChange, maxRows = DEFAULT_MAX_ITEMS, }) => {
2642
+ // Merge with defaults
2643
+ const defaults = getTableDefaults(dataSource.columns);
2644
+ const config = require$$0.useMemo(() => ({
2645
+ ...defaults,
2646
+ ...configRaw,
2647
+ }), [configRaw, defaults]);
2648
+ // Column widths state
2649
+ const [columnWidths, setColumnWidths] = require$$0.useState(() => {
2650
+ const widths = {};
2651
+ dataSource.columns.forEach((col) => {
2652
+ widths[col.name] = config.tableStyles?.[col.name]?.width || 150;
2653
+ });
2654
+ return widths;
2655
+ });
2656
+ // Track sparkline data per row/column using ref to avoid infinite loops
2657
+ const sparklineHistoryRef = require$$0.useRef({});
2658
+ // Version counter to trigger re-renders when sparkline data changes
2659
+ const [, setSparklineVersion] = require$$0.useState(0);
2660
+ // Process data for display
2661
+ const displayData = require$$0.useMemo(() => {
2662
+ const { columns, data } = dataSource;
2663
+ const { temporal } = config;
2664
+ let processedData = data.map((row) => rowToArray(row, columns));
2665
+ // Apply temporal filtering if configured
2666
+ if (temporal) {
2667
+ processedData = applyTemporalFilter(processedData, columns, temporal);
2668
+ }
2669
+ // Limit rows
2670
+ return processedData.slice(-maxRows);
2671
+ }, [dataSource, config, maxRows]);
2672
+ // Update sparkline history - use ref to avoid infinite loop
2673
+ const prevDataLengthRef = require$$0.useRef(0);
2674
+ require$$0.useEffect(() => {
2675
+ if (!config.tableStyles)
2676
+ return;
2677
+ const sparklineCols = Object.entries(config.tableStyles)
2678
+ .filter(([_, style]) => style?.miniChart === 'sparkline')
2679
+ .map(([name]) => name);
2680
+ // Only update if we have sparkline columns and data changed
2681
+ if (sparklineCols.length === 0)
2682
+ return;
2683
+ if (displayData.length === prevDataLengthRef.current && displayData.length > 0)
2684
+ return;
2685
+ prevDataLengthRef.current = displayData.length;
2686
+ let hasChanges = false;
2687
+ displayData.forEach((row, rowIndex) => {
2688
+ sparklineCols.forEach((colName) => {
2689
+ const colIndex = dataSource.columns.findIndex((c) => c.name === colName);
2690
+ if (colIndex >= 0) {
2691
+ const key = `${rowIndex}-${colName}`;
2692
+ const value = Number(row[colIndex]);
2693
+ if (!isNaN(value)) {
2694
+ const existing = sparklineHistoryRef.current[key] || [];
2695
+ const lastValue = existing[existing.length - 1];
2696
+ if (lastValue !== value || existing.length === 0) {
2697
+ sparklineHistoryRef.current[key] = [...existing, value].slice(-20);
2698
+ hasChanges = true;
2699
+ }
2700
+ }
2701
+ }
2702
+ });
2703
+ });
2704
+ // Only trigger re-render if there were actual changes
2705
+ if (hasChanges) {
2706
+ setSparklineVersion((v) => v + 1);
2707
+ }
2708
+ }, [displayData, config.tableStyles, dataSource.columns]);
2709
+ // Handle column resize
2710
+ const handleColumnResize = require$$0.useCallback((columnName, width) => {
2711
+ setColumnWidths((prev) => ({ ...prev, [columnName]: width }));
2712
+ if (onConfigChange) {
2713
+ const newConfig = {
2714
+ ...config,
2715
+ tableStyles: {
2716
+ ...config.tableStyles,
2717
+ [columnName]: {
2718
+ ...config.tableStyles?.[columnName],
2719
+ width,
2720
+ },
2721
+ },
2722
+ };
2723
+ onConfigChange(newConfig);
2724
+ }
2725
+ }, [config, onConfigChange]);
2726
+ // Visible columns
2727
+ const visibleColumns = require$$0.useMemo(() => dataSource.columns.filter((col) => {
2728
+ const style = config.tableStyles?.[col.name];
2729
+ return style?.show !== false;
2730
+ }), [dataSource.columns, config.tableStyles]);
2731
+ return (jsxRuntimeExports.jsxs("div", { className: className, style: {
2732
+ width: '100%',
2733
+ height: '100%',
2734
+ overflow: 'auto',
2735
+ backgroundColor: theme === 'dark' ? '#111827' : '#FFFFFF',
2736
+ color: theme === 'dark' ? '#F3F4F6' : '#1F2937',
2737
+ ...style,
2738
+ }, "data-testid": "data-table", children: [jsxRuntimeExports.jsxs("table", { style: {
2739
+ width: '100%',
2740
+ borderCollapse: 'collapse',
2741
+ fontSize: '14px',
2742
+ }, children: [jsxRuntimeExports.jsx("thead", { style: { position: 'sticky', top: 0, zIndex: 10 }, children: jsxRuntimeExports.jsxs("tr", { children: [jsxRuntimeExports.jsx("th", { style: {
2743
+ padding: '12px 8px',
2744
+ borderBottom: `2px solid ${theme === 'dark' ? '#374151' : '#E5E7EB'}`,
2745
+ backgroundColor: theme === 'dark' ? '#1F2937' : '#F3F4F6',
2746
+ textAlign: 'center',
2747
+ fontWeight: 600,
2748
+ width: '40px',
2749
+ minWidth: '40px',
2750
+ color: theme === 'dark' ? '#9CA3AF' : '#6B7280',
2751
+ }, children: "No." }), visibleColumns.map((col) => (jsxRuntimeExports.jsx(TableHeaderCell, { column: col, displayName: config.tableStyles?.[col.name]?.name, width: columnWidths[col.name] || 150, onResize: (width) => handleColumnResize(col.name, width), theme: theme }, col.name)))] }) }), jsxRuntimeExports.jsx("tbody", { children: displayData.map((row, rowIndex) => (jsxRuntimeExports.jsxs("tr", { style: {
2752
+ backgroundColor: rowIndex % 2 === 0
2753
+ ? 'transparent'
2754
+ : theme === 'dark'
2755
+ ? 'rgba(55, 65, 81, 0.3)'
2756
+ : 'rgba(243, 244, 246, 0.5)',
2757
+ }, children: [jsxRuntimeExports.jsx("td", { style: {
2758
+ padding: '8px',
2759
+ borderBottom: `1px solid ${theme === 'dark' ? '#374151' : '#E5E7EB'}`,
2760
+ textAlign: 'center',
2761
+ color: theme === 'dark' ? '#6B7280' : '#9CA3AF',
2762
+ fontWeight: 500,
2763
+ }, children: rowIndex + 1 }), visibleColumns.map((col) => {
2764
+ const colIndex = dataSource.columns.findIndex((c) => c.name === col.name);
2765
+ const value = row[colIndex];
2766
+ const colStyle = config.tableStyles?.[col.name];
2767
+ const sparklineKey = `${rowIndex}-${col.name}`;
2768
+ return (jsxRuntimeExports.jsx(TableCell, { value: value, isNumeric: isNumericColumn(col.type), miniChart: colStyle?.miniChart, sparklineData: sparklineHistoryRef.current[sparklineKey], color: colStyle?.color, wrap: config.tableWrap, theme: theme }, col.name));
2769
+ })] }, rowIndex))) })] }), displayData.length === 0 && (jsxRuntimeExports.jsx("div", { style: {
2770
+ padding: '48px',
2771
+ textAlign: 'center',
2772
+ color: theme === 'dark' ? '#6B7280' : '#9CA3AF',
2773
+ }, children: "No data available" }))] }));
2774
+ };
2775
+
2776
+ // Tile providers
2777
+ const TILE_PROVIDERS = {
2778
+ 'openstreetmap': 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
2779
+ 'cartodb-dark': 'https://basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
2780
+ 'cartodb-light': 'https://basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',
2781
+ };
2782
+ // Tile cache to avoid re-fetching
2783
+ const tileCache = new Map();
2784
+ /**
2785
+ * Load a map tile image
2786
+ */
2787
+ function loadTile(url) {
2788
+ if (tileCache.has(url)) {
2789
+ return Promise.resolve(tileCache.get(url));
2790
+ }
2791
+ return new Promise((resolve, reject) => {
2792
+ const img = new Image();
2793
+ img.crossOrigin = 'anonymous';
2794
+ img.onload = () => {
2795
+ tileCache.set(url, img);
2796
+ resolve(img);
2797
+ };
2798
+ img.onerror = reject;
2799
+ img.src = url;
2800
+ });
2801
+ }
2802
+ /**
2803
+ * Get tile URL for a given tile coordinate
2804
+ */
2805
+ function getTileUrl(provider, x, y, z) {
2806
+ const template = TILE_PROVIDERS[provider] || TILE_PROVIDERS['cartodb-dark'];
2807
+ return template
2808
+ .replace('{x}', String(x))
2809
+ .replace('{y}', String(y))
2810
+ .replace('{z}', String(z))
2811
+ .replace('{s}', ['a', 'b', 'c'][Math.floor(Math.random() * 3)]);
2812
+ }
2813
+ /**
2814
+ * Get default configuration for geo chart
2815
+ */
2816
+ function getGeoChartDefaults(columns) {
2817
+ // Look for lat/lng columns
2818
+ const latNames = ['lat', 'latitude', 'y'];
2819
+ const lngNames = ['lng', 'lon', 'longitude', 'x'];
2820
+ const latCol = columns.find(({ name }) => latNames.some((n) => name.toLowerCase().includes(n)));
2821
+ const lngCol = columns.find(({ name }) => lngNames.some((n) => name.toLowerCase().includes(n)));
2822
+ if (!latCol || !lngCol)
2823
+ return null;
2824
+ return {
2825
+ chartType: 'geo',
2826
+ latitude: latCol.name,
2827
+ longitude: lngCol.name,
2828
+ zoom: 2,
2829
+ tileProvider: 'cartodb-dark',
2830
+ showZoomControl: true,
2831
+ pointOpacity: 0.8,
2832
+ pointColor: '#3B82F6',
2833
+ };
2834
+ }
2835
+ /**
2836
+ * Convert lat/lng to tile coordinates
2837
+ */
2838
+ function latLngToTile(lat, lng, zoom) {
2839
+ const n = Math.pow(2, zoom);
2840
+ const x = ((lng + 180) / 360) * n;
2841
+ const latRad = (lat * Math.PI) / 180;
2842
+ const y = ((1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2) * n;
2843
+ return { x, y };
2844
+ }
2845
+ /**
2846
+ * Convert tile coordinates to pixel position
2847
+ */
2848
+ function tileToPixel(tileX, tileY, centerTileX, centerTileY, width, height, tileSize = 256) {
2849
+ const pixelX = (tileX - centerTileX) * tileSize + width / 2;
2850
+ const pixelY = (tileY - centerTileY) * tileSize + height / 2;
2851
+ return { x: pixelX, y: pixelY };
2852
+ }
2853
+ /**
2854
+ * Convert lat/lng to pixel position
2855
+ */
2856
+ function latLngToPixel(lat, lng, center, zoom, width, height) {
2857
+ const tile = latLngToTile(lat, lng, zoom);
2858
+ const centerTile = latLngToTile(center[0], center[1], zoom);
2859
+ return tileToPixel(tile.x, tile.y, centerTile.x, centerTile.y, width, height);
2860
+ }
2861
+ /**
2862
+ * Get color for a category value
2863
+ */
2864
+ function getCategoryColor(value, categories, colors) {
2865
+ const index = categories.indexOf(value);
2866
+ return colors[index % colors.length];
2867
+ }
2868
+ /**
2869
+ * GeoChart Component
2870
+ */
2871
+ const GeoChart = ({ config: configRaw, data: dataSource, theme = 'dark', className, style, maxItems, }) => {
2872
+ const canvasRef = require$$0.useRef(null);
2873
+ const containerRef = require$$0.useRef(null);
2874
+ const [dimensions, setDimensions] = require$$0.useState({ width: 0, height: 0 });
2875
+ const [zoom, setZoom] = require$$0.useState(configRaw.zoom || 2);
2876
+ const [center, setCenter] = require$$0.useState(configRaw.center || [0, 0]);
2877
+ const [isDragging, setIsDragging] = require$$0.useState(false);
2878
+ const dragStart = require$$0.useRef(null);
2879
+ // Merge with defaults
2880
+ const defaults = getGeoChartDefaults(dataSource.columns);
2881
+ const config = require$$0.useMemo(() => ({
2882
+ ...defaults,
2883
+ ...configRaw,
2884
+ }), [configRaw, defaults]);
2885
+ // Get column indices
2886
+ const latIndex = findColumnIndex(dataSource.columns, config.latitude);
2887
+ const lngIndex = findColumnIndex(dataSource.columns, config.longitude);
2888
+ const colorIndex = config.color ? findColumnIndex(dataSource.columns, config.color) : -1;
2889
+ const sizeIndex = config.size?.key ? findColumnIndex(dataSource.columns, config.size.key) : -1;
2890
+ // Process data points
2891
+ const points = require$$0.useMemo(() => {
2892
+ if (latIndex < 0 || lngIndex < 0)
2893
+ return [];
2894
+ const { columns, data } = dataSource;
2895
+ const { temporal } = config;
2896
+ // Convert data to array format and apply temporal filtering
2897
+ let processedData = data.map((row) => rowToArray(row, columns));
2898
+ // Apply temporal filtering if configured
2899
+ if (temporal) {
2900
+ processedData = applyTemporalFilter(processedData, columns, temporal);
2901
+ }
2902
+ // Limit data to maxItems
2903
+ const effectiveMaxItems = maxItems ?? config.maxItems ?? DEFAULT_MAX_ITEMS;
2904
+ processedData = processedData.slice(-effectiveMaxItems);
2905
+ const result = [];
2906
+ // Get unique color values for categorical coloring
2907
+ const colorValues = [];
2908
+ if (colorIndex >= 0) {
2909
+ processedData.forEach((arr) => {
2910
+ const val = String(arr[colorIndex] ?? '');
2911
+ if (!colorValues.includes(val)) {
2912
+ colorValues.push(val);
2913
+ }
2914
+ });
2915
+ }
2916
+ // Get color palette
2917
+ const palette = multiColorPalettes[0]?.values || ['#3B82F6'];
2918
+ // Calculate size range if needed
2919
+ let sizeMin = Infinity;
2920
+ let sizeMax = -Infinity;
2921
+ if (sizeIndex >= 0) {
2922
+ processedData.forEach((arr) => {
2923
+ const val = Number(arr[sizeIndex]);
2924
+ if (!isNaN(val)) {
2925
+ sizeMin = Math.min(sizeMin, val);
2926
+ sizeMax = Math.max(sizeMax, val);
2927
+ }
2928
+ });
2929
+ }
2930
+ processedData.forEach((arr) => {
2931
+ const lat = Number(arr[latIndex]);
2932
+ const lng = Number(arr[lngIndex]);
2933
+ if (isNaN(lat) || isNaN(lng))
2934
+ return;
2935
+ let color = config.pointColor || '#3B82F6';
2936
+ if (colorIndex >= 0) {
2937
+ const colorVal = String(arr[colorIndex] ?? '');
2938
+ color = getCategoryColor(colorVal, colorValues, palette);
2939
+ }
2940
+ let size = 6;
2941
+ if (sizeIndex >= 0) {
2942
+ const sizeVal = Number(arr[sizeIndex]);
2943
+ if (!isNaN(sizeVal) && sizeMax > sizeMin) {
2944
+ const normalized = (sizeVal - sizeMin) / (sizeMax - sizeMin);
2945
+ const minSize = config.size?.min || 4;
2946
+ const maxSize = config.size?.max || 20;
2947
+ size = minSize + normalized * (maxSize - minSize);
2948
+ }
2949
+ }
2950
+ result.push({ lat, lng, color, size, row: arr });
2951
+ });
2952
+ return result;
2953
+ }, [dataSource, latIndex, lngIndex, colorIndex, sizeIndex, config]);
2954
+ // Set initial center from first point if not specified
2955
+ require$$0.useEffect(() => {
2956
+ if (!configRaw.center && points.length > 0 && center[0] === 0 && center[1] === 0) {
2957
+ setCenter([points[0].lat, points[0].lng]);
2958
+ }
2959
+ }, [points, configRaw.center, center]);
2960
+ // Handle resize
2961
+ require$$0.useEffect(() => {
2962
+ const container = containerRef.current;
2963
+ if (!container)
2964
+ return;
2965
+ const resizeObserver = new ResizeObserver((entries) => {
2966
+ const entry = entries[0];
2967
+ if (entry) {
2968
+ setDimensions({
2969
+ width: entry.contentRect.width,
2970
+ height: entry.contentRect.height,
2971
+ });
2972
+ }
2973
+ });
2974
+ resizeObserver.observe(container);
2975
+ return () => resizeObserver.disconnect();
2976
+ }, []);
2977
+ // Draw the map and points
2978
+ require$$0.useEffect(() => {
2979
+ const canvas = canvasRef.current;
2980
+ if (!canvas || dimensions.width === 0 || dimensions.height === 0)
2981
+ return;
2982
+ const ctx = canvas.getContext('2d');
2983
+ if (!ctx)
2984
+ return;
2985
+ const { width, height } = dimensions;
2986
+ canvas.width = width;
2987
+ canvas.height = height;
2988
+ // Clear canvas with background color
2989
+ ctx.fillStyle = theme === 'dark' ? '#1a1a2e' : '#F3F4F6';
2990
+ ctx.fillRect(0, 0, width, height);
2991
+ const tileSize = 256;
2992
+ const zoomInt = Math.floor(zoom);
2993
+ const scale = Math.pow(2, zoom - zoomInt);
2994
+ // Calculate center tile
2995
+ const centerTile = latLngToTile(center[0], center[1], zoomInt);
2996
+ // Calculate how many tiles we need to cover the viewport
2997
+ const tilesX = Math.ceil(width / (tileSize * scale)) + 2;
2998
+ const tilesY = Math.ceil(height / (tileSize * scale)) + 2;
2999
+ // Calculate the top-left tile
3000
+ const startTileX = Math.floor(centerTile.x - tilesX / 2);
3001
+ const startTileY = Math.floor(centerTile.y - tilesY / 2);
3002
+ // Get tile provider
3003
+ const provider = config.tileProvider || (theme === 'dark' ? 'cartodb-dark' : 'cartodb-light');
3004
+ // Load and draw tiles
3005
+ const tilePromises = [];
3006
+ const maxTile = Math.pow(2, zoomInt);
3007
+ for (let dx = 0; dx < tilesX; dx++) {
3008
+ for (let dy = 0; dy < tilesY; dy++) {
3009
+ let tileX = startTileX + dx;
3010
+ let tileY = startTileY + dy;
3011
+ // Wrap X coordinate
3012
+ while (tileX < 0)
3013
+ tileX += maxTile;
3014
+ while (tileX >= maxTile)
3015
+ tileX -= maxTile;
3016
+ // Skip invalid Y tiles
3017
+ if (tileY < 0 || tileY >= maxTile)
3018
+ continue;
3019
+ const url = getTileUrl(provider, tileX, tileY, zoomInt);
3020
+ // Calculate pixel position for this tile
3021
+ const pixelX = (startTileX + dx - centerTile.x) * tileSize * scale + width / 2;
3022
+ const pixelY = (startTileY + dy - centerTile.y) * tileSize * scale + height / 2;
3023
+ const promise = loadTile(url)
3024
+ .then((img) => {
3025
+ ctx.drawImage(img, pixelX, pixelY, tileSize * scale, tileSize * scale);
3026
+ })
3027
+ .catch(() => {
3028
+ // Draw placeholder for failed tiles
3029
+ ctx.fillStyle = theme === 'dark' ? '#2d2d44' : '#E5E7EB';
3030
+ ctx.fillRect(pixelX, pixelY, tileSize * scale, tileSize * scale);
3031
+ });
3032
+ tilePromises.push(promise);
3033
+ }
3034
+ }
3035
+ // After all tiles are loaded, draw points on top
3036
+ Promise.all(tilePromises).then(() => {
3037
+ // Draw points
3038
+ const opacity = config.pointOpacity || 0.8;
3039
+ points.forEach((point) => {
3040
+ const pos = latLngToPixel(point.lat, point.lng, center, zoom, width, height);
3041
+ // Skip points outside viewport
3042
+ if (pos.x < -50 || pos.x > width + 50 || pos.y < -50 || pos.y > height + 50) {
3043
+ return;
3044
+ }
3045
+ const pointSize = point.size ?? 6;
3046
+ const pointColor = point.color ?? '#3B82F6';
3047
+ ctx.beginPath();
3048
+ ctx.arc(pos.x, pos.y, pointSize, 0, Math.PI * 2);
3049
+ // Parse color and add opacity
3050
+ const hexColor = pointColor.startsWith('#') ? pointColor : '#3B82F6';
3051
+ const r = parseInt(hexColor.slice(1, 3), 16);
3052
+ const g = parseInt(hexColor.slice(3, 5), 16);
3053
+ const b = parseInt(hexColor.slice(5, 7), 16);
3054
+ ctx.fillStyle = `rgba(${r}, ${g}, ${b}, ${opacity})`;
3055
+ ctx.fill();
3056
+ // Draw border
3057
+ ctx.strokeStyle = theme === 'dark' ? 'rgba(255,255,255,0.5)' : 'rgba(0,0,0,0.3)';
3058
+ ctx.lineWidth = 1.5;
3059
+ ctx.stroke();
3060
+ });
3061
+ });
3062
+ }, [dimensions, points, center, zoom, theme, config.pointOpacity, config.tileProvider]);
3063
+ // Mouse event handlers for panning
3064
+ const handleMouseDown = require$$0.useCallback((e) => {
3065
+ setIsDragging(true);
3066
+ dragStart.current = { x: e.clientX, y: e.clientY, center: [...center] };
3067
+ }, [center]);
3068
+ const handleMouseMove = require$$0.useCallback((e) => {
3069
+ if (!isDragging || !dragStart.current)
3070
+ return;
3071
+ const dx = e.clientX - dragStart.current.x;
3072
+ const dy = e.clientY - dragStart.current.y;
3073
+ // Convert pixel delta to lat/lng delta
3074
+ const scale = Math.pow(2, zoom) * 256;
3075
+ const lngDelta = (-dx / scale) * 360;
3076
+ const latDelta = (dy / scale) * 180;
3077
+ setCenter([
3078
+ Math.max(-85, Math.min(85, dragStart.current.center[0] + latDelta)),
3079
+ dragStart.current.center[1] + lngDelta,
3080
+ ]);
3081
+ }, [isDragging, zoom]);
3082
+ const handleMouseUp = require$$0.useCallback(() => {
3083
+ setIsDragging(false);
3084
+ dragStart.current = null;
3085
+ }, []);
3086
+ const handleWheel = require$$0.useCallback((e) => {
3087
+ e.preventDefault();
3088
+ const delta = e.deltaY > 0 ? -0.5 : 0.5;
3089
+ setZoom((z) => Math.max(1, Math.min(18, z + delta)));
3090
+ }, []);
3091
+ // Zoom controls
3092
+ const handleZoomIn = require$$0.useCallback(() => {
3093
+ setZoom((z) => Math.min(18, z + 1));
3094
+ }, []);
3095
+ const handleZoomOut = require$$0.useCallback(() => {
3096
+ setZoom((z) => Math.max(1, z - 1));
3097
+ }, []);
3098
+ const buttonStyle = {
3099
+ width: '32px',
3100
+ height: '32px',
3101
+ display: 'flex',
3102
+ alignItems: 'center',
3103
+ justifyContent: 'center',
3104
+ backgroundColor: theme === 'dark' ? '#374151' : '#FFFFFF',
3105
+ color: theme === 'dark' ? '#F3F4F6' : '#1F2937',
3106
+ border: `1px solid ${theme === 'dark' ? '#4B5563' : '#E5E7EB'}`,
3107
+ borderRadius: '4px',
3108
+ cursor: 'pointer',
3109
+ fontSize: '18px',
3110
+ fontWeight: 'bold',
3111
+ };
3112
+ return (jsxRuntimeExports.jsxs("div", { ref: containerRef, className: className, style: {
3113
+ width: '100%',
3114
+ height: '100%',
3115
+ position: 'relative',
3116
+ overflow: 'hidden',
3117
+ backgroundColor: theme === 'dark' ? '#1F2937' : '#F3F4F6',
3118
+ ...style,
3119
+ }, "data-testid": "geo-chart", children: [jsxRuntimeExports.jsx("canvas", { ref: canvasRef, style: {
3120
+ width: '100%',
3121
+ height: '100%',
3122
+ cursor: isDragging ? 'grabbing' : 'grab',
3123
+ }, onMouseDown: handleMouseDown, onMouseMove: handleMouseMove, onMouseUp: handleMouseUp, onMouseLeave: handleMouseUp, onWheel: handleWheel }), config.showZoomControl !== false && (jsxRuntimeExports.jsxs("div", { style: {
3124
+ position: 'absolute',
3125
+ top: '10px',
3126
+ right: '10px',
3127
+ display: 'flex',
3128
+ flexDirection: 'column',
3129
+ gap: '4px',
3130
+ }, children: [jsxRuntimeExports.jsx("button", { style: buttonStyle, onClick: handleZoomIn, children: "+" }), jsxRuntimeExports.jsx("button", { style: buttonStyle, onClick: handleZoomOut, children: "\u2212" })] })), config.showCenterDisplay && (jsxRuntimeExports.jsxs("div", { style: {
3131
+ position: 'absolute',
3132
+ bottom: '10px',
3133
+ left: '10px',
3134
+ padding: '4px 8px',
3135
+ backgroundColor: theme === 'dark' ? 'rgba(55, 65, 81, 0.9)' : 'rgba(255, 255, 255, 0.9)',
3136
+ color: theme === 'dark' ? '#F3F4F6' : '#1F2937',
3137
+ borderRadius: '4px',
3138
+ fontSize: '12px',
3139
+ fontFamily: 'monospace',
3140
+ }, children: [center[0].toFixed(4), ", ", center[1].toFixed(4), " | Zoom: ", zoom.toFixed(1)] })), jsxRuntimeExports.jsxs("div", { style: {
3141
+ position: 'absolute',
3142
+ bottom: '10px',
3143
+ right: '10px',
3144
+ padding: '4px 8px',
3145
+ backgroundColor: theme === 'dark' ? 'rgba(55, 65, 81, 0.9)' : 'rgba(255, 255, 255, 0.9)',
3146
+ color: theme === 'dark' ? '#9CA3AF' : '#6B7280',
3147
+ borderRadius: '4px',
3148
+ fontSize: '12px',
3149
+ }, children: [points.length, " points"] }), points.length === 0 && (jsxRuntimeExports.jsxs("div", { style: {
3150
+ position: 'absolute',
3151
+ top: '50%',
3152
+ left: '50%',
3153
+ transform: 'translate(-50%, -50%)',
3154
+ display: 'flex',
3155
+ flexDirection: 'column',
3156
+ alignItems: 'center',
3157
+ gap: '8px',
3158
+ color: theme === 'dark' ? '#9CA3AF' : '#6B7280',
3159
+ }, children: [jsxRuntimeExports.jsxs("svg", { width: "24", height: "24", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", style: { animation: 'spin 1s linear infinite' }, children: [jsxRuntimeExports.jsx("circle", { cx: "12", cy: "12", r: "10", strokeOpacity: "0.25" }), jsxRuntimeExports.jsx("path", { d: "M12 2a10 10 0 0 1 10 10", strokeLinecap: "round" })] }), jsxRuntimeExports.jsx("span", { children: "Waiting for data..." }), jsxRuntimeExports.jsx("style", { children: `@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }` })] }))] }));
3160
+ };
3161
+
3162
+ /**
3163
+ * Core chart utilities and base functionality
3164
+ */
3165
+ // Chart axis configuration constants
3166
+ const AXIS_HEIGHT_WITH_TITLE = 70;
3167
+ const AXIS_HEIGHT_WITHOUT_TITLE = 40;
3168
+ const MAX_LEGEND_ITEMS = 30;
3169
+ /**
3170
+ * Horizontal axis label transformation configuration
3171
+ */
3172
+ const horizontalAxisLabelConfig = {
3173
+ labelAutoHide: {
3174
+ type: 'hide',
3175
+ keepHeader: true,
3176
+ keepTail: true,
3177
+ },
3178
+ labelAutoRotate: false,
3179
+ labelAutoEllipsis: {
3180
+ type: 'ellipsis',
3181
+ minLength: 100,
3182
+ maxLength: 150,
3183
+ },
3184
+ };
3185
+ /**
3186
+ * Vertical axis label transformation configuration
3187
+ */
3188
+ const verticalAxisLabelConfig = {
3189
+ transform: [
3190
+ {
3191
+ margin: [1, 1, 1, 1],
3192
+ type: 'hide',
3193
+ },
3194
+ ],
3195
+ };
3196
+ /**
3197
+ * Apply color encoding to a chart mark
3198
+ */
3199
+ function applyColorEncoding(node, config) {
3200
+ const { values, keyColor } = config.colors;
3201
+ const domain = config.domain ?? [];
3202
+ // Generate colors for each domain value
3203
+ const colorRange = domain.map((_, index) => {
3204
+ const color = values[index % values.length];
3205
+ // Apply transparency if there's an active selection and this isn't it
3206
+ if (config.activeIndex !== undefined && config.activeIndex >= 0) {
3207
+ return index === config.activeIndex ? color : `${color}30`;
3208
+ }
3209
+ return color;
3210
+ });
3211
+ if (config.zIndex >= 0) {
3212
+ return node.encode('color', `${config.zIndex}`).scale('color', {
3213
+ type: 'ordinal',
3214
+ domain,
3215
+ range: colorRange,
3216
+ });
3217
+ }
3218
+ // Single color mode based on mark type
3219
+ switch (node.type) {
3220
+ case 'area':
3221
+ return node.style('stroke', values[keyColor]).style('fill', values[keyColor]);
3222
+ case 'line':
3223
+ return node.style('stroke', values[keyColor]);
3224
+ case 'interval':
3225
+ return node.style('fill', values[keyColor]);
3226
+ case 'point':
3227
+ return node.style('stroke', values[keyColor]);
3228
+ default:
3229
+ return node;
3230
+ }
3231
+ }
3232
+ /**
3233
+ * Apply legend configuration to a chart mark
3234
+ */
3235
+ function applyLegend(node, enabled, onItemClick, values, theme = 'dark') {
3236
+ if (!enabled || !values || values.length > MAX_LEGEND_ITEMS) {
3237
+ return node.legend(false);
3238
+ }
3239
+ const themeColors = getChartThemeColors(theme);
3240
+ return node.legend('color', {
3241
+ position: 'bottom',
3242
+ layout: {
3243
+ justifyContent: 'flex-start',
3244
+ alignItems: 'center',
3245
+ },
3246
+ itemLabelFill: themeColors.text,
3247
+ itemValueFill: themeColors.text,
3248
+ titleFill: themeColors.text,
3249
+ // Additional label styling for G2 5.x
3250
+ label: {
3251
+ fill: themeColors.text,
3252
+ fontSize: 12,
3253
+ },
3254
+ itemLabel: {
3255
+ style: {
3256
+ fill: themeColors.text,
3257
+ fontSize: 12,
3258
+ },
3259
+ },
3260
+ itemName: {
3261
+ style: {
3262
+ fill: themeColors.text,
3263
+ },
3264
+ },
3265
+ click: onItemClick
3266
+ ? (e) => {
3267
+ const index = e?.__data__?.index;
3268
+ if (index !== undefined) {
3269
+ onItemClick(index);
3270
+ }
3271
+ }
3272
+ : undefined,
3273
+ });
3274
+ }
3275
+ /**
3276
+ * Apply data label configuration to a chart mark
3277
+ */
3278
+ function applyDataLabel(node, config) {
3279
+ if (!config.enabled)
3280
+ return node;
3281
+ const { unit, yIndex, fractionDigits = 0, showAll = false, textAlign = 'center', textBaseline = 'alphabetic' } = config;
3282
+ return node.label({
3283
+ textAlign,
3284
+ textBaseline,
3285
+ text: (d) => {
3286
+ const v = Number.parseFloat(String(d?.[yIndex] ?? 0)).toFixed(fractionDigits);
3287
+ if (unit?.position === 'right') {
3288
+ return `${v}${unit.value}`;
3289
+ }
3290
+ return `${unit?.value ?? ''}${v}`;
3291
+ },
3292
+ transform: [{ type: 'overlapHide' }],
3293
+ ...(showAll ? {} : { selector: 'last' }),
3294
+ });
3295
+ }
3296
+ /**
3297
+ * Truncate label with ellipsis
3298
+ */
3299
+ function truncateLabel(value, maxChar) {
3300
+ if (maxChar === null || !value)
3301
+ return value;
3302
+ const result = value.slice(0, maxChar);
3303
+ return result === value ? result : `${result}...`;
3304
+ }
3305
+ /**
3306
+ * Render chart with standard interactions
3307
+ */
3308
+ async function renderChart(chart, theme = 'dark') {
3309
+ const themeColors = getChartThemeColors(theme);
3310
+ chart.interaction('tooltip', {
3311
+ mount: document.body,
3312
+ css: {
3313
+ '.g2-tooltip': {
3314
+ 'z-index': '10000',
3315
+ 'background-color': 'rgba(0, 0, 0, 0.8)',
3316
+ color: '#fff',
3317
+ 'border-radius': '4px',
3318
+ padding: '8px 12px',
3319
+ 'font-size': '12px',
3320
+ },
3321
+ },
3322
+ });
3323
+ chart.interaction('legendFilter', false);
3324
+ await chart.render();
3325
+ // Apply CSS-based legend text styling after render
3326
+ // This ensures legend text is visible regardless of G2's default styling
3327
+ const container = chart.getContainer();
3328
+ if (container) {
3329
+ // Query for legend text elements using various possible selectors
3330
+ const legendSelectors = [
3331
+ 'g[class*="bindClick"] text',
3332
+ 'g[class*="bindChange"] text',
3333
+ 'g[class*="legend"] text',
3334
+ 'g[class*="Legend"] text',
3335
+ // G2 5.x legend item selectors
3336
+ '[class*="category"] text',
3337
+ '[class*="item-label"] text',
3338
+ '[class*="itemLabel"] text',
3339
+ ];
3340
+ legendSelectors.forEach((selector) => {
3341
+ try {
3342
+ const elements = container.querySelectorAll(selector);
3343
+ elements.forEach((el) => {
3344
+ if (el instanceof SVGElement) {
3345
+ el.setAttribute('fill', themeColors.text);
3346
+ }
3347
+ });
3348
+ }
3349
+ catch {
3350
+ // Ignore invalid selectors
3351
+ }
3352
+ });
3353
+ // Also inject a style element for broader coverage
3354
+ const styleId = 'vistral-legend-style';
3355
+ let styleEl = container.querySelector(`#${styleId}`);
3356
+ if (!styleEl) {
3357
+ styleEl = document.createElement('style');
3358
+ styleEl.id = styleId;
3359
+ container.appendChild(styleEl);
3360
+ }
3361
+ styleEl.textContent = `
3362
+ g[bindClick] text,
3363
+ g[bindChange] text,
3364
+ [class*="legend"] text,
3365
+ [class*="Legend"] text {
3366
+ fill: ${themeColors.text} !important;
3367
+ }
3368
+ `;
3369
+ }
3370
+ }
3371
+ /**
3372
+ * Configure tooltip for a chart mark
3373
+ */
3374
+ function applyTooltip(node, enabled, config) {
3375
+ if (!enabled) {
3376
+ return node.tooltip(false);
3377
+ }
3378
+ const { xIndex, yIndex, zIndex = -1, zValues = [], colors, fractionDigits = 0, yLabel = '' } = config;
3379
+ return node.tooltip({
3380
+ title: (d) => String(d[xIndex] ?? ''),
3381
+ items: [
3382
+ (d) => {
3383
+ const colorValueIndex = zValues.indexOf(String(d[zIndex] ?? ''));
3384
+ const color = colors.values[colorValueIndex % colors.values.length] ?? colors.values[0];
3385
+ return {
3386
+ name: zIndex >= 0 ? String(d[zIndex]) : yLabel,
3387
+ value: Number.parseFloat(String(d[yIndex] ?? 0)).toFixed(fractionDigits),
3388
+ color,
3389
+ };
3390
+ },
3391
+ ],
3392
+ });
3393
+ }
3394
+ /**
3395
+ * Create default chart configuration based on data source
3396
+ */
3397
+ function createDefaultConfig(source, chartType) {
3398
+ const { header, x, y, z } = source;
3399
+ const baseConfig = {
3400
+ chartType,
3401
+ xAxis: x.index >= 0 ? header[x.index].name : '',
3402
+ yAxis: y.index >= 0 ? header[y.index].name : '',
3403
+ color: z.index >= 0 ? header[z.index].name : '',
3404
+ colors: DEFAULT_PALETTE.values,
3405
+ };
3406
+ switch (chartType) {
3407
+ case 'line':
3408
+ case 'area':
3409
+ return {
3410
+ ...baseConfig,
3411
+ xTitle: '',
3412
+ yTitle: '',
3413
+ legend: z.values.length > 0,
3414
+ dataLabel: false,
3415
+ gridlines: false,
3416
+ points: false,
3417
+ lineStyle: 'curve',
3418
+ fractionDigits: 2,
3419
+ xRange: 'Infinity',
3420
+ yRange: { min: null, max: null },
3421
+ };
3422
+ case 'bar':
3423
+ case 'column':
3424
+ return {
3425
+ ...baseConfig,
3426
+ xTitle: '',
3427
+ yTitle: '',
3428
+ legend: z.values.length > 0,
3429
+ dataLabel: false,
3430
+ gridlines: false,
3431
+ fractionDigits: 2,
3432
+ groupType: 'stack',
3433
+ };
3434
+ case 'singleValue':
3435
+ return {
3436
+ chartType,
3437
+ yAxis: y.index >= 0 ? header[y.index].name : '',
3438
+ fontSize: 64,
3439
+ color: 'blue',
3440
+ fractionDigits: 2,
3441
+ sparkline: false,
3442
+ delta: false,
3443
+ };
3444
+ default:
3445
+ return baseConfig;
3446
+ }
3447
+ }
3448
+ /**
3449
+ * Get theme colors for charts
3450
+ */
3451
+ function getChartThemeColors(theme) {
3452
+ return theme === 'dark'
3453
+ ? {
3454
+ text: '#E5E5E5', // Matches darkTheme.textColor
3455
+ textSecondary: '#9CA3AF',
3456
+ line: '#6B7280', // Matches darkTheme.axisColor (was #374151 which is very dark)
3457
+ gridline: '#374151', // Matches darkTheme.gridColor
3458
+ background: 'transparent',
3459
+ }
3460
+ : {
3461
+ text: '#000000',
3462
+ textSecondary: '#374151',
3463
+ line: '#4B5563',
3464
+ gridline: '#9CA3AF',
3465
+ background: 'transparent',
3466
+ };
3467
+ }
3468
+ /**
3469
+ * Apply chart theme
3470
+ */
3471
+ function applyChartTheme(chart, theme = 'dark') {
3472
+ const colors = getChartThemeColors(theme);
3473
+ const themeConfig = {
3474
+ view: { viewFill: colors.background },
3475
+ // Data labels on points/bars
3476
+ label: {
3477
+ fill: colors.text,
3478
+ fontSize: 11,
3479
+ },
3480
+ // Axis configuration
3481
+ axis: {
3482
+ x: {
3483
+ line: { stroke: colors.line },
3484
+ tick: { stroke: colors.line },
3485
+ label: { fill: colors.text, fontSize: 11 },
3486
+ title: { fill: colors.text, fontSize: 12, fontWeight: 500 },
3487
+ grid: { stroke: colors.gridline },
3488
+ },
3489
+ y: {
3490
+ line: { stroke: colors.line },
3491
+ tick: { stroke: colors.line },
3492
+ label: { fill: colors.text, fontSize: 11 },
3493
+ title: { fill: colors.text, fontSize: 12, fontWeight: 500 },
3494
+ grid: { stroke: colors.gridline },
3495
+ },
3496
+ },
3497
+ // Legend configuration
3498
+ legend: {
3499
+ label: { fill: colors.text, fontSize: 12 },
3500
+ title: { fill: colors.text, fontSize: 12 },
3501
+ marker: { size: 8 },
3502
+ itemLabel: { fill: colors.text, fontSize: 12 },
3503
+ itemName: { fill: colors.text, fontSize: 12 },
3504
+ itemValue: { fill: colors.textSecondary, fontSize: 12 },
3505
+ },
3506
+ // Legend category specific
3507
+ legendCategory: {
3508
+ itemLabel: { fill: colors.text },
3509
+ itemName: { fill: colors.text },
3510
+ },
3511
+ // Title configuration
3512
+ title: {
3513
+ fill: colors.text,
3514
+ fontSize: 14,
3515
+ fontWeight: 600,
3516
+ },
3517
+ };
3518
+ chart.theme(themeConfig);
3519
+ }
3520
+
3521
+ /* eslint-disable @typescript-eslint/no-explicit-any */
3522
+ /**
3523
+ * Spec Engine — converts VistralSpec + data into renderable configuration.
3524
+ *
3525
+ * This module is the heart of the declarative pipeline. It takes a
3526
+ * VistralSpec and the current data snapshot and produces transforms,
3527
+ * scales, and other derived configuration that downstream renderers
3528
+ * (e.g. AntV G2) can consume.
3529
+ */
3530
+ // ---------------------------------------------------------------------------
3531
+ // Helpers
3532
+ // ---------------------------------------------------------------------------
3533
+ /**
3534
+ * Returns the maximum parsed timestamp across all rows for the given field.
3535
+ * If data is empty, returns `Date.now()` as a sensible fallback.
3536
+ */
3537
+ function getMaxTimestamp(data, field) {
3538
+ if (data.length === 0)
3539
+ return Date.now();
3540
+ let max = -Infinity;
3541
+ for (const row of data) {
3542
+ const ts = parseDateTime(row[field]);
3543
+ if (ts > max) {
3544
+ max = ts;
3545
+ }
3546
+ }
3547
+ return max === -Infinity ? Date.now() : max;
3548
+ }
3549
+ // ---------------------------------------------------------------------------
3550
+ // G2 Spec Translation
3551
+ // ---------------------------------------------------------------------------
3552
+ /**
3553
+ * Translate a CoordinateSpec to G2 format.
3554
+ * Renames `transforms` to `transform`.
3555
+ */
3556
+ function translateCoordinate(coord) {
3557
+ const { transforms, ...rest } = coord;
3558
+ const result = { ...rest };
3559
+ if (transforms) {
3560
+ result.transform = transforms;
3561
+ }
3562
+ return result;
3563
+ }
3564
+ /**
3565
+ * Translate an AxisChannelSpec to G2 axis channel format.
3566
+ */
3567
+ function translateAxisChannel(axis, colors) {
3568
+ const result = {};
3569
+ if (axis.title !== undefined) {
3570
+ result.title = axis.title;
3571
+ result.titleFill = colors.text;
3572
+ result.titleFillOpacity = 1;
3573
+ }
3574
+ if (axis.grid !== undefined) {
3575
+ result.grid = axis.grid;
3576
+ result.gridStroke = colors.gridline;
3577
+ result.gridStrokeOpacity = 1;
3578
+ }
3579
+ if (axis.line !== undefined) {
3580
+ result.line = axis.line;
3581
+ result.lineStroke = colors.line;
3582
+ result.lineStrokeOpacity = 1;
3583
+ }
3584
+ // Force tick visibility and color
3585
+ result.tick = true;
3586
+ result.tickStroke = colors.line;
3587
+ result.tickStrokeOpacity = 1;
3588
+ // Force label color
3589
+ result.labelFill = colors.text;
3590
+ result.labelFillOpacity = 1;
3591
+ if (axis.labels) {
3592
+ if (axis.labels.format !== undefined) {
3593
+ result.labelFormatter = axis.labels.format;
3594
+ }
3595
+ if (axis.labels.rotate !== undefined) {
3596
+ result.labelTransform = [{ type: 'rotate', angle: axis.labels.rotate }];
3597
+ }
3598
+ }
3599
+ return result;
3600
+ }
3601
+ /**
3602
+ * Translate AxesSpec to G2 axis format.
3603
+ */
3604
+ function translateAxes(axes, theme = 'dark') {
3605
+ const result = {};
3606
+ const colors = getChartThemeColors(theme);
3607
+ for (const channel of ['x', 'y']) {
3608
+ const value = axes[channel];
3609
+ if (value === undefined)
3610
+ continue;
3611
+ if (value === false) {
3612
+ result[channel] = false;
3613
+ }
3614
+ else {
3615
+ result[channel] = translateAxisChannel(value, colors);
3616
+ }
3617
+ }
3618
+ return result;
3619
+ }
3620
+ /**
3621
+ * Translate a LabelSpec to G2 label format.
3622
+ * Converts `overlapHide` to `transform: [{ type: 'overlapHide' }]`.
3623
+ */
3624
+ function translateLabel(label) {
3625
+ const { overlapHide, ...rest } = label;
3626
+ const result = { ...rest };
3627
+ if (overlapHide) {
3628
+ result.transform = [{ type: 'overlapHide' }];
3629
+ }
3630
+ return result;
3631
+ }
3632
+ /**
3633
+ * Translate an AnnotationSpec to a G2 child entry.
3634
+ */
3635
+ function translateAnnotation(annotation) {
3636
+ const child = {
3637
+ type: annotation.type,
3638
+ };
3639
+ if (annotation.encode) {
3640
+ child.encode = annotation.encode;
3641
+ }
3642
+ if (annotation.style) {
3643
+ child.style = annotation.style;
3644
+ }
3645
+ if (annotation.value !== undefined) {
3646
+ child.data = [annotation.value];
3647
+ }
3648
+ if (annotation.label !== undefined) {
3649
+ child.labels = [{ text: annotation.label }];
3650
+ }
3651
+ return child;
3652
+ }
3653
+ /**
3654
+ * Translate a single MarkSpec to a G2 child entry.
3655
+ */
3656
+ function translateMark(mark, spec) {
3657
+ const child = {
3658
+ type: mark.type,
3659
+ };
3660
+ // Encode
3661
+ if (mark.encode) {
3662
+ child.encode = { ...mark.encode };
3663
+ }
3664
+ // Scale: merge top-level scales with per-mark scales (per-mark wins)
3665
+ const topScales = spec.scales ?? {};
3666
+ const markScales = mark.scales ?? {};
3667
+ const mergedScales = { ...topScales, ...markScales };
3668
+ // --- Interval Mark Safety ---
3669
+ // If the mark is 'interval' (bar/column), G2 strictly requires a 'band' scale
3670
+ // for the categorical axis to calculate bandwidth. 'ordinal' (point) scales cause crashes.
3671
+ if (mark.type === 'interval') {
3672
+ // Detect which axis is likely categorical (band).
3673
+ // Usually X for column chart, Y for bar chart.
3674
+ // Heuristic: check if the scale type is explicitly 'ordinal'.
3675
+ for (const channel in mergedScales) {
3676
+ // eslint-disable-next-line no-prototype-builtins
3677
+ if (mergedScales.hasOwnProperty(channel)) {
3678
+ const sc = mergedScales[channel];
3679
+ if (sc?.type === 'ordinal') {
3680
+ // Coerce to 'band'
3681
+ mergedScales[channel] = { ...sc, type: 'band' };
3682
+ }
3683
+ }
3684
+ }
3685
+ }
3686
+ if (Object.keys(mergedScales).length > 0) {
3687
+ child.scale = mergedScales;
3688
+ }
3689
+ // Transforms: prepend top-level transforms before mark transforms
3690
+ const topTransforms = spec.transforms ?? [];
3691
+ const markTransforms = mark.transforms ?? [];
3692
+ const allTransforms = [...topTransforms, ...markTransforms];
3693
+ if (allTransforms.length > 0) {
3694
+ child.transform = allTransforms;
3695
+ }
3696
+ // Style
3697
+ if (mark.style) {
3698
+ child.style = mark.style;
3699
+ }
3700
+ // Labels
3701
+ if (mark.labels) {
3702
+ child.labels = mark.labels.map(translateLabel);
3703
+ }
3704
+ // Tooltip
3705
+ if (mark.tooltip !== undefined) {
3706
+ child.tooltip = mark.tooltip === false ? false : mark.tooltip;
3707
+ }
3708
+ // Animate: per-mark overrides top-level
3709
+ const animate = mark.animate ?? spec.animate;
3710
+ if (animate !== undefined) {
3711
+ child.animate = animate;
3712
+ }
3713
+ return child;
3714
+ }
3715
+ // ---------------------------------------------------------------------------
3716
+ // Public API
3717
+ // ---------------------------------------------------------------------------
3718
+ /**
3719
+ * Translate a VistralSpec into a G2-compatible options object.
3720
+ *
3721
+ * This is a **pure function** — no G2 imports, no DOM access, no side effects.
3722
+ * It produces a plain object that can be handed to `chart.options(result)`.
3723
+ */
3724
+ function translateToG2Spec(spec) {
3725
+ const g2 = {
3726
+ type: 'view',
3727
+ };
3728
+ // Pre-analysis for Horizontal Bar Chart (Interval with X=Continuous, Y=Discrete)
3729
+ let shouldSwapAxes = false;
3730
+ if (!spec.coordinate) {
3731
+ const topScales = spec.scales ?? {};
3732
+ for (const mark of spec.marks) {
3733
+ if (mark.type === 'interval') {
3734
+ const markScales = mark.scales ?? {};
3735
+ const mergedScales = { ...topScales, ...markScales };
3736
+ const xScaleType = mergedScales.x?.type || 'linear';
3737
+ const yScaleType = mergedScales.y?.type || 'linear';
3738
+ const isXContinuous = ['linear', 'time', 'log', 'pow', 'sqrt'].includes(xScaleType);
3739
+ // check 'ordinal' too because we coerce it later, but here we detect intent
3740
+ const isYDiscrete = ['band', 'ordinal', 'point'].includes(yScaleType);
3741
+ if (isXContinuous && isYDiscrete) {
3742
+ shouldSwapAxes = true;
3743
+ break;
3744
+ }
3745
+ }
3746
+ }
3747
+ }
3748
+ // Coordinate
3749
+ if (spec.coordinate) {
3750
+ g2.coordinate = translateCoordinate(spec.coordinate);
3751
+ }
3752
+ else if (shouldSwapAxes) {
3753
+ g2.coordinate = { transform: [{ type: 'transpose' }] };
3754
+ }
3755
+ // Axes
3756
+ if (spec.axes) {
3757
+ // If swapping axes, we must swap the axis configuration too
3758
+ const effectiveAxes = shouldSwapAxes
3759
+ ? { ...spec.axes, x: spec.axes.y, y: spec.axes.x }
3760
+ : spec.axes;
3761
+ g2.axis = translateAxes(effectiveAxes, spec.theme);
3762
+ }
3763
+ // Legend
3764
+ if (spec.legend !== undefined) {
3765
+ if (spec.legend === false) {
3766
+ g2.legend = false;
3767
+ }
3768
+ else {
3769
+ const colors = getChartThemeColors(spec.theme ?? 'dark');
3770
+ g2.legend = {
3771
+ color: {
3772
+ position: spec.legend.position,
3773
+ // Explicitly inject colors to override G2 defaults/dimming
3774
+ itemLabelFill: colors.text,
3775
+ itemLabelFillOpacity: 1,
3776
+ itemNameFill: colors.text,
3777
+ itemNameFillOpacity: 1,
3778
+ titleFill: colors.text,
3779
+ titleFillOpacity: 1,
3780
+ // G2 5.0+ specific style overrides
3781
+ itemLabel: {
3782
+ fill: colors.text,
3783
+ fillOpacity: 1,
3784
+ fontSize: 12,
3785
+ },
3786
+ itemName: {
3787
+ fill: colors.text,
3788
+ fillOpacity: 1,
3789
+ fontSize: 12,
3790
+ },
3791
+ },
3792
+ };
3793
+ }
3794
+ }
3795
+ // Interactions: array → object map
3796
+ if (spec.interactions) {
3797
+ const interaction = {};
3798
+ for (const { type, ...options } of spec.interactions) {
3799
+ interaction[type] = options;
3800
+ }
3801
+ g2.interaction = interaction;
3802
+ }
3803
+ // Children: marks + annotations
3804
+ const children = spec.marks.map((mark) => {
3805
+ // If we are swapping axes, we need to swap the mark's encoding and scales
3806
+ // BEFORE passing to translateMark (or inside it).
3807
+ // Let's create a "swapped" mark definition to pass down.
3808
+ if (shouldSwapAxes && mark.type === 'interval') {
3809
+ const swappedMark = { ...mark };
3810
+ // Swap Encodes
3811
+ if (mark.encode) {
3812
+ swappedMark.encode = { ...mark.encode };
3813
+ const oldX = swappedMark.encode.x;
3814
+ const oldY = swappedMark.encode.y;
3815
+ if (oldX)
3816
+ swappedMark.encode.y = oldX;
3817
+ else
3818
+ delete swappedMark.encode.y;
3819
+ if (oldY)
3820
+ swappedMark.encode.x = oldY;
3821
+ else
3822
+ delete swappedMark.encode.x;
3823
+ }
3824
+ // Swap Scales
3825
+ if (mark.scales) {
3826
+ swappedMark.scales = { ...mark.scales };
3827
+ const oldX = swappedMark.scales.x;
3828
+ const oldY = swappedMark.scales.y;
3829
+ if (oldX)
3830
+ swappedMark.scales.y = oldX;
3831
+ else
3832
+ delete swappedMark.scales.y;
3833
+ if (oldY)
3834
+ swappedMark.scales.x = oldY;
3835
+ else
3836
+ delete swappedMark.scales.x;
3837
+ }
3838
+ // Note: top-level scales also need swapping but `translateMark` retrieves them from `spec.scales`.
3839
+ // We need `translateMark` to use SWAPPED top-level scales.
3840
+ // So we pass a "virtual spec" to translateMark.
3841
+ const swappedSpec = { ...spec };
3842
+ if (spec.scales) {
3843
+ swappedSpec.scales = { ...spec.scales };
3844
+ const oldX = swappedSpec.scales.x;
3845
+ const oldY = swappedSpec.scales.y;
3846
+ if (oldX)
3847
+ swappedSpec.scales.y = oldX;
3848
+ else
3849
+ delete swappedSpec.scales.y;
3850
+ if (oldY)
3851
+ swappedSpec.scales.x = oldY;
3852
+ else
3853
+ delete swappedSpec.scales.x;
3854
+ }
3855
+ return translateMark(swappedMark, swappedSpec);
3856
+ }
3857
+ return translateMark(mark, spec);
3858
+ });
3859
+ if (spec.annotations) {
3860
+ for (const annotation of spec.annotations) {
3861
+ children.push(translateAnnotation(annotation));
3862
+ }
3863
+ }
3864
+ g2.children = children;
3865
+ return g2;
3866
+ }
3867
+ // ---------------------------------------------------------------------------
3868
+ // Theme
3869
+ // ---------------------------------------------------------------------------
3870
+ /**
3871
+ * Build a G2 theme configuration object from a Vistral theme name.
3872
+ * Defaults to 'dark' when the theme argument is undefined.
3873
+ */
3874
+ function applySpecTheme(theme) {
3875
+ const colors = getChartThemeColors(theme ?? 'dark');
3876
+ return {
3877
+ view: { viewFill: colors.background },
3878
+ label: { fill: colors.text, fontSize: 11, fillOpacity: 1 },
3879
+ axis: {
3880
+ x: {
3881
+ line: { stroke: colors.line, strokeOpacity: 1 },
3882
+ tick: { stroke: colors.line, strokeOpacity: 1 },
3883
+ label: { fill: colors.text, fontSize: 11, fillOpacity: 1 },
3884
+ title: { fill: colors.text, fontSize: 12, fontWeight: 500, fillOpacity: 1 },
3885
+ grid: { stroke: colors.gridline },
3886
+ },
3887
+ y: {
3888
+ line: { stroke: colors.line, strokeOpacity: 1 },
3889
+ tick: { stroke: colors.line, strokeOpacity: 1 },
3890
+ label: { fill: colors.text, fontSize: 11, fillOpacity: 1 },
3891
+ title: { fill: colors.text, fontSize: 12, fontWeight: 500, fillOpacity: 1 },
3892
+ grid: { stroke: colors.gridline },
3893
+ },
3894
+ },
3895
+ legend: {
3896
+ label: { fill: colors.text, fontSize: 12, fillOpacity: 1 },
3897
+ title: { fill: colors.text, fontSize: 12, fillOpacity: 1 },
3898
+ itemLabel: { fill: colors.text, fontSize: 12, fillOpacity: 1 },
3899
+ itemName: { fill: colors.text, fontSize: 12, fillOpacity: 1 },
3900
+ itemValue: { fill: colors.textSecondary, fontSize: 12, fillOpacity: 1 },
3901
+ },
3902
+ legendCategory: {
3903
+ itemLabel: { fill: colors.text, fillOpacity: 1 },
3904
+ itemName: { fill: colors.text, fillOpacity: 1 },
3905
+ },
3906
+ };
3907
+ }
3908
+ // ---------------------------------------------------------------------------
3909
+ // Temporal data filtering (in JavaScript)
3910
+ // ---------------------------------------------------------------------------
3911
+ /**
3912
+ * Apply temporal filtering and sorting to data **in JavaScript** rather than
3913
+ * relying on G2 data transforms. This is the preferred approach for the
3914
+ * declarative `chart.options()` API because G2 mark-level `transform` is
3915
+ * intended for visual transforms (stackY, dodgeX, …) — not data filtering.
3916
+ *
3917
+ * Returns a new array; the input is never mutated.
3918
+ */
3919
+ function filterDataByTemporal(spec, data) {
3920
+ const { temporal } = spec;
3921
+ if (!temporal || data.length === 0)
3922
+ return data;
3923
+ const { mode, field } = temporal;
3924
+ let result = data;
3925
+ switch (mode) {
3926
+ case 'axis': {
3927
+ const { range } = temporal;
3928
+ // Time-window filter
3929
+ if (typeof range === 'number' && range !== Infinity) {
3930
+ const timeField = Array.isArray(field) ? field[0] : field;
3931
+ const maxTs = getMaxTimestamp(data, timeField);
3932
+ const windowMs = range * 60000;
3933
+ const minTs = maxTs - windowMs;
3934
+ result = result.filter((d) => {
3935
+ const ts = parseDateTime(d[timeField]);
3936
+ return ts >= minTs && ts <= maxTs;
3937
+ });
3938
+ }
3939
+ // Sort by temporal field
3940
+ const sortField = Array.isArray(field) ? field[0] : field;
3941
+ result = [...result].sort((a, b) => parseDateTime(a[sortField]) - parseDateTime(b[sortField]));
3942
+ break;
3943
+ }
3944
+ case 'frame': {
3945
+ const timeField = Array.isArray(field) ? field[0] : field;
3946
+ const maxTs = getMaxTimestamp(data, timeField);
3947
+ result = result.filter((d) => parseDateTime(d[timeField]) === maxTs);
3948
+ break;
3949
+ }
3950
+ case 'key': {
3951
+ // In 'key' mode, the `field` property represents the categorical Key (e.g. 'server').
3952
+ const keyFields = Array.isArray(temporal.field) ? temporal.field : [temporal.field];
3953
+ let timeField = 'timestamp'; // default guess
3954
+ // We need to find the timestamp field to determine "latest".
3955
+ // Heuristic: check for common names or first date-like field.
3956
+ if (data.length > 0) {
3957
+ const row = data[0];
3958
+ if (Object.prototype.hasOwnProperty.call(row, 'timestamp'))
3959
+ timeField = 'timestamp';
3960
+ else if (Object.prototype.hasOwnProperty.call(row, 'time'))
3961
+ timeField = 'time';
3962
+ else if (Object.prototype.hasOwnProperty.call(row, 'date'))
3963
+ timeField = 'date';
3964
+ else {
3965
+ // Scan for a value that looks like a timestamp
3966
+ for (const k in row) {
3967
+ if (keyFields.includes(k))
3968
+ continue;
3969
+ if (parseDateTime(row[k]) > 0) {
3970
+ timeField = k;
3971
+ break;
3972
+ }
3973
+ }
3974
+ }
3975
+ }
3976
+ const latestByKey = new Map();
3977
+ for (const row of data) {
3978
+ const key = keyFields.map(f => String(row[f] ?? '')).join('::');
3979
+ const ts = parseDateTime(row[timeField]);
3980
+ const prev = latestByKey.get(key);
3981
+ if (prev === undefined || ts > prev) {
3982
+ latestByKey.set(key, ts);
3983
+ }
3984
+ }
3985
+ result = result.filter((d) => {
3986
+ const key = keyFields.map(f => String(d[f] ?? '')).join('::');
3987
+ const ts = parseDateTime(d[timeField]);
3988
+ return latestByKey.get(key) === ts;
3989
+ });
3990
+ break;
3991
+ }
3992
+ }
3993
+ return result;
3994
+ }
3995
+ // ---------------------------------------------------------------------------
3996
+ // Pipeline helpers
3997
+ // ---------------------------------------------------------------------------
3998
+ /**
3999
+ * Collect the set of data-field names that are encoded to a channel whose
4000
+ * scale `type` is `'time'`. G2 needs Date objects (or epoch numbers) for
4001
+ * time scales — raw ISO strings are not parsed automatically.
4002
+ */
4003
+ function collectTimeFields(spec) {
4004
+ const timeFields = new Set();
4005
+ const topScales = spec.scales ?? {};
4006
+ for (const mark of spec.marks) {
4007
+ const markScales = mark.scales ?? {};
4008
+ const merged = { ...topScales, ...markScales };
4009
+ for (const [channel, scaleConfig] of Object.entries(merged)) {
4010
+ if (scaleConfig?.type === 'time') {
4011
+ const fieldName = mark.encode?.[channel];
4012
+ if (typeof fieldName === 'string') {
4013
+ timeFields.add(fieldName);
4014
+ }
4015
+ }
4016
+ }
4017
+ }
4018
+ // The temporal field is usually a date...
4019
+ // BUT if it is encoded to a 'band' scale (e.g. in a Bar Chart),
4020
+ // we must NOT convert it to a Date object, otherwise G2 will override the band scale with a time scale.
4021
+ if (spec.temporal?.field) {
4022
+ // In 'key' mode, the fields is the KEY, not the time.
4023
+ if (spec.temporal.mode === 'key') {
4024
+ return timeFields;
4025
+ }
4026
+ const fields = Array.isArray(spec.temporal.field) ? spec.temporal.field : [spec.temporal.field];
4027
+ let isBand = false;
4028
+ for (const mark of spec.marks) {
4029
+ const markScales = mark.scales ?? {};
4030
+ const merged = { ...topScales, ...markScales };
4031
+ for (const [channel, encodedField] of Object.entries(mark.encode ?? {})) {
4032
+ if (fields.includes(encodedField)) {
4033
+ const type = merged[channel]?.type;
4034
+ if (type === 'band') {
4035
+ isBand = true;
4036
+ }
4037
+ }
4038
+ }
4039
+ }
4040
+ if (!isBand) {
4041
+ fields.forEach(f => timeFields.add(f));
4042
+ }
4043
+ }
4044
+ return timeFields;
4045
+ }
4046
+ /**
4047
+ * If any area or line mark uses a `color` encoding (multi-series), return the
4048
+ * field name so the pipeline can apply a stable secondary sort. This prevents
4049
+ * the visual stacking order from flipping when series values cross each other.
4050
+ */
4051
+ function getSeriesFieldForStableSort(spec) {
4052
+ for (const mark of spec.marks) {
4053
+ if ((mark.type === 'area' || mark.type === 'line') && mark.encode?.color) {
4054
+ const colorField = mark.encode.color;
4055
+ if (typeof colorField === 'string')
4056
+ return colorField;
4057
+ }
4058
+ }
4059
+ return null;
4060
+ }
4061
+ /**
4062
+ * Find the time/x field from the spec — either from temporal config or from
4063
+ * the first mark's x encoding that uses a time scale.
4064
+ */
4065
+ function getTimeFieldFromSpec(spec) {
4066
+ // 1. From temporal config
4067
+ if (spec.temporal?.field) {
4068
+ const f = spec.temporal.field;
4069
+ return Array.isArray(f) ? f[0] : f;
4070
+ }
4071
+ // 2. From marks' x encoding with time scale
4072
+ const topScales = spec.scales ?? {};
4073
+ for (const mark of spec.marks) {
4074
+ const markScales = mark.scales ?? {};
4075
+ const merged = { ...topScales, ...markScales };
4076
+ if (merged.x?.type === 'time' && typeof mark.encode?.x === 'string') {
4077
+ return mark.encode.x;
4078
+ }
4079
+ }
4080
+ return null;
4081
+ }
4082
+ // ---------------------------------------------------------------------------
4083
+ // Pipeline
4084
+ // ---------------------------------------------------------------------------
4085
+ /**
4086
+ * Main pipeline — combines temporal data filtering, G2 spec translation, and
4087
+ * theme application into a single G2-ready options object.
4088
+ *
4089
+ * 1. `filterDataByTemporal(spec, data)` — filter/sort data in JavaScript
4090
+ * 2. `translateToG2Spec(spec)` — produce G2 options (no visual transforms)
4091
+ * 3. `applySpecTheme(spec.theme)` — attach theme configuration
4092
+ * 4. Attach filtered data + sliding time domain to each child mark
4093
+ *
4094
+ * The returned object is ready for `chart.options(result)`.
4095
+ */
4096
+ function buildG2Options(spec, data) {
4097
+ // Filter/sort data in JS — do NOT inject temporal transforms into G2
4098
+ let filteredData = filterDataByTemporal(spec, data);
4099
+ // --- Stable sort by color/series field for area/line marks -----------------
4100
+ // For stacked or overlapping area/line charts with a color encoding, the
4101
+ // data rows within each time group must be in a consistent order. Without
4102
+ // this, the visual stacking order flips when series values cross each other.
4103
+ const seriesField = getSeriesFieldForStableSort(spec);
4104
+ if (seriesField && filteredData.length > 0) {
4105
+ // Find the time/x field for the primary sort key
4106
+ const timeField = getTimeFieldFromSpec(spec);
4107
+ if (timeField) {
4108
+ // Combined sort: primary by time, secondary by series (stable)
4109
+ filteredData = [...filteredData].sort((a, b) => {
4110
+ const ta = parseDateTime(a[timeField]);
4111
+ const tb = parseDateTime(b[timeField]);
4112
+ if (ta !== tb)
4113
+ return ta - tb;
4114
+ // Same time — sort by series name for consistent stack order
4115
+ const sa = String(a[seriesField] ?? '');
4116
+ const sb = String(b[seriesField] ?? '');
4117
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
4118
+ });
4119
+ }
4120
+ else {
4121
+ // No time field — just sort by series for consistent order
4122
+ filteredData = [...filteredData].sort((a, b) => {
4123
+ const sa = String(a[seriesField] ?? '');
4124
+ const sb = String(b[seriesField] ?? '');
4125
+ return sa < sb ? -1 : sa > sb ? 1 : 0;
4126
+ });
4127
+ }
4128
+ }
4129
+ // --- Convert time-scale fields to Date objects ----------------------------
4130
+ // G2's time scale cannot parse ISO 8601 strings directly; it needs Date
4131
+ // objects (or epoch numbers). Collect every data field that is encoded to a
4132
+ // channel whose scale `type` is `'time'` and convert those field values.
4133
+ const timeFields = collectTimeFields(spec);
4134
+ if (timeFields.size > 0 && filteredData.length > 0) {
4135
+ filteredData = filteredData.map((row) => {
4136
+ const newRow = { ...row };
4137
+ for (const f of timeFields) {
4138
+ if (newRow[f] !== undefined) {
4139
+ newRow[f] = new Date(parseDateTime(newRow[f]));
4140
+ }
4141
+ }
4142
+ return newRow;
4143
+ });
4144
+ }
4145
+ // Translate spec to G2 (only visual transforms like stackY/dodgeX reach G2)
4146
+ const g2Spec = translateToG2Spec(spec);
4147
+ g2Spec.theme = applySpecTheme(spec.theme);
4148
+ // Attach filtered data at the view level. Child marks inherit from the
4149
+ // view; annotations that already carry their own `data` (set by
4150
+ // translateAnnotation) keep it — G2 lets child-level data override.
4151
+ g2Spec.data = filteredData;
4152
+ // --- Axis-mode temporal: set sliding time domain on appropriate scale ---
4153
+ // This makes the axis scroll forward as new data arrives.
4154
+ if (spec.temporal?.mode === 'axis' && filteredData.length > 0) {
4155
+ const field = spec.temporal.field;
4156
+ const timeField = Array.isArray(field) ? field[0] : field;
4157
+ const maxTs = getMaxTimestamp(filteredData, timeField);
4158
+ const range = spec.temporal.range;
4159
+ let minTs;
4160
+ if (typeof range === 'number' && range !== Infinity) {
4161
+ minTs = maxTs - range * 60000;
4162
+ }
4163
+ else {
4164
+ // No finite range — span the full data extent
4165
+ minTs = maxTs;
4166
+ for (const row of filteredData) {
4167
+ const ts = parseDateTime(row[timeField]);
4168
+ if (ts < minTs)
4169
+ minTs = ts;
4170
+ }
4171
+ }
4172
+ // Auto-detect a suitable time format mask
4173
+ // Check both axes for mask config, though usually it's on the temporal axis
4174
+ const xMask = spec.scales?.x?.mask;
4175
+ const yMask = spec.scales?.y?.mask;
4176
+ const mask = (xMask || yMask) ?? getTimeMask(minTs, maxTs);
4177
+ if (g2Spec.children) {
4178
+ for (const child of g2Spec.children) {
4179
+ if (!child.scale)
4180
+ child.scale = {};
4181
+ // Interval marks (bars) usually require a 'band' scale for width calculation.
4182
+ // Forcing 'time' scale can cause internal G2 crashes (getBandWidth error).
4183
+ // Since data is already filtered by time, we can skip enforcing time scale here.
4184
+ if (child.type === 'interval') {
4185
+ continue;
4186
+ }
4187
+ // Find which channel is using the temporal field
4188
+ let targetChannel = null;
4189
+ // Check local encode first
4190
+ if (child.encode) {
4191
+ if (child.encode.x === timeField)
4192
+ targetChannel = 'x';
4193
+ else if (child.encode.y === timeField)
4194
+ targetChannel = 'y';
4195
+ }
4196
+ // If not found in local mark, could rely on defaults but Vistral requires explicit encode usually.
4197
+ // If we found a target channel, update its scale.
4198
+ if (targetChannel) {
4199
+ // Don't override an explicit 'band' scale with 'time'
4200
+ const existingType = child.scale[targetChannel]?.type || spec.scales?.[targetChannel]?.type;
4201
+ if (existingType === 'band') {
4202
+ continue;
4203
+ }
4204
+ child.scale[targetChannel] = {
4205
+ ...(child.scale[targetChannel] ?? {}),
4206
+ type: 'time',
4207
+ domainMin: new Date(minTs),
4208
+ domainMax: new Date(maxTs),
4209
+ mask,
4210
+ };
4211
+ }
4212
+ }
4213
+ }
4214
+ }
4215
+ return g2Spec;
4216
+ }
4217
+
4218
+ // ---------------------------------------------------------------------------
4219
+ // Helpers
4220
+ // ---------------------------------------------------------------------------
4221
+ /**
4222
+ * Normalise a `StreamDataSource` into an array of `Record<string, unknown>`.
4223
+ *
4224
+ * Rows that are already objects are kept as-is. Array rows are mapped using
4225
+ * the column definitions so that `row[i]` becomes `{ [columns[i].name]: v }`.
4226
+ */
4227
+ function normaliseData(source) {
4228
+ if (!source || !source.data || source.data.length === 0)
4229
+ return [];
4230
+ const { columns, data } = source;
4231
+ return data.map((row) => {
4232
+ if (Array.isArray(row)) {
4233
+ return arrayRowToObject(row, columns);
4234
+ }
4235
+ return row;
4236
+ });
4237
+ }
4238
+ /**
4239
+ * Convert a single array-style row to an object using column definitions.
4240
+ */
4241
+ function arrayRowToObject(row, columns) {
4242
+ const obj = {};
4243
+ for (let i = 0; i < columns.length; i++) {
4244
+ obj[columns[i].name] = row[i];
4245
+ }
4246
+ return obj;
4247
+ }
4248
+ /**
4249
+ * Normalise raw rows (which may be arrays or objects) into objects.
4250
+ * When array rows are encountered without column info we fall back to
4251
+ * positional keys ("col_0", "col_1", ...).
4252
+ */
4253
+ function normaliseRows(rows, columns) {
4254
+ return rows.map((row) => {
4255
+ if (Array.isArray(row)) {
4256
+ if (columns && columns.length > 0) {
4257
+ return arrayRowToObject(row, columns);
4258
+ }
4259
+ // Fallback: positional keys
4260
+ const obj = {};
4261
+ for (let i = 0; i < row.length; i++) {
4262
+ obj[`col_${i}`] = row[i];
4263
+ }
4264
+ return obj;
4265
+ }
4266
+ return row;
4267
+ });
4268
+ }
4269
+ // ---------------------------------------------------------------------------
4270
+ // Component
4271
+ // ---------------------------------------------------------------------------
4272
+ /**
4273
+ * `VistralChart` renders a VistralSpec declaratively. It manages the G2
4274
+ * chart lifecycle and exposes an imperative `ChartHandle` via ref for
4275
+ * streaming updates.
4276
+ */
4277
+ const VistralChart = require$$0.forwardRef(function VistralChart(props, ref) {
4278
+ const { spec, source, width, height, className, style, onReady } = props;
4279
+ // DOM container
4280
+ const containerRef = require$$0.useRef(null);
4281
+ // G2 chart instance
4282
+ const chartRef = require$$0.useRef(null);
4283
+ // Internal data buffer
4284
+ const dataRef = require$$0.useRef([]);
4285
+ // Column definitions (kept from source for array-row normalisation)
4286
+ const columnsRef = require$$0.useRef([]);
4287
+ // Throttle timer
4288
+ const throttleTimerRef = require$$0.useRef(null);
4289
+ const pendingRenderRef = require$$0.useRef(false);
4290
+ // Track whether onReady has been called
4291
+ const [readyFired, setReadyFired] = require$$0.useState(false);
4292
+ // ----- Render helper -----
4293
+ const renderChart = require$$0.useCallback(() => {
4294
+ const chart = chartRef.current;
4295
+ if (!chart)
4296
+ return;
4297
+ const data = dataRef.current;
4298
+ // Skip rendering when there is no data — avoids putting G2 into a
4299
+ // broken empty state that prevents subsequent renders from showing.
4300
+ if (data.length === 0)
4301
+ return;
4302
+ const g2Options = buildG2Options(spec, data);
4303
+ // Apply explicit dimensions if provided
4304
+ if (width !== undefined)
4305
+ g2Options.width = width;
4306
+ if (height !== undefined)
4307
+ g2Options.height = height;
4308
+ chart.options(g2Options);
4309
+ chart.render();
4310
+ }, [spec, width, height]);
4311
+ /**
4312
+ * Schedule a render, respecting the optional throttle interval.
4313
+ */
4314
+ const scheduleRender = require$$0.useCallback(() => {
4315
+ const throttle = spec.streaming?.throttle ?? 0;
4316
+ if (throttle <= 0) {
4317
+ renderChart();
4318
+ return;
4319
+ }
4320
+ // If a timer is already running, mark as pending
4321
+ if (throttleTimerRef.current !== null) {
4322
+ pendingRenderRef.current = true;
4323
+ return;
4324
+ }
4325
+ renderChart();
4326
+ throttleTimerRef.current = setTimeout(() => {
4327
+ throttleTimerRef.current = null;
4328
+ if (pendingRenderRef.current) {
4329
+ pendingRenderRef.current = false;
4330
+ renderChart();
4331
+ }
4332
+ }, throttle);
4333
+ }, [renderChart, spec.streaming?.throttle]);
4334
+ // ----- Imperative handle -----
4335
+ const maxItems = spec.streaming?.maxItems ?? DEFAULT_MAX_ITEMS;
4336
+ const handleRef = require$$0.useRef({
4337
+ append: () => { },
4338
+ replace: () => { },
4339
+ clear: () => { },
4340
+ g2: null,
4341
+ });
4342
+ // Keep handle methods up-to-date
4343
+ handleRef.current.append = (rows) => {
4344
+ const normalised = normaliseRows(rows, columnsRef.current);
4345
+ const buffer = dataRef.current;
4346
+ buffer.push(...normalised);
4347
+ // Trim to maxItems
4348
+ if (buffer.length > maxItems) {
4349
+ dataRef.current = buffer.slice(buffer.length - maxItems);
4350
+ }
4351
+ scheduleRender();
4352
+ };
4353
+ handleRef.current.replace = (rows) => {
4354
+ const normalised = normaliseRows(rows, columnsRef.current);
4355
+ dataRef.current = normalised.slice(-maxItems);
4356
+ scheduleRender();
4357
+ };
4358
+ handleRef.current.clear = () => {
4359
+ dataRef.current = [];
4360
+ scheduleRender();
4361
+ };
4362
+ handleRef.current.g2 = chartRef.current;
4363
+ require$$0.useImperativeHandle(ref, () => handleRef.current, []);
4364
+ // ----- Chart lifecycle: create / destroy -----
4365
+ require$$0.useEffect(() => {
4366
+ if (!containerRef.current)
4367
+ return;
4368
+ const chart = new g2.Chart({
4369
+ container: containerRef.current,
4370
+ autoFit: true,
4371
+ });
4372
+ chartRef.current = chart;
4373
+ handleRef.current.g2 = chart;
4374
+ // Fire onReady after the chart instance is created. This happens
4375
+ // synchronously inside the effect so the handle is available by the
4376
+ // time any sibling effects or the caller's own effects run.
4377
+ if (!readyFired && onReady) {
4378
+ onReady(handleRef.current);
4379
+ setReadyFired(true);
4380
+ }
4381
+ return () => {
4382
+ // Cleanup throttle timer
4383
+ if (throttleTimerRef.current !== null) {
4384
+ clearTimeout(throttleTimerRef.current);
4385
+ throttleTimerRef.current = null;
4386
+ }
4387
+ chart.destroy();
4388
+ chartRef.current = null;
4389
+ handleRef.current.g2 = null;
4390
+ };
4391
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4392
+ }, []);
4393
+ // ----- React to source / spec changes -----
4394
+ require$$0.useEffect(() => {
4395
+ if (source) {
4396
+ columnsRef.current = source.columns;
4397
+ dataRef.current = normaliseData(source);
4398
+ }
4399
+ scheduleRender();
4400
+ }, [source, scheduleRender]);
4401
+ // ----- Render -----
4402
+ const containerStyle = {
4403
+ width: width !== undefined ? width : '100%',
4404
+ height: height !== undefined ? height : '100%',
4405
+ ...style,
4406
+ };
4407
+ return (jsxRuntimeExports.jsx("div", { ref: containerRef, className: className, style: containerStyle }));
4408
+ });
4409
+
4410
+ /**
4411
+ * Config Compilers — bridge between legacy chart configs and VistralSpec.
4412
+ *
4413
+ * These functions convert the existing high-level chart configuration
4414
+ * objects (TimeSeriesConfig, BarColumnConfig) into the declarative
4415
+ * VistralSpec grammar.
4416
+ */
4417
+ // ---------------------------------------------------------------------------
4418
+ // Helpers
4419
+ // ---------------------------------------------------------------------------
4420
+ /**
4421
+ * Map the legacy TemporalConfig to a TemporalSpec.
4422
+ * Falls back to the given `defaultField` when the config's field is empty.
4423
+ */
4424
+ function mapTemporal(temporal, defaultField) {
4425
+ if (!temporal)
4426
+ return undefined;
4427
+ return {
4428
+ mode: temporal.mode,
4429
+ field: temporal.field || defaultField,
4430
+ range: temporal.range,
4431
+ };
4432
+ }
4433
+ // ---------------------------------------------------------------------------
4434
+ // compileTimeSeriesConfig
4435
+ // ---------------------------------------------------------------------------
4436
+ /**
4437
+ * Compile a `TimeSeriesConfig` into a `VistralSpec`.
4438
+ *
4439
+ * Mapping summary:
4440
+ * - `chartType` -> mark type ('line' | 'area')
4441
+ * - `xAxis` / `yAxis` / `color` -> encode channels
4442
+ * - `lineStyle: 'curve'` -> style.shape: 'smooth', else 'line'
4443
+ * - Always adds style.connect: true
4444
+ * - `points: true` -> adds second point mark (tooltip: false)
4445
+ * - `dataLabel: true` -> adds label; if showAll is false, selector: 'last'
4446
+ * - area + color -> transforms: [{ type: 'stackY' }]
4447
+ * - scales.x: time scale with optional mask from xFormat
4448
+ * - scales.y: linear, nice, optional domain from yRange
4449
+ * - temporal -> maps to TemporalSpec
4450
+ * - streaming: { maxItems: config.maxItems ?? DEFAULT_MAX_ITEMS }
4451
+ * - axes, legend, theme, animate configured per defaults
4452
+ */
4453
+ function compileTimeSeriesConfig(config, theme = 'dark') {
4454
+ const { chartType, xAxis, yAxis, color } = config;
4455
+ // -- Primary mark ----------------------------------------------------------
4456
+ const mark = {
4457
+ type: chartType, // 'line' | 'area'
4458
+ encode: {
4459
+ x: xAxis,
4460
+ y: yAxis,
4461
+ ...(color ? { color } : {}),
4462
+ },
4463
+ style: {
4464
+ connect: true,
4465
+ ...(config.chartType === 'line'
4466
+ ? { shape: config.lineStyle === 'curve' ? 'smooth' : 'line' }
4467
+ : {}),
4468
+ ...(config.chartType === 'area' && config.lineStyle === 'curve'
4469
+ ? { shape: 'smooth' }
4470
+ : {}),
4471
+ },
4472
+ };
4473
+ // Labels
4474
+ if (config.dataLabel) {
4475
+ const label = {
4476
+ text: yAxis,
4477
+ overlapHide: true,
4478
+ };
4479
+ if (config.showAll === false) {
4480
+ label.selector = 'last';
4481
+ }
4482
+ mark.labels = [label];
4483
+ }
4484
+ // -- Marks array -----------------------------------------------------------
4485
+ const marks = [mark];
4486
+ if (config.points) {
4487
+ marks.push({
4488
+ type: 'point',
4489
+ encode: {
4490
+ x: xAxis,
4491
+ y: yAxis,
4492
+ ...(color ? { color } : {}),
4493
+ },
4494
+ tooltip: false,
4495
+ });
4496
+ }
4497
+ // -- Transforms ------------------------------------------------------------
4498
+ const transforms = [];
4499
+ if (chartType === 'area' && color) {
4500
+ transforms.push({ type: 'stackY' });
4501
+ }
4502
+ // -- Scales ----------------------------------------------------------------
4503
+ const xScale = { type: 'time' };
4504
+ if (config.xFormat) {
4505
+ xScale.mask = config.xFormat;
4506
+ }
4507
+ const yScale = { type: 'linear', nice: true };
4508
+ if (config.yRange &&
4509
+ config.yRange.min != null &&
4510
+ config.yRange.max != null) {
4511
+ yScale.domain = [config.yRange.min, config.yRange.max];
4512
+ }
4513
+ // -- Temporal --------------------------------------------------------------
4514
+ // Default to axis-bound sliding window for time series charts
4515
+ const temporal = mapTemporal(config.temporal, xAxis)
4516
+ ?? { mode: 'axis', field: xAxis, range: 2 };
4517
+ // -- Axes ------------------------------------------------------------------
4518
+ const gridY = config.gridlines ?? true;
4519
+ // -- Legend ----------------------------------------------------------------
4520
+ const legend = config.legend === false
4521
+ ? false
4522
+ : { position: 'bottom', interactive: true };
4523
+ // -- Assemble spec ---------------------------------------------------------
4524
+ const spec = {
4525
+ marks,
4526
+ scales: {
4527
+ x: xScale,
4528
+ y: yScale,
4529
+ },
4530
+ ...(transforms.length > 0 ? { transforms } : {}),
4531
+ ...(temporal ? { temporal } : {}),
4532
+ streaming: { maxItems: config.maxItems ?? DEFAULT_MAX_ITEMS },
4533
+ axes: {
4534
+ x: { title: config.xTitle || false, grid: false },
4535
+ y: { title: config.yTitle || false, grid: gridY },
4536
+ },
4537
+ legend,
4538
+ theme: theme,
4539
+ animate: false,
4540
+ };
4541
+ return spec;
4542
+ }
4543
+ // ---------------------------------------------------------------------------
4544
+ // compileBarColumnConfig
4545
+ // ---------------------------------------------------------------------------
4546
+ /**
4547
+ * Compile a `BarColumnConfig` into a `VistralSpec`.
4548
+ *
4549
+ * Mapping summary:
4550
+ * - mark type is always 'interval'
4551
+ * - `chartType 'bar'` -> coordinate: { transforms: [{ type: 'transpose' }] }
4552
+ * - `color` set -> transforms: stackY (if groupType==='stack') or dodgeX
4553
+ * - `dataLabel: true` -> label with text: yAxis, overlapHide: true
4554
+ * - scales: x with padding 0.5, y linear with nice
4555
+ * - Same streaming/axes/legend/theme/animate defaults as time series
4556
+ */
4557
+ function compileBarColumnConfig(config, theme = 'dark') {
4558
+ const { xAxis, yAxis, color, chartType } = config;
4559
+ const isBar = chartType === 'bar';
4560
+ // Standard Mapping:
4561
+ // xAxis -> Independent Variable (Category) -> x channel (Band scale)
4562
+ // yAxis -> Dependent Variable (Value) -> y channel (Linear scale)
4563
+ //
4564
+ // For Bar Charts, we apply 'transpose' to flip the visual axes.
4565
+ // -- Primary mark ----------------------------------------------------------
4566
+ const mark = {
4567
+ type: 'interval',
4568
+ encode: {
4569
+ x: xAxis,
4570
+ y: yAxis,
4571
+ ...(color ? { color } : {}),
4572
+ },
4573
+ };
4574
+ // Labels: Always display the VALUE (yAxis)
4575
+ if (config.dataLabel) {
4576
+ mark.labels = [
4577
+ {
4578
+ text: yAxis,
4579
+ overlapHide: true,
4580
+ },
4581
+ ];
4582
+ }
4583
+ // -- Transforms ------------------------------------------------------------
4584
+ const transforms = [];
4585
+ if (color) {
4586
+ transforms.push({
4587
+ type: config.groupType === 'stack' ? 'stackY' : 'dodgeX',
4588
+ });
4589
+ }
4590
+ // -- Coordinate ------------------------------------------------------------
4591
+ const coordinate = isBar
4592
+ ? { transforms: [{ type: 'transpose' }] }
4593
+ : undefined;
4594
+ // -- Scales ----------------------------------------------------------------
4595
+ // G2 Interval Mark expects 'x' to be the discrete (band) axis.
4596
+ // We use Transpose for Bar Charts to flip it to the vertical axis.
4597
+ const scales = {
4598
+ x: { type: 'band', padding: 0.5 },
4599
+ y: { type: 'linear', nice: true },
4600
+ };
4601
+ // -- Temporal --------------------------------------------------------------
4602
+ // Default temporal field is the Category field (xAxis)
4603
+ const temporal = mapTemporal(config.temporal, xAxis);
4604
+ // -- Axes ------------------------------------------------------------------
4605
+ const gridY = config.gridlines ?? true;
4606
+ // -- Legend ----------------------------------------------------------------
4607
+ const legend = config.legend === false
4608
+ ? false
4609
+ : { position: 'bottom', interactive: true };
4610
+ // -- Assemble spec ---------------------------------------------------------
4611
+ const spec = {
4612
+ marks: [mark],
4613
+ scales,
4614
+ ...(transforms.length > 0 ? { transforms } : {}),
4615
+ ...(coordinate ? { coordinate } : {}),
4616
+ ...(temporal ? { temporal } : {}),
4617
+ streaming: { maxItems: config.maxItems ?? DEFAULT_MAX_ITEMS },
4618
+ axes: {
4619
+ x: { title: config.xTitle || false, grid: false },
4620
+ y: { title: config.yTitle || false, grid: gridY },
4621
+ },
4622
+ legend,
4623
+ theme: theme,
4624
+ animate: false,
4625
+ };
4626
+ return spec;
4627
+ }
4628
+
4629
+ /**
4630
+ * Check if configuration is for a time series chart
4631
+ */
4632
+ function isTimeSeriesConfig(config) {
4633
+ return config.chartType === 'line' || config.chartType === 'area';
4634
+ }
4635
+ /**
4636
+ * Check if configuration is for a bar/column chart
4637
+ */
4638
+ function isBarColumnConfig(config) {
4639
+ return config.chartType === 'bar' || config.chartType === 'column';
4640
+ }
4641
+ /**
4642
+ * Check if configuration is for a single value chart
4643
+ */
4644
+ function isSingleValueConfig(config) {
4645
+ return config.chartType === 'singleValue';
4646
+ }
4647
+ /**
4648
+ * Check if configuration is for a table
4649
+ */
4650
+ function isTableConfig(config) {
4651
+ return config.chartType === 'table';
4652
+ }
4653
+ /**
4654
+ * Check if configuration is for a geo chart
4655
+ */
4656
+ function isGeoConfig(config) {
4657
+ return config.chartType === 'geo';
4658
+ }
4659
+ /**
4660
+ * Error Boundary for chart rendering errors
4661
+ */
4662
+ class ChartErrorBoundary extends require$$0.Component {
4663
+ constructor(props) {
4664
+ super(props);
4665
+ this.state = { hasError: false, error: null };
4666
+ }
4667
+ static getDerivedStateFromError(error) {
4668
+ return { hasError: true, error };
4669
+ }
4670
+ render() {
4671
+ if (this.state.hasError) {
4672
+ const { theme } = this.props;
4673
+ return (jsxRuntimeExports.jsxs("div", { style: {
4674
+ width: '100%',
4675
+ height: '100%',
4676
+ display: 'flex',
4677
+ flexDirection: 'column',
4678
+ alignItems: 'center',
4679
+ justifyContent: 'center',
4680
+ padding: '24px',
4681
+ textAlign: 'center',
4682
+ color: theme === 'dark' ? '#F87171' : '#DC2626',
4683
+ backgroundColor: theme === 'dark' ? 'rgba(127, 29, 29, 0.1)' : 'rgba(254, 226, 226, 0.5)',
4684
+ borderRadius: '8px',
4685
+ }, children: [jsxRuntimeExports.jsxs("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [jsxRuntimeExports.jsx("circle", { cx: "12", cy: "12", r: "10" }), jsxRuntimeExports.jsx("line", { x1: "12", y1: "8", x2: "12", y2: "12" }), jsxRuntimeExports.jsx("line", { x1: "12", y1: "16", x2: "12.01", y2: "16" })] }), jsxRuntimeExports.jsx("p", { style: { marginTop: '16px', fontWeight: 500 }, children: "Chart rendering error" }), jsxRuntimeExports.jsx("p", { style: {
4686
+ marginTop: '8px',
4687
+ fontSize: '12px',
4688
+ color: theme === 'dark' ? '#FCA5A5' : '#F87171',
4689
+ }, children: this.state.error?.message || 'Unknown error' })] }));
4690
+ }
4691
+ return this.props.children;
4692
+ }
4693
+ }
4694
+ /**
4695
+ * Placeholder for unsupported chart types
4696
+ */
4697
+ const UnsupportedChart = ({ chartType, theme, }) => (jsxRuntimeExports.jsxs("div", { style: {
4698
+ width: '100%',
4699
+ height: '100%',
4700
+ display: 'flex',
4701
+ flexDirection: 'column',
4702
+ alignItems: 'center',
4703
+ justifyContent: 'center',
4704
+ padding: '24px',
4705
+ textAlign: 'center',
4706
+ color: theme === 'dark' ? '#FCD34D' : '#D97706',
4707
+ backgroundColor: theme === 'dark' ? 'rgba(120, 53, 15, 0.1)' : 'rgba(254, 243, 199, 0.5)',
4708
+ borderRadius: '8px',
4709
+ }, children: [jsxRuntimeExports.jsxs("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round", children: [jsxRuntimeExports.jsx("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2", ry: "2" }), jsxRuntimeExports.jsx("line", { x1: "9", y1: "9", x2: "15", y2: "15" }), jsxRuntimeExports.jsx("line", { x1: "15", y1: "9", x2: "9", y2: "15" })] }), jsxRuntimeExports.jsxs("p", { style: { marginTop: '16px', fontWeight: 500 }, children: ["Unsupported chart type: \"", chartType, "\""] }), jsxRuntimeExports.jsx("p", { style: {
4710
+ marginTop: '8px',
4711
+ fontSize: '12px',
4712
+ color: theme === 'dark' ? '#FDE68A' : '#F59E0B',
4713
+ }, children: "Supported types: line, area, bar, column, singleValue, table, geo" })] }));
4714
+ /**
4715
+ * StreamChart Component
4716
+ *
4717
+ * Universal chart component for streaming data visualization.
4718
+ * Automatically renders the appropriate chart based on the config.chartType property.
4719
+ *
4720
+ * @example
4721
+ * ```tsx
4722
+ * <StreamChart
4723
+ * config={{
4724
+ * chartType: 'line',
4725
+ * xAxis: 'timestamp',
4726
+ * yAxis: 'value',
4727
+ * legend: true,
4728
+ * }}
4729
+ * data={{
4730
+ * columns: [
4731
+ * { name: 'timestamp', type: 'datetime64' },
4732
+ * { name: 'value', type: 'float64' },
4733
+ * ],
4734
+ * data: [...],
4735
+ * }}
4736
+ * theme="dark"
4737
+ * />
4738
+ * ```
4739
+ */
4740
+ const StreamChart = ({ config, data, theme = 'dark', showTable = false, className, style, onConfigChange, }) => {
4741
+ // If showTable is true, always render as table
4742
+ if (showTable) {
4743
+ const tableConfig = {
4744
+ chartType: 'table',
4745
+ tableStyles: {},
4746
+ tableWrap: false,
4747
+ };
4748
+ return (jsxRuntimeExports.jsx(ChartErrorBoundary, { theme: theme, children: jsxRuntimeExports.jsx(DataTable, { config: tableConfig, data: data, theme: theme, className: className, style: style, onConfigChange: onConfigChange, maxRows: config.maxItems }) }));
4749
+ }
4750
+ // Render appropriate chart based on config type
4751
+ const chartComponent = require$$0.useMemo(() => {
4752
+ // Phase 2: Use Grammar Abstraction for Time Series
4753
+ if (isTimeSeriesConfig(config)) {
4754
+ const spec = compileTimeSeriesConfig(config, theme);
4755
+ return (jsxRuntimeExports.jsx(VistralChart, { spec: spec, source: data, className: className, style: style }));
4756
+ }
4757
+ // Phase 2: Use Grammar Abstraction for Bar/Column
4758
+ if (isBarColumnConfig(config)) {
4759
+ const spec = compileBarColumnConfig(config, theme);
4760
+ return (jsxRuntimeExports.jsx(VistralChart, { spec: spec, source: data, className: className, style: style }));
4761
+ }
4762
+ if (isSingleValueConfig(config)) {
4763
+ return (jsxRuntimeExports.jsx(SingleValueChart, { config: config, data: data, theme: theme, className: className, style: style }));
4764
+ }
4765
+ if (isTableConfig(config)) {
4766
+ return (jsxRuntimeExports.jsx(DataTable, { config: config, data: data, theme: theme, className: className, style: style, onConfigChange: onConfigChange, maxRows: config.maxItems }));
4767
+ }
4768
+ if (isGeoConfig(config)) {
4769
+ return (jsxRuntimeExports.jsx(GeoChart, { config: config, data: data, theme: theme, className: className, style: style, maxItems: config.maxItems }));
4770
+ }
4771
+ // Unsupported chart type
4772
+ return jsxRuntimeExports.jsx(UnsupportedChart, { chartType: config.chartType, theme: theme });
4773
+ }, [config, data, theme, className, style, onConfigChange]);
4774
+ return jsxRuntimeExports.jsx(ChartErrorBoundary, { theme: theme, children: chartComponent });
4775
+ };
4776
+
4777
+ exports.AXIS_HEIGHT_WITHOUT_TITLE = AXIS_HEIGHT_WITHOUT_TITLE;
4778
+ exports.AXIS_HEIGHT_WITH_TITLE = AXIS_HEIGHT_WITH_TITLE;
4779
+ exports.DEFAULT_MAX_ITEMS = DEFAULT_MAX_ITEMS;
4780
+ exports.DEFAULT_PALETTE = DEFAULT_PALETTE;
4781
+ exports.DataTable = DataTable;
4782
+ exports.GeoChart = GeoChart;
4783
+ exports.MAX_LEGEND_ITEMS = MAX_LEGEND_ITEMS;
4784
+ exports.SingleValueChart = SingleValueChart;
4785
+ exports.StreamChart = StreamChart;
4786
+ exports.VistralChart = VistralChart;
4787
+ exports.abbreviateNumber = abbreviateNumber;
4788
+ exports.allPalettes = allPalettes;
4789
+ exports.applyChartTheme = applyChartTheme;
4790
+ exports.applyColorEncoding = applyColorEncoding;
4791
+ exports.applyDataLabel = applyDataLabel;
4792
+ exports.applyLegend = applyLegend;
4793
+ exports.applyTemporalFilter = applyTemporalFilter;
4794
+ exports.applyTooltip = applyTooltip;
4795
+ exports.calculateColumnStats = calculateColumnStats;
4796
+ exports.clamp = clamp;
4797
+ exports.compileBarColumnConfig = compileBarColumnConfig;
4798
+ exports.compileTimeSeriesConfig = compileTimeSeriesConfig;
4799
+ exports.createDefaultConfig = createDefaultConfig;
4800
+ exports.darkTheme = darkTheme;
4801
+ exports.debounce = debounce;
4802
+ exports.default = StreamChart;
4803
+ exports.filterByKey = filterByKey;
4804
+ exports.filterByLatestTimestamp = filterByLatestTimestamp;
4805
+ exports.findColumnIndex = findColumnIndex;
4806
+ exports.findPaletteByLabel = findPaletteByLabel;
4807
+ exports.findPaletteByValues = findPaletteByValues;
4808
+ exports.formatBytes = formatBytes;
4809
+ exports.formatDuration = formatDuration;
4810
+ exports.formatNumber = formatNumber;
4811
+ exports.generateId = generateId;
4812
+ exports.getChartThemeColors = getChartThemeColors;
4813
+ exports.getColumnsByType = getColumnsByType;
4814
+ exports.getGeoChartDefaults = getGeoChartDefaults;
4815
+ exports.getPaletteKeyColor = getPaletteKeyColor;
4816
+ exports.getRowValue = getRowValue;
4817
+ exports.getSeriesColors = getSeriesColors;
4818
+ exports.getSingleValueDefaults = getSingleValueDefaults;
4819
+ exports.getTableDefaults = getTableDefaults;
4820
+ exports.getTheme = getTheme;
4821
+ exports.getTimeMask = getTimeMask;
4822
+ exports.getUniqueValues = getUniqueValues;
4823
+ exports.horizontalAxisLabelConfig = horizontalAxisLabelConfig;
4824
+ exports.isBooleanColumn = isBooleanColumn;
4825
+ exports.isDateTimeColumn = isDateTimeColumn;
4826
+ exports.isNumericColumn = isNumericColumn;
4827
+ exports.isStringColumn = isStringColumn;
4828
+ exports.lightTheme = lightTheme;
4829
+ exports.mergeDeep = mergeDeep;
4830
+ exports.multiColorPalettes = multiColorPalettes;
4831
+ exports.parseDateTime = parseDateTime;
4832
+ exports.processDataSource = processDataSource;
4833
+ exports.renderChart = renderChart;
4834
+ exports.rowToArray = rowToArray;
4835
+ exports.singleColorPalettes = singleColorPalettes;
4836
+ exports.truncateLabel = truncateLabel;
4837
+ exports.truncateWithEllipsis = truncateWithEllipsis;
4838
+ exports.useAutoConfig = useAutoConfig;
4839
+ exports.useChart = useChart;
4840
+ exports.useChartAnimation = useChartAnimation;
4841
+ exports.useChartTheme = useChartTheme;
4842
+ exports.useDataSource = useDataSource;
4843
+ exports.useDebouncedValue = useDebouncedValue;
4844
+ exports.useLastUpdated = useLastUpdated;
4845
+ exports.usePrevious = usePrevious;
4846
+ exports.useResizeObserver = useResizeObserver;
4847
+ exports.useSparklineData = useSparklineData;
4848
+ exports.useStreamingData = useStreamingData;
4849
+ exports.verticalAxisLabelConfig = verticalAxisLabelConfig;
4850
+ //# sourceMappingURL=index.js.map