@codella-software/react 2.2.2 → 2.2.4

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.mjs CHANGED
@@ -1,8 +1,9 @@
1
1
  import { useState, useEffect, useMemo, createContext, useContext, useCallback, useRef } from "react";
2
2
  import { TableBuilder } from "@codella-software/utils";
3
3
  import { jsx } from "react/jsx-runtime";
4
- import { fromEvent, Observable as Observable$1, of, EMPTY, Subject as Subject$1, BehaviorSubject, timer } from "rxjs";
5
- import { takeUntil, map, filter, tap, take, distinctUntilChanged } from "rxjs/operators";
4
+ import { SSEService, WebsocketService, LiveUpdateService } from "@codella/core/live-updates";
5
+ import { RichContentService } from "@codella/core/rich-content";
6
+ import { TabsService } from "@codella/core/tabs";
6
7
  function useFiltersAndSort(options) {
7
8
  const { service } = options;
8
9
  const [state, setState] = useState(() => {
@@ -107,1387 +108,6 @@ function useFormBuilder(options) {
107
108
  }), [builder, state, isSubmitting]);
108
109
  return memoizedReturn;
109
110
  }
110
- class LiveUpdateService {
111
- constructor(wsService, sseService) {
112
- this.wsService = wsService;
113
- this.sseService = sseService;
114
- this.activeType = null;
115
- this.isInitialized = false;
116
- this.eventMappings = {};
117
- }
118
- initialize(config2) {
119
- if (this.isInitialized) {
120
- return;
121
- }
122
- this.eventMappings = config2.eventMappings ?? {};
123
- if (config2.sseEnabled) {
124
- this.activeType = "SSE";
125
- this.sseService.connect().catch((error) => {
126
- console.error("[LiveUpdateService] SSE connection failed:", error);
127
- if (config2.wsEnabled) {
128
- this.activeType = "WebSocket";
129
- this.wsService.connect();
130
- }
131
- });
132
- } else if (config2.wsEnabled) {
133
- this.activeType = "WebSocket";
134
- this.wsService.connect();
135
- }
136
- this.isInitialized = true;
137
- }
138
- get type() {
139
- return this.activeType;
140
- }
141
- get isConnected$() {
142
- switch (this.activeType) {
143
- case "SSE":
144
- return this.sseService.isConnected$;
145
- case "WebSocket":
146
- return this.wsService.isConnected$;
147
- default:
148
- return of(false);
149
- }
150
- }
151
- get canSend() {
152
- return this.activeType === "WebSocket";
153
- }
154
- /**
155
- * Subscribe to a named event using configured mappings
156
- */
157
- on(eventName) {
158
- const mapping = this.eventMappings[eventName];
159
- if (!mapping) {
160
- console.warn(`[LiveUpdateService] No mapping found for event: ${eventName}`);
161
- return EMPTY;
162
- }
163
- switch (this.activeType) {
164
- case "SSE":
165
- if (mapping.sseEvent) {
166
- return this.sseService.on(mapping.sseEvent);
167
- }
168
- break;
169
- case "WebSocket":
170
- if (mapping.wsAction) {
171
- return this.wsService.on(mapping.wsAction);
172
- }
173
- break;
174
- }
175
- return EMPTY;
176
- }
177
- /**
178
- * Send a message via WebSocket (if available)
179
- */
180
- send(action, payload) {
181
- if (!this.canSend) {
182
- console.warn("[LiveUpdateService] WebSocket not available for sending");
183
- return;
184
- }
185
- this.wsService.sendMessage(action, payload);
186
- }
187
- disconnect() {
188
- this.sseService.disconnect();
189
- this.wsService.disconnect();
190
- this.activeType = null;
191
- this.isInitialized = false;
192
- }
193
- destroy() {
194
- this.sseService.destroy();
195
- this.wsService.destroy();
196
- this.activeType = null;
197
- this.isInitialized = false;
198
- }
199
- }
200
- const DEFAULT_CONFIG = {
201
- maxReconnectAttempts: 5,
202
- initialReconnectDelay: 1e3,
203
- maxReconnectDelay: 3e4
204
- };
205
- class BaseConnectionService {
206
- constructor(config2 = {}) {
207
- this.destroySubject$ = new Subject$1();
208
- this.messagesSubject$ = new Subject$1();
209
- this.connectionStatusSubject$ = new BehaviorSubject(false);
210
- this.reconnectAttempts = 0;
211
- this.messages$ = this.messagesSubject$.asObservable();
212
- this.isConnected$ = this.connectionStatusSubject$.asObservable();
213
- this.config = { ...DEFAULT_CONFIG, ...config2 };
214
- }
215
- getReconnectDelay(attempt) {
216
- return Math.min(
217
- this.config.initialReconnectDelay * Math.pow(2, attempt),
218
- this.config.maxReconnectDelay
219
- );
220
- }
221
- scheduleReconnect(connectFn) {
222
- if (this.reconnectAttempts >= this.config.maxReconnectAttempts) {
223
- console.error(`[${this.serviceName}] Max reconnection attempts reached`);
224
- return;
225
- }
226
- const delay = this.getReconnectDelay(this.reconnectAttempts);
227
- this.reconnectAttempts++;
228
- console.log(
229
- `[${this.serviceName}] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`
230
- );
231
- timer(delay).pipe(take(1), takeUntil(this.destroySubject$)).subscribe(() => connectFn());
232
- }
233
- resetReconnectAttempts() {
234
- this.reconnectAttempts = 0;
235
- }
236
- destroy() {
237
- this.disconnect();
238
- this.destroySubject$.next();
239
- this.destroySubject$.complete();
240
- this.messagesSubject$.complete();
241
- this.connectionStatusSubject$.complete();
242
- }
243
- }
244
- class FetchEventSource {
245
- constructor(url, headers) {
246
- this.url = url;
247
- this.headers = headers;
248
- this.eventTarget = new EventTarget();
249
- this.abortController = null;
250
- }
251
- async connect() {
252
- var _a;
253
- this.abortController = new AbortController();
254
- try {
255
- const response = await fetch(this.url, {
256
- method: "GET",
257
- headers: this.headers,
258
- signal: this.abortController.signal
259
- });
260
- if (!response.ok) {
261
- const error = new Event("error");
262
- this.eventTarget.dispatchEvent(error);
263
- return;
264
- }
265
- const openEvent = new Event("open");
266
- this.eventTarget.dispatchEvent(openEvent);
267
- const reader = (_a = response.body) == null ? void 0 : _a.getReader();
268
- if (!reader) {
269
- const error = new Event("error");
270
- this.eventTarget.dispatchEvent(error);
271
- return;
272
- }
273
- const decoder = new TextDecoder();
274
- let buffer = "";
275
- while (true) {
276
- const { done, value } = await reader.read();
277
- if (done) break;
278
- buffer += decoder.decode(value, { stream: true });
279
- const lines = buffer.split("\n");
280
- for (let i = 0; i < lines.length - 1; i++) {
281
- this.processLine(lines[i]);
282
- }
283
- buffer = lines[lines.length - 1];
284
- }
285
- if (buffer.length > 0) {
286
- this.processLine(buffer);
287
- }
288
- } catch (error) {
289
- if (error instanceof Error && error.name !== "AbortError") {
290
- const errorEvent = new Event("error");
291
- this.eventTarget.dispatchEvent(errorEvent);
292
- }
293
- }
294
- }
295
- processLine(line) {
296
- line = line.trim();
297
- if (line === "" || line.startsWith(":")) {
298
- return;
299
- }
300
- const colonIndex = line.indexOf(":");
301
- if (colonIndex === -1) {
302
- return;
303
- }
304
- const field = line.substring(0, colonIndex);
305
- let value = line.substring(colonIndex + 1);
306
- if (value.startsWith(" ")) {
307
- value = value.substring(1);
308
- }
309
- if (field === "data") {
310
- const event = new MessageEvent("message", {
311
- data: value
312
- });
313
- this.eventTarget.dispatchEvent(event);
314
- }
315
- }
316
- addEventListener(type, listener) {
317
- this.eventTarget.addEventListener(type, listener);
318
- }
319
- removeEventListener(type, listener) {
320
- this.eventTarget.removeEventListener(type, listener);
321
- }
322
- get onopen() {
323
- return this.eventTarget.onopen;
324
- }
325
- set onopen(handler) {
326
- if (this.eventTarget.onopen) {
327
- this.eventTarget.removeEventListener("open", this.eventTarget.onopen);
328
- }
329
- if (handler) {
330
- this.eventTarget.addEventListener("open", handler);
331
- this.eventTarget.onopen = handler;
332
- }
333
- }
334
- get onerror() {
335
- return this.eventTarget.onerror;
336
- }
337
- set onerror(handler) {
338
- if (this.eventTarget.onerror) {
339
- this.eventTarget.removeEventListener("error", this.eventTarget.onerror);
340
- }
341
- if (handler) {
342
- this.eventTarget.addEventListener("error", handler);
343
- this.eventTarget.onerror = handler;
344
- }
345
- }
346
- close() {
347
- var _a;
348
- (_a = this.abortController) == null ? void 0 : _a.abort();
349
- this.abortController = null;
350
- }
351
- }
352
- class SSEService extends BaseConnectionService {
353
- constructor(config2) {
354
- super();
355
- this.eventSource = null;
356
- this.sseConfig = {
357
- headerName: "Authorization",
358
- headerPrefix: "Bearer",
359
- ...config2
360
- };
361
- }
362
- get serviceName() {
363
- return "SSE";
364
- }
365
- async connect() {
366
- if (this.eventSource) {
367
- return;
368
- }
369
- try {
370
- if (!this.sseConfig.authProvider.isAuthenticated()) {
371
- console.error("[SSE] Not authenticated");
372
- return;
373
- }
374
- const idToken = await this.sseConfig.authProvider.getIdToken();
375
- if (!idToken) {
376
- console.error("[SSE] No auth token available");
377
- return;
378
- }
379
- const headers = {
380
- [this.sseConfig.headerName]: `${this.sseConfig.headerPrefix} ${idToken}`
381
- };
382
- const url = new URL(this.sseConfig.url);
383
- this.eventSource = new FetchEventSource(url.toString(), headers);
384
- this.setupEventListeners();
385
- await this.eventSource.connect();
386
- } catch (error) {
387
- console.error("[SSE] Connection error:", error);
388
- this.scheduleReconnect(() => this.connect());
389
- }
390
- }
391
- setupEventListeners() {
392
- if (!this.eventSource) return;
393
- this.eventSource.onopen = () => {
394
- console.log("[SSE] Connected");
395
- this.connectionStatusSubject$.next(true);
396
- this.resetReconnectAttempts();
397
- };
398
- this.eventSource.onerror = (event) => {
399
- console.error("[SSE] Error:", event);
400
- this.connectionStatusSubject$.next(false);
401
- this.cleanup();
402
- this.scheduleReconnect(() => this.connect());
403
- };
404
- fromEvent(this.eventSource, "message").pipe(
405
- takeUntil(this.destroySubject$),
406
- map((event) => {
407
- try {
408
- return JSON.parse(event.data);
409
- } catch (error) {
410
- console.error("[SSE] Parse error:", error);
411
- return null;
412
- }
413
- }),
414
- filter((msg) => msg !== null)
415
- ).subscribe((message) => {
416
- this.messagesSubject$.next(message);
417
- });
418
- }
419
- cleanup() {
420
- var _a;
421
- (_a = this.eventSource) == null ? void 0 : _a.close();
422
- this.eventSource = null;
423
- }
424
- on(eventType) {
425
- return this.messages$.pipe(
426
- filter((msg) => msg.eventType === eventType),
427
- map((msg) => msg.data)
428
- );
429
- }
430
- disconnect() {
431
- this.cleanup();
432
- this.connectionStatusSubject$.next(false);
433
- this.resetReconnectAttempts();
434
- }
435
- destroy() {
436
- this.cleanup();
437
- this.destroySubject$.next();
438
- this.destroySubject$.complete();
439
- }
440
- }
441
- var extendStatics = function(d, b) {
442
- extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
443
- d2.__proto__ = b2;
444
- } || function(d2, b2) {
445
- for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
446
- };
447
- return extendStatics(d, b);
448
- };
449
- function __extends(d, b) {
450
- if (typeof b !== "function" && b !== null)
451
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
452
- extendStatics(d, b);
453
- function __() {
454
- this.constructor = d;
455
- }
456
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
457
- }
458
- var __assign = function() {
459
- __assign = Object.assign || function __assign2(t) {
460
- for (var s, i = 1, n = arguments.length; i < n; i++) {
461
- s = arguments[i];
462
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
463
- }
464
- return t;
465
- };
466
- return __assign.apply(this, arguments);
467
- };
468
- function __values(o) {
469
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
470
- if (m) return m.call(o);
471
- if (o && typeof o.length === "number") return {
472
- next: function() {
473
- if (o && i >= o.length) o = void 0;
474
- return { value: o && o[i++], done: !o };
475
- }
476
- };
477
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
478
- }
479
- function __read(o, n) {
480
- var m = typeof Symbol === "function" && o[Symbol.iterator];
481
- if (!m) return o;
482
- var i = m.call(o), r, ar = [], e;
483
- try {
484
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
485
- } catch (error) {
486
- e = { error };
487
- } finally {
488
- try {
489
- if (r && !r.done && (m = i["return"])) m.call(i);
490
- } finally {
491
- if (e) throw e.error;
492
- }
493
- }
494
- return ar;
495
- }
496
- function __spreadArray(to, from, pack) {
497
- if (arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
498
- if (ar || !(i in from)) {
499
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
500
- ar[i] = from[i];
501
- }
502
- }
503
- return to.concat(ar || Array.prototype.slice.call(from));
504
- }
505
- typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
506
- var e = new Error(message);
507
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
508
- };
509
- function isFunction(value) {
510
- return typeof value === "function";
511
- }
512
- function createErrorClass(createImpl) {
513
- var _super = function(instance) {
514
- Error.call(instance);
515
- instance.stack = new Error().stack;
516
- };
517
- var ctorFunc = createImpl(_super);
518
- ctorFunc.prototype = Object.create(Error.prototype);
519
- ctorFunc.prototype.constructor = ctorFunc;
520
- return ctorFunc;
521
- }
522
- var UnsubscriptionError = createErrorClass(function(_super) {
523
- return function UnsubscriptionErrorImpl(errors) {
524
- _super(this);
525
- this.message = errors ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function(err, i) {
526
- return i + 1 + ") " + err.toString();
527
- }).join("\n ") : "";
528
- this.name = "UnsubscriptionError";
529
- this.errors = errors;
530
- };
531
- });
532
- function arrRemove(arr, item) {
533
- if (arr) {
534
- var index = arr.indexOf(item);
535
- 0 <= index && arr.splice(index, 1);
536
- }
537
- }
538
- var Subscription = (function() {
539
- function Subscription2(initialTeardown) {
540
- this.initialTeardown = initialTeardown;
541
- this.closed = false;
542
- this._parentage = null;
543
- this._finalizers = null;
544
- }
545
- Subscription2.prototype.unsubscribe = function() {
546
- var e_1, _a, e_2, _b;
547
- var errors;
548
- if (!this.closed) {
549
- this.closed = true;
550
- var _parentage = this._parentage;
551
- if (_parentage) {
552
- this._parentage = null;
553
- if (Array.isArray(_parentage)) {
554
- try {
555
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
556
- var parent_1 = _parentage_1_1.value;
557
- parent_1.remove(this);
558
- }
559
- } catch (e_1_1) {
560
- e_1 = { error: e_1_1 };
561
- } finally {
562
- try {
563
- if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
564
- } finally {
565
- if (e_1) throw e_1.error;
566
- }
567
- }
568
- } else {
569
- _parentage.remove(this);
570
- }
571
- }
572
- var initialFinalizer = this.initialTeardown;
573
- if (isFunction(initialFinalizer)) {
574
- try {
575
- initialFinalizer();
576
- } catch (e) {
577
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
578
- }
579
- }
580
- var _finalizers = this._finalizers;
581
- if (_finalizers) {
582
- this._finalizers = null;
583
- try {
584
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
585
- var finalizer = _finalizers_1_1.value;
586
- try {
587
- execFinalizer(finalizer);
588
- } catch (err) {
589
- errors = errors !== null && errors !== void 0 ? errors : [];
590
- if (err instanceof UnsubscriptionError) {
591
- errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
592
- } else {
593
- errors.push(err);
594
- }
595
- }
596
- }
597
- } catch (e_2_1) {
598
- e_2 = { error: e_2_1 };
599
- } finally {
600
- try {
601
- if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
602
- } finally {
603
- if (e_2) throw e_2.error;
604
- }
605
- }
606
- }
607
- if (errors) {
608
- throw new UnsubscriptionError(errors);
609
- }
610
- }
611
- };
612
- Subscription2.prototype.add = function(teardown) {
613
- var _a;
614
- if (teardown && teardown !== this) {
615
- if (this.closed) {
616
- execFinalizer(teardown);
617
- } else {
618
- if (teardown instanceof Subscription2) {
619
- if (teardown.closed || teardown._hasParent(this)) {
620
- return;
621
- }
622
- teardown._addParent(this);
623
- }
624
- (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
625
- }
626
- }
627
- };
628
- Subscription2.prototype._hasParent = function(parent) {
629
- var _parentage = this._parentage;
630
- return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
631
- };
632
- Subscription2.prototype._addParent = function(parent) {
633
- var _parentage = this._parentage;
634
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
635
- };
636
- Subscription2.prototype._removeParent = function(parent) {
637
- var _parentage = this._parentage;
638
- if (_parentage === parent) {
639
- this._parentage = null;
640
- } else if (Array.isArray(_parentage)) {
641
- arrRemove(_parentage, parent);
642
- }
643
- };
644
- Subscription2.prototype.remove = function(teardown) {
645
- var _finalizers = this._finalizers;
646
- _finalizers && arrRemove(_finalizers, teardown);
647
- if (teardown instanceof Subscription2) {
648
- teardown._removeParent(this);
649
- }
650
- };
651
- Subscription2.EMPTY = (function() {
652
- var empty = new Subscription2();
653
- empty.closed = true;
654
- return empty;
655
- })();
656
- return Subscription2;
657
- })();
658
- var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
659
- function isSubscription(value) {
660
- return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
661
- }
662
- function execFinalizer(finalizer) {
663
- if (isFunction(finalizer)) {
664
- finalizer();
665
- } else {
666
- finalizer.unsubscribe();
667
- }
668
- }
669
- var config = {
670
- Promise: void 0
671
- };
672
- var timeoutProvider = {
673
- setTimeout: function(handler, timeout) {
674
- var args = [];
675
- for (var _i = 2; _i < arguments.length; _i++) {
676
- args[_i - 2] = arguments[_i];
677
- }
678
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
679
- },
680
- clearTimeout: function(handle) {
681
- return clearTimeout(handle);
682
- },
683
- delegate: void 0
684
- };
685
- function reportUnhandledError(err) {
686
- timeoutProvider.setTimeout(function() {
687
- {
688
- throw err;
689
- }
690
- });
691
- }
692
- function noop() {
693
- }
694
- function errorContext(cb) {
695
- {
696
- cb();
697
- }
698
- }
699
- var Subscriber = (function(_super) {
700
- __extends(Subscriber2, _super);
701
- function Subscriber2(destination) {
702
- var _this = _super.call(this) || this;
703
- _this.isStopped = false;
704
- if (destination) {
705
- _this.destination = destination;
706
- if (isSubscription(destination)) {
707
- destination.add(_this);
708
- }
709
- } else {
710
- _this.destination = EMPTY_OBSERVER;
711
- }
712
- return _this;
713
- }
714
- Subscriber2.create = function(next, error, complete) {
715
- return new SafeSubscriber(next, error, complete);
716
- };
717
- Subscriber2.prototype.next = function(value) {
718
- if (this.isStopped) ;
719
- else {
720
- this._next(value);
721
- }
722
- };
723
- Subscriber2.prototype.error = function(err) {
724
- if (this.isStopped) ;
725
- else {
726
- this.isStopped = true;
727
- this._error(err);
728
- }
729
- };
730
- Subscriber2.prototype.complete = function() {
731
- if (this.isStopped) ;
732
- else {
733
- this.isStopped = true;
734
- this._complete();
735
- }
736
- };
737
- Subscriber2.prototype.unsubscribe = function() {
738
- if (!this.closed) {
739
- this.isStopped = true;
740
- _super.prototype.unsubscribe.call(this);
741
- this.destination = null;
742
- }
743
- };
744
- Subscriber2.prototype._next = function(value) {
745
- this.destination.next(value);
746
- };
747
- Subscriber2.prototype._error = function(err) {
748
- try {
749
- this.destination.error(err);
750
- } finally {
751
- this.unsubscribe();
752
- }
753
- };
754
- Subscriber2.prototype._complete = function() {
755
- try {
756
- this.destination.complete();
757
- } finally {
758
- this.unsubscribe();
759
- }
760
- };
761
- return Subscriber2;
762
- })(Subscription);
763
- var ConsumerObserver = (function() {
764
- function ConsumerObserver2(partialObserver) {
765
- this.partialObserver = partialObserver;
766
- }
767
- ConsumerObserver2.prototype.next = function(value) {
768
- var partialObserver = this.partialObserver;
769
- if (partialObserver.next) {
770
- try {
771
- partialObserver.next(value);
772
- } catch (error) {
773
- handleUnhandledError(error);
774
- }
775
- }
776
- };
777
- ConsumerObserver2.prototype.error = function(err) {
778
- var partialObserver = this.partialObserver;
779
- if (partialObserver.error) {
780
- try {
781
- partialObserver.error(err);
782
- } catch (error) {
783
- handleUnhandledError(error);
784
- }
785
- } else {
786
- handleUnhandledError(err);
787
- }
788
- };
789
- ConsumerObserver2.prototype.complete = function() {
790
- var partialObserver = this.partialObserver;
791
- if (partialObserver.complete) {
792
- try {
793
- partialObserver.complete();
794
- } catch (error) {
795
- handleUnhandledError(error);
796
- }
797
- }
798
- };
799
- return ConsumerObserver2;
800
- })();
801
- var SafeSubscriber = (function(_super) {
802
- __extends(SafeSubscriber2, _super);
803
- function SafeSubscriber2(observerOrNext, error, complete) {
804
- var _this = _super.call(this) || this;
805
- var partialObserver;
806
- if (isFunction(observerOrNext) || !observerOrNext) {
807
- partialObserver = {
808
- next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : void 0,
809
- error: error !== null && error !== void 0 ? error : void 0,
810
- complete: complete !== null && complete !== void 0 ? complete : void 0
811
- };
812
- } else {
813
- {
814
- partialObserver = observerOrNext;
815
- }
816
- }
817
- _this.destination = new ConsumerObserver(partialObserver);
818
- return _this;
819
- }
820
- return SafeSubscriber2;
821
- })(Subscriber);
822
- function handleUnhandledError(error) {
823
- {
824
- reportUnhandledError(error);
825
- }
826
- }
827
- function defaultErrorHandler(err) {
828
- throw err;
829
- }
830
- var EMPTY_OBSERVER = {
831
- closed: true,
832
- next: noop,
833
- error: defaultErrorHandler,
834
- complete: noop
835
- };
836
- var observable = (function() {
837
- return typeof Symbol === "function" && Symbol.observable || "@@observable";
838
- })();
839
- function identity(x) {
840
- return x;
841
- }
842
- function pipeFromArray(fns) {
843
- if (fns.length === 0) {
844
- return identity;
845
- }
846
- if (fns.length === 1) {
847
- return fns[0];
848
- }
849
- return function piped(input) {
850
- return fns.reduce(function(prev, fn) {
851
- return fn(prev);
852
- }, input);
853
- };
854
- }
855
- var Observable = (function() {
856
- function Observable2(subscribe) {
857
- if (subscribe) {
858
- this._subscribe = subscribe;
859
- }
860
- }
861
- Observable2.prototype.lift = function(operator) {
862
- var observable2 = new Observable2();
863
- observable2.source = this;
864
- observable2.operator = operator;
865
- return observable2;
866
- };
867
- Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
868
- var _this = this;
869
- var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
870
- errorContext(function() {
871
- var _a = _this, operator = _a.operator, source = _a.source;
872
- subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
873
- });
874
- return subscriber;
875
- };
876
- Observable2.prototype._trySubscribe = function(sink) {
877
- try {
878
- return this._subscribe(sink);
879
- } catch (err) {
880
- sink.error(err);
881
- }
882
- };
883
- Observable2.prototype.forEach = function(next, promiseCtor) {
884
- var _this = this;
885
- promiseCtor = getPromiseCtor(promiseCtor);
886
- return new promiseCtor(function(resolve, reject) {
887
- var subscriber = new SafeSubscriber({
888
- next: function(value) {
889
- try {
890
- next(value);
891
- } catch (err) {
892
- reject(err);
893
- subscriber.unsubscribe();
894
- }
895
- },
896
- error: reject,
897
- complete: resolve
898
- });
899
- _this.subscribe(subscriber);
900
- });
901
- };
902
- Observable2.prototype._subscribe = function(subscriber) {
903
- var _a;
904
- return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
905
- };
906
- Observable2.prototype[observable] = function() {
907
- return this;
908
- };
909
- Observable2.prototype.pipe = function() {
910
- var operations = [];
911
- for (var _i = 0; _i < arguments.length; _i++) {
912
- operations[_i] = arguments[_i];
913
- }
914
- return pipeFromArray(operations)(this);
915
- };
916
- Observable2.prototype.toPromise = function(promiseCtor) {
917
- var _this = this;
918
- promiseCtor = getPromiseCtor(promiseCtor);
919
- return new promiseCtor(function(resolve, reject) {
920
- var value;
921
- _this.subscribe(function(x) {
922
- return value = x;
923
- }, function(err) {
924
- return reject(err);
925
- }, function() {
926
- return resolve(value);
927
- });
928
- });
929
- };
930
- Observable2.create = function(subscribe) {
931
- return new Observable2(subscribe);
932
- };
933
- return Observable2;
934
- })();
935
- function getPromiseCtor(promiseCtor) {
936
- var _a;
937
- return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
938
- }
939
- function isObserver(value) {
940
- return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
941
- }
942
- function isSubscriber(value) {
943
- return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
944
- }
945
- var ObjectUnsubscribedError = createErrorClass(function(_super) {
946
- return function ObjectUnsubscribedErrorImpl() {
947
- _super(this);
948
- this.name = "ObjectUnsubscribedError";
949
- this.message = "object unsubscribed";
950
- };
951
- });
952
- var Subject = (function(_super) {
953
- __extends(Subject2, _super);
954
- function Subject2() {
955
- var _this = _super.call(this) || this;
956
- _this.closed = false;
957
- _this.currentObservers = null;
958
- _this.observers = [];
959
- _this.isStopped = false;
960
- _this.hasError = false;
961
- _this.thrownError = null;
962
- return _this;
963
- }
964
- Subject2.prototype.lift = function(operator) {
965
- var subject = new AnonymousSubject(this, this);
966
- subject.operator = operator;
967
- return subject;
968
- };
969
- Subject2.prototype._throwIfClosed = function() {
970
- if (this.closed) {
971
- throw new ObjectUnsubscribedError();
972
- }
973
- };
974
- Subject2.prototype.next = function(value) {
975
- var _this = this;
976
- errorContext(function() {
977
- var e_1, _a;
978
- _this._throwIfClosed();
979
- if (!_this.isStopped) {
980
- if (!_this.currentObservers) {
981
- _this.currentObservers = Array.from(_this.observers);
982
- }
983
- try {
984
- for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
985
- var observer = _c.value;
986
- observer.next(value);
987
- }
988
- } catch (e_1_1) {
989
- e_1 = { error: e_1_1 };
990
- } finally {
991
- try {
992
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
993
- } finally {
994
- if (e_1) throw e_1.error;
995
- }
996
- }
997
- }
998
- });
999
- };
1000
- Subject2.prototype.error = function(err) {
1001
- var _this = this;
1002
- errorContext(function() {
1003
- _this._throwIfClosed();
1004
- if (!_this.isStopped) {
1005
- _this.hasError = _this.isStopped = true;
1006
- _this.thrownError = err;
1007
- var observers = _this.observers;
1008
- while (observers.length) {
1009
- observers.shift().error(err);
1010
- }
1011
- }
1012
- });
1013
- };
1014
- Subject2.prototype.complete = function() {
1015
- var _this = this;
1016
- errorContext(function() {
1017
- _this._throwIfClosed();
1018
- if (!_this.isStopped) {
1019
- _this.isStopped = true;
1020
- var observers = _this.observers;
1021
- while (observers.length) {
1022
- observers.shift().complete();
1023
- }
1024
- }
1025
- });
1026
- };
1027
- Subject2.prototype.unsubscribe = function() {
1028
- this.isStopped = this.closed = true;
1029
- this.observers = this.currentObservers = null;
1030
- };
1031
- Object.defineProperty(Subject2.prototype, "observed", {
1032
- get: function() {
1033
- var _a;
1034
- return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
1035
- },
1036
- enumerable: false,
1037
- configurable: true
1038
- });
1039
- Subject2.prototype._trySubscribe = function(subscriber) {
1040
- this._throwIfClosed();
1041
- return _super.prototype._trySubscribe.call(this, subscriber);
1042
- };
1043
- Subject2.prototype._subscribe = function(subscriber) {
1044
- this._throwIfClosed();
1045
- this._checkFinalizedStatuses(subscriber);
1046
- return this._innerSubscribe(subscriber);
1047
- };
1048
- Subject2.prototype._innerSubscribe = function(subscriber) {
1049
- var _this = this;
1050
- var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
1051
- if (hasError || isStopped) {
1052
- return EMPTY_SUBSCRIPTION;
1053
- }
1054
- this.currentObservers = null;
1055
- observers.push(subscriber);
1056
- return new Subscription(function() {
1057
- _this.currentObservers = null;
1058
- arrRemove(observers, subscriber);
1059
- });
1060
- };
1061
- Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
1062
- var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1063
- if (hasError) {
1064
- subscriber.error(thrownError);
1065
- } else if (isStopped) {
1066
- subscriber.complete();
1067
- }
1068
- };
1069
- Subject2.prototype.asObservable = function() {
1070
- var observable2 = new Observable();
1071
- observable2.source = this;
1072
- return observable2;
1073
- };
1074
- Subject2.create = function(destination, source) {
1075
- return new AnonymousSubject(destination, source);
1076
- };
1077
- return Subject2;
1078
- })(Observable);
1079
- var AnonymousSubject = (function(_super) {
1080
- __extends(AnonymousSubject2, _super);
1081
- function AnonymousSubject2(destination, source) {
1082
- var _this = _super.call(this) || this;
1083
- _this.destination = destination;
1084
- _this.source = source;
1085
- return _this;
1086
- }
1087
- AnonymousSubject2.prototype.next = function(value) {
1088
- var _a, _b;
1089
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1090
- };
1091
- AnonymousSubject2.prototype.error = function(err) {
1092
- var _a, _b;
1093
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1094
- };
1095
- AnonymousSubject2.prototype.complete = function() {
1096
- var _a, _b;
1097
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1098
- };
1099
- AnonymousSubject2.prototype._subscribe = function(subscriber) {
1100
- var _a, _b;
1101
- return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1102
- };
1103
- return AnonymousSubject2;
1104
- })(Subject);
1105
- var dateTimestampProvider = {
1106
- now: function() {
1107
- return (dateTimestampProvider.delegate || Date).now();
1108
- },
1109
- delegate: void 0
1110
- };
1111
- var ReplaySubject = (function(_super) {
1112
- __extends(ReplaySubject2, _super);
1113
- function ReplaySubject2(_bufferSize, _windowTime, _timestampProvider) {
1114
- if (_bufferSize === void 0) {
1115
- _bufferSize = Infinity;
1116
- }
1117
- if (_windowTime === void 0) {
1118
- _windowTime = Infinity;
1119
- }
1120
- if (_timestampProvider === void 0) {
1121
- _timestampProvider = dateTimestampProvider;
1122
- }
1123
- var _this = _super.call(this) || this;
1124
- _this._bufferSize = _bufferSize;
1125
- _this._windowTime = _windowTime;
1126
- _this._timestampProvider = _timestampProvider;
1127
- _this._buffer = [];
1128
- _this._infiniteTimeWindow = true;
1129
- _this._infiniteTimeWindow = _windowTime === Infinity;
1130
- _this._bufferSize = Math.max(1, _bufferSize);
1131
- _this._windowTime = Math.max(1, _windowTime);
1132
- return _this;
1133
- }
1134
- ReplaySubject2.prototype.next = function(value) {
1135
- var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime;
1136
- if (!isStopped) {
1137
- _buffer.push(value);
1138
- !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
1139
- }
1140
- this._trimBuffer();
1141
- _super.prototype.next.call(this, value);
1142
- };
1143
- ReplaySubject2.prototype._subscribe = function(subscriber) {
1144
- this._throwIfClosed();
1145
- this._trimBuffer();
1146
- var subscription = this._innerSubscribe(subscriber);
1147
- var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer;
1148
- var copy = _buffer.slice();
1149
- for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
1150
- subscriber.next(copy[i]);
1151
- }
1152
- this._checkFinalizedStatuses(subscriber);
1153
- return subscription;
1154
- };
1155
- ReplaySubject2.prototype._trimBuffer = function() {
1156
- var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow;
1157
- var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
1158
- _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
1159
- if (!_infiniteTimeWindow) {
1160
- var now = _timestampProvider.now();
1161
- var last = 0;
1162
- for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
1163
- last = i;
1164
- }
1165
- last && _buffer.splice(0, last + 1);
1166
- }
1167
- };
1168
- return ReplaySubject2;
1169
- })(Subject);
1170
- var DEFAULT_WEBSOCKET_CONFIG = {
1171
- url: "",
1172
- deserializer: function(e) {
1173
- return JSON.parse(e.data);
1174
- },
1175
- serializer: function(value) {
1176
- return JSON.stringify(value);
1177
- }
1178
- };
1179
- var WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT = "WebSocketSubject.error must be called with an object with an error code, and an optional reason: { code: number, reason: string }";
1180
- var WebSocketSubject = (function(_super) {
1181
- __extends(WebSocketSubject2, _super);
1182
- function WebSocketSubject2(urlConfigOrSource, destination) {
1183
- var _this = _super.call(this) || this;
1184
- _this._socket = null;
1185
- if (urlConfigOrSource instanceof Observable) {
1186
- _this.destination = destination;
1187
- _this.source = urlConfigOrSource;
1188
- } else {
1189
- var config2 = _this._config = __assign({}, DEFAULT_WEBSOCKET_CONFIG);
1190
- _this._output = new Subject();
1191
- if (typeof urlConfigOrSource === "string") {
1192
- config2.url = urlConfigOrSource;
1193
- } else {
1194
- for (var key in urlConfigOrSource) {
1195
- if (urlConfigOrSource.hasOwnProperty(key)) {
1196
- config2[key] = urlConfigOrSource[key];
1197
- }
1198
- }
1199
- }
1200
- if (!config2.WebSocketCtor && WebSocket) {
1201
- config2.WebSocketCtor = WebSocket;
1202
- } else if (!config2.WebSocketCtor) {
1203
- throw new Error("no WebSocket constructor can be found");
1204
- }
1205
- _this.destination = new ReplaySubject();
1206
- }
1207
- return _this;
1208
- }
1209
- WebSocketSubject2.prototype.lift = function(operator) {
1210
- var sock = new WebSocketSubject2(this._config, this.destination);
1211
- sock.operator = operator;
1212
- sock.source = this;
1213
- return sock;
1214
- };
1215
- WebSocketSubject2.prototype._resetState = function() {
1216
- this._socket = null;
1217
- if (!this.source) {
1218
- this.destination = new ReplaySubject();
1219
- }
1220
- this._output = new Subject();
1221
- };
1222
- WebSocketSubject2.prototype.multiplex = function(subMsg, unsubMsg, messageFilter) {
1223
- var self = this;
1224
- return new Observable(function(observer) {
1225
- try {
1226
- self.next(subMsg());
1227
- } catch (err) {
1228
- observer.error(err);
1229
- }
1230
- var subscription = self.subscribe({
1231
- next: function(x) {
1232
- try {
1233
- if (messageFilter(x)) {
1234
- observer.next(x);
1235
- }
1236
- } catch (err) {
1237
- observer.error(err);
1238
- }
1239
- },
1240
- error: function(err) {
1241
- return observer.error(err);
1242
- },
1243
- complete: function() {
1244
- return observer.complete();
1245
- }
1246
- });
1247
- return function() {
1248
- try {
1249
- self.next(unsubMsg());
1250
- } catch (err) {
1251
- observer.error(err);
1252
- }
1253
- subscription.unsubscribe();
1254
- };
1255
- });
1256
- };
1257
- WebSocketSubject2.prototype._connectSocket = function() {
1258
- var _this = this;
1259
- var _a = this._config, WebSocketCtor = _a.WebSocketCtor, protocol = _a.protocol, url = _a.url, binaryType = _a.binaryType;
1260
- var observer = this._output;
1261
- var socket = null;
1262
- try {
1263
- socket = protocol ? new WebSocketCtor(url, protocol) : new WebSocketCtor(url);
1264
- this._socket = socket;
1265
- if (binaryType) {
1266
- this._socket.binaryType = binaryType;
1267
- }
1268
- } catch (e) {
1269
- observer.error(e);
1270
- return;
1271
- }
1272
- var subscription = new Subscription(function() {
1273
- _this._socket = null;
1274
- if (socket && socket.readyState === 1) {
1275
- socket.close();
1276
- }
1277
- });
1278
- socket.onopen = function(evt) {
1279
- var _socket = _this._socket;
1280
- if (!_socket) {
1281
- socket.close();
1282
- _this._resetState();
1283
- return;
1284
- }
1285
- var openObserver = _this._config.openObserver;
1286
- if (openObserver) {
1287
- openObserver.next(evt);
1288
- }
1289
- var queue = _this.destination;
1290
- _this.destination = Subscriber.create(function(x) {
1291
- if (socket.readyState === 1) {
1292
- try {
1293
- var serializer = _this._config.serializer;
1294
- socket.send(serializer(x));
1295
- } catch (e) {
1296
- _this.destination.error(e);
1297
- }
1298
- }
1299
- }, function(err) {
1300
- var closingObserver = _this._config.closingObserver;
1301
- if (closingObserver) {
1302
- closingObserver.next(void 0);
1303
- }
1304
- if (err && err.code) {
1305
- socket.close(err.code, err.reason);
1306
- } else {
1307
- observer.error(new TypeError(WEBSOCKETSUBJECT_INVALID_ERROR_OBJECT));
1308
- }
1309
- _this._resetState();
1310
- }, function() {
1311
- var closingObserver = _this._config.closingObserver;
1312
- if (closingObserver) {
1313
- closingObserver.next(void 0);
1314
- }
1315
- socket.close();
1316
- _this._resetState();
1317
- });
1318
- if (queue && queue instanceof ReplaySubject) {
1319
- subscription.add(queue.subscribe(_this.destination));
1320
- }
1321
- };
1322
- socket.onerror = function(e) {
1323
- _this._resetState();
1324
- observer.error(e);
1325
- };
1326
- socket.onclose = function(e) {
1327
- if (socket === _this._socket) {
1328
- _this._resetState();
1329
- }
1330
- var closeObserver = _this._config.closeObserver;
1331
- if (closeObserver) {
1332
- closeObserver.next(e);
1333
- }
1334
- if (e.wasClean) {
1335
- observer.complete();
1336
- } else {
1337
- observer.error(e);
1338
- }
1339
- };
1340
- socket.onmessage = function(e) {
1341
- try {
1342
- var deserializer = _this._config.deserializer;
1343
- observer.next(deserializer(e));
1344
- } catch (err) {
1345
- observer.error(err);
1346
- }
1347
- };
1348
- };
1349
- WebSocketSubject2.prototype._subscribe = function(subscriber) {
1350
- var _this = this;
1351
- var source = this.source;
1352
- if (source) {
1353
- return source.subscribe(subscriber);
1354
- }
1355
- if (!this._socket) {
1356
- this._connectSocket();
1357
- }
1358
- this._output.subscribe(subscriber);
1359
- subscriber.add(function() {
1360
- var _socket = _this._socket;
1361
- if (_this._output.observers.length === 0) {
1362
- if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) {
1363
- _socket.close();
1364
- }
1365
- _this._resetState();
1366
- }
1367
- });
1368
- return subscriber;
1369
- };
1370
- WebSocketSubject2.prototype.unsubscribe = function() {
1371
- var _socket = this._socket;
1372
- if (_socket && (_socket.readyState === 1 || _socket.readyState === 0)) {
1373
- _socket.close();
1374
- }
1375
- this._resetState();
1376
- _super.prototype.unsubscribe.call(this);
1377
- };
1378
- return WebSocketSubject2;
1379
- })(AnonymousSubject);
1380
- function webSocket(urlConfigOrSource) {
1381
- return new WebSocketSubject(urlConfigOrSource);
1382
- }
1383
- class WebsocketService extends BaseConnectionService {
1384
- constructor(config2) {
1385
- super();
1386
- this.socket$ = null;
1387
- this.wsConfig = config2;
1388
- }
1389
- get serviceName() {
1390
- return "WS";
1391
- }
1392
- connect() {
1393
- if (this.socket$) {
1394
- return;
1395
- }
1396
- this.socket$ = webSocket({
1397
- url: this.wsConfig.url,
1398
- openObserver: {
1399
- next: () => {
1400
- console.log("[WS] Connected");
1401
- this.connectionStatusSubject$.next(true);
1402
- this.resetReconnectAttempts();
1403
- this.sendMessage("INIT_CONNECTION");
1404
- }
1405
- },
1406
- closeObserver: {
1407
- next: (event) => {
1408
- console.log("[WS] Closed:", event.code, event.reason);
1409
- this.connectionStatusSubject$.next(false);
1410
- this.socket$ = null;
1411
- if (event.code !== 1e3 && event.reason !== "Closing duplicate connection") {
1412
- this.scheduleReconnect(() => this.connect());
1413
- }
1414
- }
1415
- }
1416
- });
1417
- this.socket$.pipe(
1418
- takeUntil(this.destroySubject$),
1419
- tap({
1420
- error: (err) => {
1421
- console.error("[WS] Error:", err);
1422
- this.connectionStatusSubject$.next(false);
1423
- }
1424
- })
1425
- ).subscribe({
1426
- next: (message) => {
1427
- if (this.isIncomingMessage(message)) {
1428
- this.messagesSubject$.next(message);
1429
- }
1430
- },
1431
- error: (err) => console.error("[WS] Stream error:", err)
1432
- });
1433
- }
1434
- isIncomingMessage(msg) {
1435
- return "action" in msg && !("Authorization" in msg);
1436
- }
1437
- async sendMessage(action, payload) {
1438
- if (!this.socket$ || !this.connectionStatusSubject$.value) {
1439
- console.warn("[WS] Cannot send message - not connected");
1440
- return;
1441
- }
1442
- try {
1443
- if (!this.wsConfig.authProvider.isAuthenticated()) {
1444
- console.warn(`[WS] Cannot send message - not authenticated for action: ${action}`);
1445
- return;
1446
- }
1447
- const idToken = await this.wsConfig.authProvider.getIdToken();
1448
- if (!idToken) {
1449
- console.warn(`[WS] Cannot send message - no auth token available for action: ${action}`);
1450
- return;
1451
- }
1452
- this.socket$.next({
1453
- Authorization: idToken,
1454
- action,
1455
- payload
1456
- });
1457
- } catch (error) {
1458
- console.error("[WS] Error sending message:", error);
1459
- }
1460
- }
1461
- on(action) {
1462
- return this.messages$.pipe(
1463
- filter((msg) => msg.action === action),
1464
- map((msg) => msg.payload)
1465
- );
1466
- }
1467
- request(sendAction, responseAction, payload) {
1468
- return new Observable$1((subscriber) => {
1469
- const sub = this.on(responseAction).pipe(take(1)).subscribe(subscriber);
1470
- this.sendMessage(sendAction, payload);
1471
- return () => sub.unsubscribe();
1472
- });
1473
- }
1474
- disconnect() {
1475
- var _a;
1476
- (_a = this.socket$) == null ? void 0 : _a.complete();
1477
- this.socket$ = null;
1478
- this.connectionStatusSubject$.next(false);
1479
- this.resetReconnectAttempts();
1480
- }
1481
- destroy() {
1482
- var _a;
1483
- (_a = this.socket$) == null ? void 0 : _a.complete();
1484
- this.socket$ = null;
1485
- this.destroySubject$.next();
1486
- this.destroySubject$.complete();
1487
- this.messagesSubject$.complete();
1488
- this.connectionStatusSubject$.complete();
1489
- }
1490
- }
1491
111
  const LiveUpdateContext = createContext(null);
1492
112
  const useLiveUpdateContext = () => {
1493
113
  const context = useContext(LiveUpdateContext);
@@ -1629,691 +249,6 @@ const useLiveUpdates = (eventName) => {
1629
249
  }, [eventName, service]);
1630
250
  return { data, error };
1631
251
  };
1632
- class ContentModel {
1633
- constructor(doc) {
1634
- this.document = doc || this.createEmptyDocument();
1635
- }
1636
- /**
1637
- * Create empty document with single empty paragraph
1638
- */
1639
- static createEmpty() {
1640
- return {
1641
- type: "document",
1642
- version: "1.0",
1643
- children: [
1644
- {
1645
- type: "paragraph",
1646
- children: [{ type: "text", text: "" }]
1647
- }
1648
- ]
1649
- };
1650
- }
1651
- /**
1652
- * Get the current document
1653
- */
1654
- getDocument() {
1655
- return JSON.parse(JSON.stringify(this.document));
1656
- }
1657
- /**
1658
- * Replace entire document
1659
- */
1660
- setDocument(doc) {
1661
- this.document = JSON.parse(JSON.stringify(doc));
1662
- }
1663
- /**
1664
- * Get all text content as plain string
1665
- */
1666
- getPlainText() {
1667
- let text = "";
1668
- const traverse = (node) => {
1669
- if (node.type === "text") {
1670
- text += node.text;
1671
- } else if ("children" in node) {
1672
- node.children.forEach(traverse);
1673
- } else if (node.type === "image") {
1674
- text += "[Image]";
1675
- } else if (node.type === "mention") {
1676
- text += `@${node.label}`;
1677
- }
1678
- };
1679
- this.document.children.forEach(traverse);
1680
- return text;
1681
- }
1682
- /**
1683
- * Insert text at selection/cursor position
1684
- */
1685
- insertText(text, marks) {
1686
- const doc = this.cloneDocument();
1687
- const firstPara = this.getFirstParagraph(doc);
1688
- if (firstPara && firstPara.children.length > 0) {
1689
- const firstChild = firstPara.children[0];
1690
- if (firstChild.type === "text") {
1691
- firstChild.text += text;
1692
- if (marks) {
1693
- firstChild.marks = marks;
1694
- }
1695
- }
1696
- }
1697
- return doc;
1698
- }
1699
- /**
1700
- * Insert a paragraph at the end
1701
- */
1702
- insertParagraph(content) {
1703
- const doc = this.cloneDocument();
1704
- doc.children.push({
1705
- type: "paragraph",
1706
- children: content || [{ type: "text", text: "" }]
1707
- });
1708
- return doc;
1709
- }
1710
- /**
1711
- * Insert heading
1712
- */
1713
- insertHeading(level, content) {
1714
- const doc = this.cloneDocument();
1715
- doc.children.push({
1716
- type: "heading",
1717
- level,
1718
- children: content || [{ type: "text", text: "" }]
1719
- });
1720
- return doc;
1721
- }
1722
- /**
1723
- * Insert image
1724
- */
1725
- insertImage(url, attrs) {
1726
- const doc = this.cloneDocument();
1727
- const lastBlock = doc.children[doc.children.length - 1];
1728
- if ((attrs == null ? void 0 : attrs.display) === "block") {
1729
- doc.children.push({
1730
- type: "paragraph",
1731
- children: [
1732
- {
1733
- type: "image",
1734
- url,
1735
- attrs: attrs || {}
1736
- }
1737
- ]
1738
- });
1739
- } else {
1740
- if (lastBlock && lastBlock.type === "paragraph") {
1741
- lastBlock.children.push({
1742
- type: "image",
1743
- url,
1744
- attrs: attrs || {}
1745
- });
1746
- } else {
1747
- doc.children.push({
1748
- type: "paragraph",
1749
- children: [
1750
- {
1751
- type: "image",
1752
- url,
1753
- attrs: attrs || {}
1754
- }
1755
- ]
1756
- });
1757
- }
1758
- }
1759
- return doc;
1760
- }
1761
- /**
1762
- * Insert mention
1763
- */
1764
- insertMention(id, label, meta) {
1765
- const doc = this.cloneDocument();
1766
- const lastBlock = doc.children[doc.children.length - 1];
1767
- if (lastBlock && lastBlock.type === "paragraph") {
1768
- lastBlock.children.push({
1769
- type: "mention",
1770
- id,
1771
- label,
1772
- meta
1773
- });
1774
- }
1775
- return doc;
1776
- }
1777
- /**
1778
- * Insert list
1779
- */
1780
- insertList(listType, items = [[]]) {
1781
- const doc = this.cloneDocument();
1782
- const children = items.map((item) => ({
1783
- type: "list-item",
1784
- children: item || [{ type: "text", text: "" }],
1785
- depth: 0
1786
- }));
1787
- doc.children.push({
1788
- type: "list",
1789
- listType,
1790
- children
1791
- });
1792
- return doc;
1793
- }
1794
- /**
1795
- * Toggle a mark type on text in a range
1796
- */
1797
- toggleMark(mark, selection) {
1798
- var _a;
1799
- const doc = this.cloneDocument();
1800
- const firstPara = this.getFirstParagraph(doc);
1801
- if (firstPara && ((_a = firstPara.children[0]) == null ? void 0 : _a.type) === "text") {
1802
- const textNode = firstPara.children[0];
1803
- if (!textNode.marks) {
1804
- textNode.marks = [];
1805
- }
1806
- const existingMark = textNode.marks.findIndex((m) => m.type === mark);
1807
- if (existingMark >= 0) {
1808
- textNode.marks.splice(existingMark, 1);
1809
- } else {
1810
- textNode.marks.push({ type: mark });
1811
- }
1812
- }
1813
- return doc;
1814
- }
1815
- /**
1816
- * Check if a mark type is active at cursor
1817
- */
1818
- isMarkActive(mark) {
1819
- var _a, _b;
1820
- const firstPara = this.getFirstParagraph(this.document);
1821
- if (((_a = firstPara == null ? void 0 : firstPara.children[0]) == null ? void 0 : _a.type) === "text") {
1822
- const textNode = firstPara.children[0];
1823
- return ((_b = textNode.marks) == null ? void 0 : _b.some((m) => m.type === mark)) || false;
1824
- }
1825
- return false;
1826
- }
1827
- /**
1828
- * Get active marks at cursor
1829
- */
1830
- getActiveMarks() {
1831
- var _a, _b;
1832
- const firstPara = this.getFirstParagraph(this.document);
1833
- if (((_a = firstPara == null ? void 0 : firstPara.children[0]) == null ? void 0 : _a.type) === "text") {
1834
- const textNode = firstPara.children[0];
1835
- return ((_b = textNode.marks) == null ? void 0 : _b.map((m) => m.type)) || [];
1836
- }
1837
- return [];
1838
- }
1839
- /**
1840
- * Delete content (simplified - deletes last block)
1841
- */
1842
- deleteContent(selection) {
1843
- const doc = this.cloneDocument();
1844
- if (doc.children.length > 1) {
1845
- doc.children.pop();
1846
- } else if (doc.children.length === 1 && doc.children[0].type === "paragraph") {
1847
- doc.children[0].children = [{ type: "text", text: "" }];
1848
- }
1849
- return doc;
1850
- }
1851
- /**
1852
- * Replace entire content
1853
- */
1854
- replaceContent(nodes) {
1855
- const doc = this.cloneDocument();
1856
- doc.children = nodes;
1857
- return doc;
1858
- }
1859
- /**
1860
- * Clone document (deep copy)
1861
- */
1862
- cloneDocument() {
1863
- return JSON.parse(JSON.stringify(this.document));
1864
- }
1865
- /**
1866
- * Get first paragraph in document
1867
- */
1868
- getFirstParagraph(doc) {
1869
- for (const block of doc.children) {
1870
- if (block.type === "paragraph") {
1871
- return block;
1872
- }
1873
- }
1874
- return null;
1875
- }
1876
- /**
1877
- * Find node by predicate
1878
- */
1879
- findNode(predicate) {
1880
- const search = (node) => {
1881
- if (predicate(node)) {
1882
- return node;
1883
- }
1884
- if ("children" in node) {
1885
- for (const child of node.children) {
1886
- const result = search(child);
1887
- if (result) return result;
1888
- }
1889
- }
1890
- return null;
1891
- };
1892
- for (const child of this.document.children) {
1893
- const result = search(child);
1894
- if (result) return result;
1895
- }
1896
- return null;
1897
- }
1898
- /**
1899
- * Count all nodes of a type
1900
- */
1901
- countNodes(type) {
1902
- let count = 0;
1903
- const traverse = (node) => {
1904
- if (node.type === type) count++;
1905
- if ("children" in node) {
1906
- node.children.forEach(traverse);
1907
- }
1908
- };
1909
- this.document.children.forEach(traverse);
1910
- return count;
1911
- }
1912
- createEmptyDocument() {
1913
- return ContentModel.createEmpty();
1914
- }
1915
- }
1916
- class RichContentService {
1917
- constructor(config2 = {}) {
1918
- this.history = [];
1919
- this.historyIndex = -1;
1920
- this.adapter = null;
1921
- this.defaultImageHandler = async (file) => {
1922
- return new Promise((resolve) => {
1923
- const reader = new FileReader();
1924
- reader.onload = (e) => {
1925
- var _a;
1926
- resolve({ url: (_a = e.target) == null ? void 0 : _a.result });
1927
- };
1928
- reader.readAsDataURL(file);
1929
- });
1930
- };
1931
- this.config = {
1932
- initialContent: config2.initialContent || ContentModel.createEmpty(),
1933
- allowedMarks: config2.allowedMarks || [
1934
- "bold",
1935
- "italic",
1936
- "underline",
1937
- "strikethrough",
1938
- "code"
1939
- ],
1940
- allowedBlocks: config2.allowedBlocks || [
1941
- "document",
1942
- "paragraph",
1943
- "heading",
1944
- "list",
1945
- "blockquote",
1946
- "code-block",
1947
- "horizontal-rule"
1948
- ],
1949
- maxListDepth: config2.maxListDepth ?? 3,
1950
- imageUploadHandler: config2.imageUploadHandler || this.defaultImageHandler,
1951
- mentionProvider: config2.mentionProvider || (() => Promise.resolve([])),
1952
- middleware: config2.middleware || {},
1953
- enableHistory: config2.enableHistory ?? true,
1954
- maxHistorySteps: config2.maxHistorySteps ?? 100,
1955
- placeholder: config2.placeholder || "",
1956
- readOnly: config2.readOnly ?? false
1957
- };
1958
- this.middleware = this.config.middleware;
1959
- this.contentModel = new ContentModel(this.config.initialContent);
1960
- this.contentSubject = new BehaviorSubject(
1961
- this.contentModel.getDocument()
1962
- );
1963
- this.commandSubject = new Subject$1();
1964
- this.mentionSubject = new Subject$1();
1965
- this.stateSubject = new BehaviorSubject({
1966
- content: this.contentModel.getDocument(),
1967
- selection: null,
1968
- canUndo: false,
1969
- canRedo: false,
1970
- isFocused: false,
1971
- isDirty: false,
1972
- mentions: {
1973
- isActive: false,
1974
- query: "",
1975
- position: { x: 0, y: 0 }
1976
- },
1977
- selectedFormats: /* @__PURE__ */ new Set()
1978
- });
1979
- if (this.config.enableHistory) {
1980
- this.history.push({
1981
- content: this.contentModel.getDocument(),
1982
- timestamp: Date.now()
1983
- });
1984
- this.historyIndex = 0;
1985
- }
1986
- this.commandSubject.subscribe((cmd) => this.executeCommand(cmd));
1987
- }
1988
- /**
1989
- * Create service from empty state
1990
- */
1991
- static create(config2) {
1992
- return new RichContentService(config2);
1993
- }
1994
- // =========================================================================
1995
- // PUBLIC OBSERVABLES
1996
- // =========================================================================
1997
- /**
1998
- * Get content$ observable
1999
- */
2000
- getContent$() {
2001
- return this.contentSubject.asObservable();
2002
- }
2003
- /**
2004
- * Get full state$ observable
2005
- */
2006
- getState$() {
2007
- return this.stateSubject.asObservable();
2008
- }
2009
- /**
2010
- * Get canUndo$ observable
2011
- */
2012
- getCanUndo$() {
2013
- return this.stateSubject.pipe(
2014
- map((s) => s.canUndo),
2015
- distinctUntilChanged()
2016
- );
2017
- }
2018
- /**
2019
- * Get canRedo$ observable
2020
- */
2021
- getCanRedo$() {
2022
- return this.stateSubject.pipe(
2023
- map((s) => s.canRedo),
2024
- distinctUntilChanged()
2025
- );
2026
- }
2027
- /**
2028
- * Get isFocused$ observable
2029
- */
2030
- getIsFocused$() {
2031
- return this.stateSubject.pipe(
2032
- map((s) => s.isFocused),
2033
- distinctUntilChanged()
2034
- );
2035
- }
2036
- /**
2037
- * Get mentions$ observable - for autocomplete dropdown
2038
- */
2039
- getMentions$() {
2040
- return this.mentionSubject.asObservable();
2041
- }
2042
- /**
2043
- * Get selectedFormats$ observable
2044
- */
2045
- getSelectedFormats$() {
2046
- return this.stateSubject.pipe(
2047
- map((s) => s.selectedFormats || /* @__PURE__ */ new Set()),
2048
- distinctUntilChanged()
2049
- );
2050
- }
2051
- // =========================================================================
2052
- // STATE GETTERS
2053
- // =========================================================================
2054
- getContent() {
2055
- return this.contentSubject.getValue();
2056
- }
2057
- getState() {
2058
- return this.stateSubject.getValue();
2059
- }
2060
- getPlainText() {
2061
- return this.contentModel.getPlainText();
2062
- }
2063
- canUndo() {
2064
- return this.historyIndex > 0;
2065
- }
2066
- canRedo() {
2067
- return this.historyIndex < this.history.length - 1;
2068
- }
2069
- isFocused() {
2070
- return this.getState().isFocused;
2071
- }
2072
- // =========================================================================
2073
- // ADAPTER MANAGEMENT
2074
- // =========================================================================
2075
- /**
2076
- * Attach DOM adapter for contentEditable syncing
2077
- */
2078
- attachAdapter(adapter) {
2079
- this.adapter = adapter;
2080
- const docFromDom = adapter.syncFromDOM();
2081
- this.setContent(docFromDom);
2082
- }
2083
- /**
2084
- * Detach adapter
2085
- */
2086
- detachAdapter() {
2087
- if (this.adapter) {
2088
- this.adapter.unmount();
2089
- this.adapter = null;
2090
- }
2091
- }
2092
- /**
2093
- * Get attached adapter
2094
- */
2095
- getAdapter() {
2096
- return this.adapter;
2097
- }
2098
- // =========================================================================
2099
- // COMMAND EXECUTION
2100
- // =========================================================================
2101
- /**
2102
- * Execute a command
2103
- */
2104
- execute(command, payload) {
2105
- const cmd = typeof command === "string" ? { type: command, payload } : command;
2106
- this.commandSubject.next(cmd);
2107
- }
2108
- /**
2109
- * Execute text insertion
2110
- */
2111
- insertText(text, marks) {
2112
- this.execute("insertText", { text, marks });
2113
- }
2114
- /**
2115
- * Execute paragraph insertion
2116
- */
2117
- insertParagraph() {
2118
- this.execute("insertParagraph");
2119
- }
2120
- /**
2121
- * Execute heading insertion
2122
- */
2123
- insertHeading(level) {
2124
- this.execute("insertHeading", { level });
2125
- }
2126
- /**
2127
- * Execute image insertion
2128
- */
2129
- insertImage(url, attrs) {
2130
- this.execute("insertImage", { url, attrs });
2131
- }
2132
- /**
2133
- * Execute image upload
2134
- */
2135
- async uploadImage(file) {
2136
- try {
2137
- const result = await this.config.imageUploadHandler(file);
2138
- this.insertImage(result.url, result.attrs);
2139
- } catch (error) {
2140
- console.error("Image upload failed:", error);
2141
- throw error;
2142
- }
2143
- }
2144
- /**
2145
- * Execute mention insertion
2146
- */
2147
- insertMention(id, label, meta) {
2148
- this.execute("insertMention", { id, label, meta });
2149
- }
2150
- /**
2151
- * Execute list insertion
2152
- */
2153
- insertList(listType) {
2154
- this.execute("insertList", { listType });
2155
- }
2156
- /**
2157
- * Execute mark toggle (bold, italic, etc.)
2158
- */
2159
- toggleMark(mark) {
2160
- this.execute("toggleMark", { mark });
2161
- }
2162
- /**
2163
- * Delete content
2164
- */
2165
- deleteContent() {
2166
- this.execute("deleteContent");
2167
- }
2168
- /**
2169
- * Set focus state
2170
- */
2171
- setFocus(focused) {
2172
- const state = this.getState();
2173
- state.isFocused = focused;
2174
- this.stateSubject.next(state);
2175
- }
2176
- /**
2177
- * Set selection
2178
- */
2179
- setSelection(selection) {
2180
- const state = this.getState();
2181
- state.selection = selection;
2182
- this.stateSubject.next(state);
2183
- }
2184
- /**
2185
- * Set mention query (triggers autocomplete)
2186
- */
2187
- setMentionQuery(query, position) {
2188
- if (query.length > 0) {
2189
- this.mentionSubject.next({ query, position });
2190
- }
2191
- }
2192
- // =========================================================================
2193
- // HISTORY (UNDO/REDO)
2194
- // =========================================================================
2195
- /**
2196
- * Undo to previous state
2197
- */
2198
- undo() {
2199
- if (this.canUndo()) {
2200
- this.historyIndex--;
2201
- this.applyHistoryState();
2202
- }
2203
- }
2204
- /**
2205
- * Redo to next state
2206
- */
2207
- redo() {
2208
- if (this.canRedo()) {
2209
- this.historyIndex++;
2210
- this.applyHistoryState();
2211
- }
2212
- }
2213
- /**
2214
- * Clear history
2215
- */
2216
- clearHistory() {
2217
- this.history = [{ content: this.getContent(), timestamp: Date.now() }];
2218
- this.historyIndex = 0;
2219
- this.updateHistoryState();
2220
- }
2221
- // =========================================================================
2222
- // PRIVATE METHODS
2223
- // =========================================================================
2224
- executeCommand(cmd) {
2225
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
2226
- if (this.config.readOnly) {
2227
- console.warn("Editor is in read-only mode");
2228
- return;
2229
- }
2230
- this.getContent();
2231
- let newContent;
2232
- switch (cmd.type) {
2233
- case "insertText":
2234
- newContent = this.contentModel.insertText((_a = cmd.payload) == null ? void 0 : _a.text, (_b = cmd.payload) == null ? void 0 : _b.marks);
2235
- break;
2236
- case "insertParagraph":
2237
- newContent = this.contentModel.insertParagraph((_c = cmd.payload) == null ? void 0 : _c.children);
2238
- break;
2239
- case "insertHeading":
2240
- newContent = this.contentModel.insertHeading(
2241
- ((_d = cmd.payload) == null ? void 0 : _d.level) || 1,
2242
- (_e = cmd.payload) == null ? void 0 : _e.children
2243
- );
2244
- break;
2245
- case "insertImage":
2246
- newContent = this.contentModel.insertImage((_f = cmd.payload) == null ? void 0 : _f.url, (_g = cmd.payload) == null ? void 0 : _g.attrs);
2247
- break;
2248
- case "insertMention":
2249
- newContent = this.contentModel.insertMention(
2250
- (_h = cmd.payload) == null ? void 0 : _h.id,
2251
- (_i = cmd.payload) == null ? void 0 : _i.label,
2252
- (_j = cmd.payload) == null ? void 0 : _j.meta
2253
- );
2254
- break;
2255
- case "insertList":
2256
- newContent = this.contentModel.insertList((_k = cmd.payload) == null ? void 0 : _k.listType, (_l = cmd.payload) == null ? void 0 : _l.items);
2257
- break;
2258
- case "toggleMark":
2259
- newContent = this.contentModel.toggleMark((_m = cmd.payload) == null ? void 0 : _m.mark, (_n = cmd.payload) == null ? void 0 : _n.selection);
2260
- break;
2261
- case "deleteContent":
2262
- newContent = this.contentModel.deleteContent((_o = cmd.payload) == null ? void 0 : _o.selection);
2263
- break;
2264
- case "replaceContent":
2265
- newContent = this.contentModel.replaceContent((_p = cmd.payload) == null ? void 0 : _p.nodes);
2266
- break;
2267
- default:
2268
- console.warn(`Unknown command type: ${cmd.type}`);
2269
- return;
2270
- }
2271
- if (this.config.enableHistory) {
2272
- this.history = this.history.slice(0, this.historyIndex + 1);
2273
- this.history.push({
2274
- content: newContent,
2275
- timestamp: Date.now()
2276
- });
2277
- if (this.history.length > this.config.maxHistorySteps) {
2278
- this.history.shift();
2279
- } else {
2280
- this.historyIndex++;
2281
- }
2282
- }
2283
- this.setContent(newContent);
2284
- }
2285
- setContent(doc) {
2286
- this.contentModel.setDocument(doc);
2287
- this.contentSubject.next(doc);
2288
- const state = this.getState();
2289
- state.content = doc;
2290
- state.isDirty = true;
2291
- state.selectedFormats = new Set(this.contentModel.getActiveMarks());
2292
- this.stateSubject.next(state);
2293
- if (this.adapter) {
2294
- this.adapter.syncToDOM(doc);
2295
- }
2296
- this.updateHistoryState();
2297
- }
2298
- applyHistoryState() {
2299
- const entry = this.history[this.historyIndex];
2300
- this.contentModel.setDocument(entry.content);
2301
- this.contentSubject.next(entry.content);
2302
- const state = this.getState();
2303
- state.content = entry.content;
2304
- this.stateSubject.next(state);
2305
- if (this.adapter) {
2306
- this.adapter.syncToDOM(entry.content);
2307
- }
2308
- this.updateHistoryState();
2309
- }
2310
- updateHistoryState() {
2311
- const state = this.getState();
2312
- state.canUndo = this.canUndo();
2313
- state.canRedo = this.canRedo();
2314
- this.stateSubject.next(state);
2315
- }
2316
- }
2317
252
  function useRichContent(options = {}) {
2318
253
  const service = useMemo(() => RichContentService.create(options), []);
2319
254
  const [content, setContent] = useState(service.getContent());
@@ -2406,12 +341,12 @@ function useRichContent(options = {}) {
2406
341
  };
2407
342
  }
2408
343
  function useTableService(options) {
2409
- const { config: config2, data } = options;
344
+ const { config, data } = options;
2410
345
  const builder = useMemo(() => {
2411
- const tb = new TableBuilder(config2);
346
+ const tb = new TableBuilder(config);
2412
347
  tb.setData(data);
2413
348
  return tb;
2414
- }, [config2]);
349
+ }, [config]);
2415
350
  const [state, setState] = useState(() => builder.getState());
2416
351
  const [selectedRows, setSelectedRows] = useState([]);
2417
352
  const [allSelected, setAllSelected] = useState(false);
@@ -2488,216 +423,9 @@ function useTableService(options) {
2488
423
  }), [state, selectedRows, allSelected, memoizedMethods]);
2489
424
  return memoizedReturn;
2490
425
  }
2491
- class TabsService {
2492
- constructor(config2) {
2493
- this.config = config2;
2494
- this.urlParam = config2.urlParam || "tab";
2495
- this.tabsSubject = new BehaviorSubject(config2.tabs);
2496
- const initialTabId = this.getInitialTabId();
2497
- this.activeTabSubject = new BehaviorSubject(initialTabId);
2498
- this.tabChangeSubject = new BehaviorSubject(null);
2499
- if (this.config.enableUrlRouting) {
2500
- this.setupUrlRouting();
2501
- }
2502
- }
2503
- /**
2504
- * Get initial tab ID from URL or config
2505
- */
2506
- getInitialTabId() {
2507
- var _a;
2508
- if (this.config.enableUrlRouting && typeof window !== "undefined") {
2509
- const params = new URLSearchParams(window.location.search);
2510
- const urlTabId = params.get(this.urlParam);
2511
- if (urlTabId && this.config.tabs.some((t) => t.id === urlTabId)) {
2512
- return urlTabId;
2513
- }
2514
- }
2515
- return this.config.defaultTabId || ((_a = this.config.tabs[0]) == null ? void 0 : _a.id) || "";
2516
- }
2517
- /**
2518
- * Setup URL routing listener
2519
- */
2520
- setupUrlRouting() {
2521
- if (typeof window === "undefined") return;
2522
- const handleUrlChange = () => {
2523
- const params = new URLSearchParams(window.location.search);
2524
- const urlTabId = params.get(this.urlParam);
2525
- if (urlTabId && urlTabId !== this.activeTabSubject.value) {
2526
- this.setActiveTab(urlTabId);
2527
- }
2528
- };
2529
- window.addEventListener("popstate", handleUrlChange);
2530
- }
2531
- /**
2532
- * Update URL with current active tab
2533
- */
2534
- updateUrl(tabId) {
2535
- if (!this.config.enableUrlRouting || typeof window === "undefined") return;
2536
- const params = new URLSearchParams(window.location.search);
2537
- params.set(this.urlParam, tabId);
2538
- const newUrl = `${window.location.pathname}?${params.toString()}`;
2539
- window.history.pushState({ tab: tabId }, "", newUrl);
2540
- }
2541
- /**
2542
- * Set active tab by ID
2543
- */
2544
- setActiveTab(tabId) {
2545
- const tab = this.config.tabs.find((t) => t.id === tabId);
2546
- if (!tab || tab.disabled) return;
2547
- const previousTabId = this.activeTabSubject.value;
2548
- this.activeTabSubject.next(tabId);
2549
- if (this.config.enableUrlRouting) {
2550
- this.updateUrl(tabId);
2551
- }
2552
- this.tabChangeSubject.next({
2553
- previousTabId,
2554
- currentTabId: tabId,
2555
- tab
2556
- });
2557
- }
2558
- /**
2559
- * Set active tab by index
2560
- */
2561
- setActiveTabByIndex(index) {
2562
- const tab = this.config.tabs[index];
2563
- if (tab) {
2564
- this.setActiveTab(tab.id);
2565
- }
2566
- }
2567
- /**
2568
- * Get active tab ID
2569
- */
2570
- getActiveTabId() {
2571
- return this.activeTabSubject.value;
2572
- }
2573
- /**
2574
- * Get active tab
2575
- */
2576
- getActiveTab() {
2577
- return this.config.tabs.find((t) => t.id === this.activeTabSubject.value);
2578
- }
2579
- /**
2580
- * Get active tab index
2581
- */
2582
- getActiveTabIndex() {
2583
- return this.config.tabs.findIndex((t) => t.id === this.activeTabSubject.value);
2584
- }
2585
- /**
2586
- * Get all tabs
2587
- */
2588
- getTabs() {
2589
- return this.tabsSubject.value;
2590
- }
2591
- /**
2592
- * Observable of active tab ID
2593
- */
2594
- getActiveTabId$() {
2595
- return this.activeTabSubject.asObservable().pipe(distinctUntilChanged());
2596
- }
2597
- /**
2598
- * Observable of active tab
2599
- */
2600
- getActiveTab$() {
2601
- return this.activeTabSubject.asObservable().pipe(
2602
- distinctUntilChanged(),
2603
- map((tabId) => this.config.tabs.find((t) => t.id === tabId))
2604
- );
2605
- }
2606
- /**
2607
- * Observable of tab change events
2608
- */
2609
- onTabChange$() {
2610
- return this.tabChangeSubject.asObservable();
2611
- }
2612
- /**
2613
- * Observable of all tabs
2614
- */
2615
- getTabs$() {
2616
- return this.tabsSubject.asObservable().pipe(distinctUntilChanged());
2617
- }
2618
- /**
2619
- * Update tabs
2620
- */
2621
- updateTabs(tabs) {
2622
- var _a;
2623
- this.config.tabs = tabs;
2624
- this.tabsSubject.next(tabs);
2625
- if (!tabs.find((t) => t.id === this.activeTabSubject.value)) {
2626
- const newActiveTabId = ((_a = tabs[0]) == null ? void 0 : _a.id) || "";
2627
- this.setActiveTab(newActiveTabId);
2628
- }
2629
- }
2630
- /**
2631
- * Add a tab
2632
- */
2633
- addTab(tab, index) {
2634
- const tabs = [...this.config.tabs];
2635
- if (index !== void 0) {
2636
- tabs.splice(index, 0, tab);
2637
- } else {
2638
- tabs.push(tab);
2639
- }
2640
- this.updateTabs(tabs);
2641
- }
2642
- /**
2643
- * Remove a tab
2644
- */
2645
- removeTab(tabId) {
2646
- const tabs = this.config.tabs.filter((t) => t.id !== tabId);
2647
- this.updateTabs(tabs);
2648
- }
2649
- /**
2650
- * Enable/disable a tab
2651
- */
2652
- setTabDisabled(tabId, disabled) {
2653
- const tabs = this.config.tabs.map(
2654
- (t) => t.id === tabId ? { ...t, disabled } : t
2655
- );
2656
- this.updateTabs(tabs);
2657
- if (disabled && this.activeTabSubject.value === tabId) {
2658
- const enabledTab = tabs.find((t) => !t.disabled);
2659
- if (enabledTab) {
2660
- this.setActiveTab(enabledTab.id);
2661
- }
2662
- }
2663
- }
2664
- /**
2665
- * Update tab badge
2666
- */
2667
- setTabBadge(tabId, badge) {
2668
- const tabs = this.config.tabs.map(
2669
- (t) => t.id === tabId ? { ...t, badge } : t
2670
- );
2671
- this.updateTabs(tabs);
2672
- }
2673
- /**
2674
- * Move to next tab
2675
- */
2676
- nextTab() {
2677
- const currentIndex = this.getActiveTabIndex();
2678
- const nextIndex = (currentIndex + 1) % this.config.tabs.length;
2679
- this.setActiveTabByIndex(nextIndex);
2680
- }
2681
- /**
2682
- * Move to previous tab
2683
- */
2684
- previousTab() {
2685
- const currentIndex = this.getActiveTabIndex();
2686
- const prevIndex = currentIndex === 0 ? this.config.tabs.length - 1 : currentIndex - 1;
2687
- this.setActiveTabByIndex(prevIndex);
2688
- }
2689
- /**
2690
- * Destroy service and cleanup
2691
- */
2692
- destroy() {
2693
- this.activeTabSubject.complete();
2694
- this.tabsSubject.complete();
2695
- this.tabChangeSubject.complete();
2696
- }
2697
- }
2698
426
  const TabsContext = createContext(void 0);
2699
- function TabsProvider({ config: config2, children }) {
2700
- const [service] = useState(() => new TabsService(config2));
427
+ function TabsProvider({ config, children }) {
428
+ const [service] = useState(() => new TabsService(config));
2701
429
  const [activeTabId, setActiveTabId] = useState(() => service.getActiveTabId());
2702
430
  const [tabs, setTabs] = useState(() => service.getTabs());
2703
431
  useEffect(() => {