@weldsuite/helpdesk-widget-sdk 1.0.15 → 1.0.17

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.
@@ -35,32 +35,6 @@ const DEFAULT_CONFIG = {
35
35
  closeOnClick: true,
36
36
  },
37
37
  },
38
- customization: {
39
- primaryColor: '#000000',
40
- accentColor: '#3b82f6',
41
- backgroundColor: '#ffffff',
42
- textColor: '#111827',
43
- fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
44
- fontSize: '14px',
45
- borderRadius: '12px',
46
- },
47
- features: {
48
- attachments: true,
49
- reactions: true,
50
- typing: true,
51
- readReceipts: true,
52
- offlineMode: false,
53
- fileUpload: true,
54
- imageUpload: true,
55
- voiceMessages: false,
56
- videoMessages: false,
57
- },
58
- mobile: {
59
- fullScreen: true,
60
- scrollLock: true,
61
- keyboardHandling: 'auto',
62
- safeAreaInsets: true,
63
- },
64
38
  auth: {
65
39
  enabled: true,
66
40
  mode: 'anonymous',
@@ -104,6 +78,7 @@ function resolveConfig(config) {
104
78
  validateConfig(config);
105
79
  return {
106
80
  widgetId: config.widgetId,
81
+ testMode: config.testMode,
107
82
  api: {
108
83
  ...DEFAULT_CONFIG.api,
109
84
  widgetId: config.widgetId,
@@ -133,18 +108,6 @@ function resolveConfig(config) {
133
108
  ...config.iframes?.backdrop,
134
109
  },
135
110
  },
136
- customization: {
137
- ...DEFAULT_CONFIG.customization,
138
- ...config.customization,
139
- },
140
- features: {
141
- ...DEFAULT_CONFIG.features,
142
- ...config.features,
143
- },
144
- mobile: {
145
- ...DEFAULT_CONFIG.mobile,
146
- ...config.mobile,
147
- },
148
111
  auth: {
149
112
  ...DEFAULT_CONFIG.auth,
150
113
  ...config.auth,
@@ -387,6 +350,8 @@ class IframeManager {
387
350
  this.modalContainer = null;
388
351
  this.styleElement = null;
389
352
  this.messageBroker = null;
353
+ // Guard flag to prevent double-binding event listeners
354
+ this.eventListenersBound = false;
390
355
  this.config = config;
391
356
  this.logger = new Logger(config.logging);
392
357
  this.deviceInfo = detectDevice();
@@ -426,18 +391,27 @@ class IframeManager {
426
391
  }
427
392
  /**
428
393
  * Create root container structure
394
+ * Reuses existing container if it has the same widgetId (singleton behavior)
429
395
  */
430
396
  createRootContainer() {
431
- // Check if already exists
432
- let existingContainer = document.getElementById('weld-container');
397
+ const existingContainer = document.getElementById('weld-container');
433
398
  if (existingContainer) {
434
- this.logger.warn('Weld container already exists, removing old instance');
399
+ // Reuse if same widgetId
400
+ if (existingContainer.getAttribute('data-widget-id') === this.config.widgetId) {
401
+ this.logger.debug('Reusing existing root container');
402
+ this.rootContainer = existingContainer;
403
+ this.appContainer = existingContainer.querySelector('.weld-app');
404
+ this.modalContainer = document.getElementById('weld-modal-container');
405
+ return;
406
+ }
407
+ this.logger.warn('Weld container already exists with different widgetId, removing old instance');
435
408
  existingContainer.remove();
436
409
  }
437
410
  // Create root container
438
411
  this.rootContainer = document.createElement('div');
439
412
  this.rootContainer.id = 'weld-container';
440
413
  this.rootContainer.className = 'weld-namespace';
414
+ this.rootContainer.setAttribute('data-widget-id', this.config.widgetId);
441
415
  // Create app container
442
416
  this.appContainer = document.createElement('div');
443
417
  this.appContainer.className = 'weld-app';
@@ -472,17 +446,7 @@ class IframeManager {
472
446
  * Generate CSS for containers
473
447
  */
474
448
  generateCSS() {
475
- const { customization } = this.config;
476
449
  return `
477
- /* Weld Container */
478
- #weld-container {
479
- --weld-color-primary: ${customization.primaryColor};
480
- --weld-color-accent: ${customization.accentColor};
481
- --weld-font-family: ${customization.fontFamily};
482
- --weld-font-size-base: ${customization.fontSize};
483
- --weld-radius-xl: ${customization.borderRadius};
484
- }
485
-
486
450
  /* Import main stylesheet */
487
451
  @import url('/styles/index.css');
488
452
 
@@ -506,20 +470,27 @@ class IframeManager {
506
470
  * Create launcher iframe
507
471
  */
508
472
  async createLauncherIframe() {
473
+ // Guard: skip if launcher iframe already exists
474
+ if (this.iframes.has(IframeType.LAUNCHER)) {
475
+ this.logger.debug('Launcher iframe already exists, skipping creation');
476
+ return;
477
+ }
509
478
  const { iframes } = this.config;
510
479
  const { launcher } = iframes;
511
480
  // Create container
512
481
  const container = document.createElement('div');
513
482
  container.className = 'weld-launcher-frame';
514
483
  container.setAttribute('data-state', 'visible');
484
+ // Container is larger than the button to allow hover animations (scale, shadow) without clipping
485
+ const launcherPadding = 10;
515
486
  container.style.cssText = `
516
487
  position: fixed;
517
- bottom: ${launcher.position.bottom};
518
- right: ${launcher.position.right};
519
- width: ${launcher.size};
520
- height: ${launcher.size};
488
+ bottom: calc(${launcher.position.bottom} - ${launcherPadding}px);
489
+ right: calc(${launcher.position.right} - ${launcherPadding}px);
490
+ width: calc(${launcher.size} + ${launcherPadding * 2}px);
491
+ height: calc(${launcher.size} + ${launcherPadding * 2}px);
521
492
  z-index: 2147483003;
522
- pointer-events: auto;
493
+ pointer-events: none;
523
494
  display: block;
524
495
  `;
525
496
  // Create iframe
@@ -531,8 +502,12 @@ class IframeManager {
531
502
  width: 100%;
532
503
  height: 100%;
533
504
  border: none;
534
- background: transparent;
505
+ background: none;
506
+ color-scheme: none;
535
507
  display: block;
508
+ pointer-events: auto;
509
+ border-radius: 50%;
510
+ filter: drop-shadow(rgba(9, 14, 21, 0.54) 0px 1px 6px) drop-shadow(rgba(9, 14, 21, 0.9) 0px 2px 32px);
536
511
  `;
537
512
  iframe.setAttribute('allow', 'clipboard-write');
538
513
  iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups');
@@ -548,20 +523,36 @@ class IframeManager {
548
523
  createdAt: Date.now(),
549
524
  });
550
525
  // When DOM loads, notify MessageBroker to send weld:init
526
+ let launcherRetried = false;
551
527
  iframe.onload = () => {
552
528
  const metadata = this.iframes.get(IframeType.LAUNCHER);
553
529
  if (metadata) {
554
530
  this.logger.debug('Launcher iframe DOM loaded');
555
- // Notify MessageBroker that DOM is loaded (triggers weld:init)
556
531
  this.messageBroker?.setIframeDomLoaded(IframeType.LAUNCHER);
557
532
  }
558
533
  };
534
+ iframe.onerror = () => {
535
+ this.logger.error('Launcher iframe failed to load');
536
+ if (!launcherRetried) {
537
+ launcherRetried = true;
538
+ this.logger.info('Retrying launcher iframe load...');
539
+ setTimeout(() => { iframe.src = this.buildIframeUrl(launcher.url); }, 3000);
540
+ }
541
+ else {
542
+ this.config.onError?.(new Error('Failed to load widget launcher'));
543
+ }
544
+ };
559
545
  this.logger.debug('Launcher iframe created');
560
546
  }
561
547
  /**
562
548
  * Create widget iframe
563
549
  */
564
550
  async createWidgetIframe() {
551
+ // Guard: skip if widget iframe already exists
552
+ if (this.iframes.has(IframeType.WIDGET)) {
553
+ this.logger.debug('Widget iframe already exists, skipping creation');
554
+ return;
555
+ }
565
556
  const { iframes } = this.config;
566
557
  const { widget } = iframes;
567
558
  // Create container
@@ -642,54 +633,32 @@ class IframeManager {
642
633
  createdAt: Date.now(),
643
634
  });
644
635
  // When DOM loads, notify MessageBroker to send weld:init
636
+ let widgetRetried = false;
645
637
  iframe.onload = () => {
646
638
  const metadata = this.iframes.get(IframeType.WIDGET);
647
639
  if (metadata) {
648
640
  this.logger.debug('Widget iframe DOM loaded');
649
- // Notify MessageBroker that DOM is loaded (triggers weld:init)
650
641
  this.messageBroker?.setIframeDomLoaded(IframeType.WIDGET);
651
642
  }
652
643
  };
644
+ iframe.onerror = () => {
645
+ this.logger.error('Widget iframe failed to load');
646
+ if (!widgetRetried) {
647
+ widgetRetried = true;
648
+ this.logger.info('Retrying widget iframe load...');
649
+ setTimeout(() => { iframe.src = this.buildIframeUrl(widget.url); }, 3000);
650
+ }
651
+ else {
652
+ this.config.onError?.(new Error('Failed to load widget'));
653
+ }
654
+ };
653
655
  this.logger.debug('Widget iframe created');
654
656
  }
655
657
  /**
656
- * Create backdrop iframe
658
+ * Create backdrop iframe — disabled, widget stays non-modal so users can interact with the page
657
659
  */
658
660
  async createBackdropIframe() {
659
- if (!this.config.iframes.backdrop?.enabled) {
660
- this.logger.debug('Backdrop disabled, skipping creation');
661
- return;
662
- }
663
- // Create container
664
- const container = document.createElement('div');
665
- container.className = 'weld-backdrop-frame';
666
- container.setAttribute('data-state', 'hidden');
667
- container.style.cssText = `
668
- position: fixed;
669
- top: 0;
670
- left: 0;
671
- right: 0;
672
- bottom: 0;
673
- z-index: 2147483000;
674
- background: transparent;
675
- pointer-events: none;
676
- opacity: 0;
677
- transition: opacity 200ms ease;
678
- `;
679
- this.appContainer?.appendChild(container);
680
- // Store metadata (backdrop doesn't have an iframe, just a div)
681
- // We'll create a minimal "iframe" reference for consistency
682
- const dummyIframe = document.createElement('iframe');
683
- dummyIframe.style.display = 'none';
684
- this.iframes.set(IframeType.BACKDROP, {
685
- type: IframeType.BACKDROP,
686
- element: dummyIframe,
687
- container,
688
- ready: true, // Backdrop is always ready
689
- visible: false,
690
- createdAt: Date.now(),
691
- });
692
- this.logger.debug('Backdrop created');
661
+ this.logger.debug('Backdrop disabled, skipping creation');
693
662
  }
694
663
  /**
695
664
  * Build iframe URL with parameters
@@ -703,12 +672,21 @@ class IframeManager {
703
672
  url.searchParams.set('device', this.deviceInfo.type);
704
673
  url.searchParams.set('mobile', String(this.deviceInfo.isMobile));
705
674
  url.searchParams.set('parentOrigin', window.location.origin);
675
+ if (this.config.testMode) {
676
+ url.searchParams.set('testMode', 'true');
677
+ }
706
678
  return url.toString();
707
679
  }
708
680
  /**
709
681
  * Setup event listeners
710
682
  */
711
683
  setupEventListeners() {
684
+ // Guard: prevent double-binding
685
+ if (this.eventListenersBound) {
686
+ this.logger.debug('Event listeners already bound, skipping');
687
+ return;
688
+ }
689
+ this.eventListenersBound = true;
712
690
  // Window resize - use bound handler for proper cleanup
713
691
  window.addEventListener('resize', this.boundHandleResize);
714
692
  // Orientation change - use bound handler for proper cleanup
@@ -811,7 +789,7 @@ class IframeManager {
811
789
  iframe.container.style.transform = 'scale(1) translateY(0)';
812
790
  }
813
791
  // Handle mobile scroll lock
814
- if (this.deviceInfo.isMobile && type === IframeType.WIDGET && this.config.mobile.scrollLock) {
792
+ if (this.deviceInfo.isMobile && type === IframeType.WIDGET) {
815
793
  document.body.classList.add('weld-mobile-open');
816
794
  }
817
795
  // Hide launcher on mobile when widget is open (full-screen mode)
@@ -910,6 +888,8 @@ class IframeManager {
910
888
  this.iframes.clear();
911
889
  // Clear messageBroker reference
912
890
  this.messageBroker = null;
891
+ // Reset guard flag
892
+ this.eventListenersBound = false;
913
893
  this.logger.info('IframeManager destroyed');
914
894
  }
915
895
  }
@@ -977,6 +957,8 @@ var MessageType;
977
957
  // Events
978
958
  MessageType["EVENT_TRACK"] = "weld:event:track";
979
959
  MessageType["ERROR_REPORT"] = "weld:error:report";
960
+ // Page tracking
961
+ MessageType["PAGE_CHANGE"] = "weld:page:change";
980
962
  // API responses
981
963
  MessageType["API_SUCCESS"] = "weld:api:success";
982
964
  MessageType["API_ERROR"] = "weld:api:error";
@@ -1516,8 +1498,6 @@ class MessageBroker {
1516
1498
  iframeType,
1517
1499
  config: {
1518
1500
  api: this.config.api,
1519
- customization: this.config.customization,
1520
- features: this.config.features,
1521
1501
  },
1522
1502
  };
1523
1503
  const message = createMessage('weld:init', MessageOrigin.PARENT, initPayload);
@@ -2190,7 +2170,7 @@ class StateCoordinator {
2190
2170
  }
2191
2171
  }
2192
2172
 
2193
- var version = "1.0.15";
2173
+ var version = "1.0.17";
2194
2174
  var packageJson = {
2195
2175
  version: version};
2196
2176
 
@@ -2198,6 +2178,16 @@ var packageJson = {
2198
2178
  * Weld SDK - Main Entry Point
2199
2179
  * Public API for the Weld helpdesk widget
2200
2180
  */
2181
+ /**
2182
+ * Module-level singleton registry keyed by widgetId
2183
+ */
2184
+ const sdkRegistry = new Map();
2185
+ /**
2186
+ * SessionStorage key helpers
2187
+ */
2188
+ function openStateKey(widgetId) {
2189
+ return `weld-widget-open-${widgetId}`;
2190
+ }
2201
2191
  /**
2202
2192
  * SDK initialization status
2203
2193
  */
@@ -2220,6 +2210,8 @@ class WeldSDK {
2220
2210
  this.readyResolve = null;
2221
2211
  // Subscription IDs for cleanup
2222
2212
  this.subscriptionIds = [];
2213
+ // Page tracking cleanup
2214
+ this.pageTrackingCleanup = null;
2223
2215
  /**
2224
2216
  * Update user attributes (Intercom-style, with rate limiting)
2225
2217
  * Limited to 20 calls per page load to prevent abuse
@@ -2258,6 +2250,13 @@ class WeldSDK {
2258
2250
  console.log('[Weld SDK] Received message:', event.data.type);
2259
2251
  }
2260
2252
  if (event.data?.type === 'launcher:clicked') {
2253
+ if (this.status !== SDKStatus.READY) {
2254
+ console.log('[Weld SDK] Launcher clicked but SDK not ready yet — waiting...');
2255
+ this.readyPromise?.then(() => {
2256
+ this.handleLauncherClickMessage(event);
2257
+ });
2258
+ return;
2259
+ }
2261
2260
  // Toggle behavior - if widget is open, close it; if closed, open it
2262
2261
  const state = this.stateCoordinator.getState();
2263
2262
  if (state.widget.isOpen) {
@@ -2270,9 +2269,260 @@ class WeldSDK {
2270
2269
  }
2271
2270
  }
2272
2271
  if (event.data?.type === 'weld:close') {
2272
+ if (this.status !== SDKStatus.READY)
2273
+ return;
2273
2274
  console.log('[Weld SDK] Widget close requested');
2274
2275
  this.close();
2275
2276
  }
2277
+ if (event.data?.type === 'weld:unread-count') {
2278
+ const count = event.data.count ?? 0;
2279
+ // Forward to launcher iframe
2280
+ const launcherIframe = this.iframeManager.getIframe(IframeType.LAUNCHER);
2281
+ if (launcherIframe?.element?.contentWindow) {
2282
+ launcherIframe.element.contentWindow.postMessage({
2283
+ type: 'weld:unread-count',
2284
+ count
2285
+ }, '*');
2286
+ }
2287
+ // Update state coordinator for external API consumers
2288
+ this.stateCoordinator.setBadgeCount(count);
2289
+ }
2290
+ if (event.data?.type === 'weld:image:open' && event.data?.url) {
2291
+ this.showImageLightbox(event.data.url);
2292
+ }
2293
+ }
2294
+ /**
2295
+ * Show fullscreen image lightbox on the parent page
2296
+ */
2297
+ showImageLightbox(url) {
2298
+ // Remove existing lightbox if any
2299
+ const existing = document.getElementById('weld-image-lightbox');
2300
+ if (existing)
2301
+ existing.remove();
2302
+ // Zoom / pan state
2303
+ let scale = 1;
2304
+ let translateX = 0;
2305
+ let translateY = 0;
2306
+ let isDragging = false;
2307
+ let dragStartX = 0;
2308
+ let dragStartY = 0;
2309
+ let lastTranslateX = 0;
2310
+ let lastTranslateY = 0;
2311
+ const applyTransform = () => {
2312
+ img.style.transform = `translate(${translateX}px, ${translateY}px) scale(${scale})`;
2313
+ };
2314
+ const resetTransform = () => {
2315
+ scale = 1;
2316
+ translateX = 0;
2317
+ translateY = 0;
2318
+ applyTransform();
2319
+ img.style.cursor = 'zoom-in';
2320
+ };
2321
+ const overlay = document.createElement('div');
2322
+ overlay.id = 'weld-image-lightbox';
2323
+ overlay.style.cssText = `
2324
+ position: fixed;
2325
+ inset: 0;
2326
+ z-index: 2147483647;
2327
+ background: rgba(0, 0, 0, 0.92);
2328
+ display: flex;
2329
+ align-items: center;
2330
+ justify-content: center;
2331
+ padding: 16px;
2332
+ cursor: pointer;
2333
+ overflow: hidden;
2334
+ `;
2335
+ // Close button
2336
+ const closeBtn = document.createElement('button');
2337
+ closeBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`;
2338
+ closeBtn.style.cssText = `
2339
+ position: absolute;
2340
+ top: 16px;
2341
+ right: 16px;
2342
+ width: 40px;
2343
+ height: 40px;
2344
+ border-radius: 50%;
2345
+ border: none;
2346
+ background: rgba(255, 255, 255, 0.1);
2347
+ color: white;
2348
+ cursor: pointer;
2349
+ display: flex;
2350
+ align-items: center;
2351
+ justify-content: center;
2352
+ transition: background 0.15s;
2353
+ `;
2354
+ closeBtn.onmouseenter = () => { closeBtn.style.background = 'rgba(255, 255, 255, 0.2)'; };
2355
+ closeBtn.onmouseleave = () => { closeBtn.style.background = 'rgba(255, 255, 255, 0.1)'; };
2356
+ // Download button
2357
+ const downloadBtn = document.createElement('a');
2358
+ downloadBtn.href = url;
2359
+ downloadBtn.download = '';
2360
+ downloadBtn.target = '_blank';
2361
+ downloadBtn.rel = 'noopener noreferrer';
2362
+ downloadBtn.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" y1="15" x2="12" y2="3"></line></svg>`;
2363
+ downloadBtn.style.cssText = `
2364
+ position: absolute;
2365
+ top: 16px;
2366
+ right: 64px;
2367
+ width: 40px;
2368
+ height: 40px;
2369
+ border-radius: 50%;
2370
+ border: none;
2371
+ background: rgba(255, 255, 255, 0.1);
2372
+ color: white;
2373
+ cursor: pointer;
2374
+ display: flex;
2375
+ align-items: center;
2376
+ justify-content: center;
2377
+ transition: background 0.15s;
2378
+ text-decoration: none;
2379
+ `;
2380
+ downloadBtn.onmouseenter = () => { downloadBtn.style.background = 'rgba(255, 255, 255, 0.2)'; };
2381
+ downloadBtn.onmouseleave = () => { downloadBtn.style.background = 'rgba(255, 255, 255, 0.1)'; };
2382
+ // Image
2383
+ const img = document.createElement('img');
2384
+ img.src = url;
2385
+ img.alt = 'Full size';
2386
+ img.draggable = false;
2387
+ img.style.cssText = `
2388
+ max-width: 100%;
2389
+ max-height: 100%;
2390
+ object-fit: contain;
2391
+ border-radius: 8px;
2392
+ cursor: zoom-in;
2393
+ transition: transform 0.2s ease;
2394
+ user-select: none;
2395
+ `;
2396
+ // Click to toggle zoom
2397
+ img.addEventListener('click', (e) => {
2398
+ e.stopPropagation();
2399
+ if (scale === 1) {
2400
+ // Zoom in to 2.5x centered on click position
2401
+ const rect = img.getBoundingClientRect();
2402
+ const clickX = e.clientX - rect.left - rect.width / 2;
2403
+ const clickY = e.clientY - rect.top - rect.height / 2;
2404
+ scale = 2.5;
2405
+ translateX = -clickX * 1.5;
2406
+ translateY = -clickY * 1.5;
2407
+ applyTransform();
2408
+ img.style.cursor = 'zoom-out';
2409
+ }
2410
+ else {
2411
+ // Zoom out - reset
2412
+ resetTransform();
2413
+ }
2414
+ });
2415
+ // Mouse wheel zoom
2416
+ overlay.addEventListener('wheel', (e) => {
2417
+ e.preventDefault();
2418
+ const delta = e.deltaY > 0 ? -0.25 : 0.25;
2419
+ const newScale = Math.min(Math.max(scale + delta, 1), 5);
2420
+ if (newScale === 1) {
2421
+ resetTransform();
2422
+ }
2423
+ else {
2424
+ scale = newScale;
2425
+ applyTransform();
2426
+ img.style.cursor = 'zoom-out';
2427
+ }
2428
+ }, { passive: false });
2429
+ // Drag to pan when zoomed
2430
+ img.addEventListener('mousedown', (e) => {
2431
+ if (scale <= 1)
2432
+ return;
2433
+ e.preventDefault();
2434
+ isDragging = true;
2435
+ dragStartX = e.clientX;
2436
+ dragStartY = e.clientY;
2437
+ lastTranslateX = translateX;
2438
+ lastTranslateY = translateY;
2439
+ img.style.cursor = 'grabbing';
2440
+ img.style.transition = 'none';
2441
+ });
2442
+ window.addEventListener('mousemove', (e) => {
2443
+ if (!isDragging)
2444
+ return;
2445
+ translateX = lastTranslateX + (e.clientX - dragStartX);
2446
+ translateY = lastTranslateY + (e.clientY - dragStartY);
2447
+ applyTransform();
2448
+ });
2449
+ window.addEventListener('mouseup', () => {
2450
+ if (!isDragging)
2451
+ return;
2452
+ isDragging = false;
2453
+ img.style.cursor = scale > 1 ? 'zoom-out' : 'zoom-in';
2454
+ img.style.transition = 'transform 0.2s ease';
2455
+ });
2456
+ // Touch: pinch to zoom + drag to pan
2457
+ let lastTouchDist = 0;
2458
+ let lastTouchScale = 1;
2459
+ overlay.addEventListener('touchstart', (e) => {
2460
+ if (e.touches.length === 2) {
2461
+ e.preventDefault();
2462
+ const dx = e.touches[0].clientX - e.touches[1].clientX;
2463
+ const dy = e.touches[0].clientY - e.touches[1].clientY;
2464
+ lastTouchDist = Math.hypot(dx, dy);
2465
+ lastTouchScale = scale;
2466
+ }
2467
+ else if (e.touches.length === 1 && scale > 1) {
2468
+ isDragging = true;
2469
+ dragStartX = e.touches[0].clientX;
2470
+ dragStartY = e.touches[0].clientY;
2471
+ lastTranslateX = translateX;
2472
+ lastTranslateY = translateY;
2473
+ img.style.transition = 'none';
2474
+ }
2475
+ }, { passive: false });
2476
+ overlay.addEventListener('touchmove', (e) => {
2477
+ if (e.touches.length === 2) {
2478
+ e.preventDefault();
2479
+ const dx = e.touches[0].clientX - e.touches[1].clientX;
2480
+ const dy = e.touches[0].clientY - e.touches[1].clientY;
2481
+ const dist = Math.hypot(dx, dy);
2482
+ scale = Math.min(Math.max(lastTouchScale * (dist / lastTouchDist), 1), 5);
2483
+ if (scale === 1) {
2484
+ translateX = 0;
2485
+ translateY = 0;
2486
+ }
2487
+ applyTransform();
2488
+ }
2489
+ else if (e.touches.length === 1 && isDragging) {
2490
+ e.preventDefault();
2491
+ translateX = lastTranslateX + (e.touches[0].clientX - dragStartX);
2492
+ translateY = lastTranslateY + (e.touches[0].clientY - dragStartY);
2493
+ applyTransform();
2494
+ }
2495
+ }, { passive: false });
2496
+ overlay.addEventListener('touchend', (e) => {
2497
+ if (e.touches.length < 2) {
2498
+ lastTouchDist = 0;
2499
+ }
2500
+ if (e.touches.length === 0) {
2501
+ isDragging = false;
2502
+ img.style.transition = 'transform 0.2s ease';
2503
+ }
2504
+ });
2505
+ const close = () => {
2506
+ document.removeEventListener('keydown', handleKeyDown);
2507
+ overlay.remove();
2508
+ };
2509
+ // Only close on backdrop click when not zoomed (prevent accidental close while panning)
2510
+ overlay.addEventListener('click', (e) => {
2511
+ if (e.target === overlay && scale <= 1)
2512
+ close();
2513
+ });
2514
+ downloadBtn.addEventListener('click', (e) => e.stopPropagation());
2515
+ closeBtn.addEventListener('click', (e) => { e.stopPropagation(); close(); });
2516
+ // Close on Escape
2517
+ const handleKeyDown = (e) => {
2518
+ if (e.key === 'Escape')
2519
+ close();
2520
+ };
2521
+ document.addEventListener('keydown', handleKeyDown);
2522
+ overlay.appendChild(closeBtn);
2523
+ overlay.appendChild(downloadBtn);
2524
+ overlay.appendChild(img);
2525
+ document.body.appendChild(overlay);
2276
2526
  }
2277
2527
  /**
2278
2528
  * Initialize the SDK and render widget
@@ -2298,6 +2548,13 @@ class WeldSDK {
2298
2548
  this.logger.info('WeldSDK ready');
2299
2549
  // Call onReady callback
2300
2550
  this.config.onReady?.();
2551
+ // Start tracking page URL changes
2552
+ this.startPageTracking();
2553
+ // Auto-open if widget was previously open (persisted in sessionStorage)
2554
+ if (this.wasOpen()) {
2555
+ this.logger.info('Restoring previously open widget from sessionStorage');
2556
+ this.open();
2557
+ }
2301
2558
  }
2302
2559
  catch (error) {
2303
2560
  this.status = SDKStatus.ERROR;
@@ -2376,6 +2633,58 @@ class WeldSDK {
2376
2633
  isReady() {
2377
2634
  return this.status === SDKStatus.READY;
2378
2635
  }
2636
+ /**
2637
+ * Update callbacks on an existing instance (used by singleton reuse)
2638
+ */
2639
+ updateCallbacks(config) {
2640
+ if (config.onReady !== undefined)
2641
+ this.config.onReady = config.onReady;
2642
+ if (config.onOpen !== undefined)
2643
+ this.config.onOpen = config.onOpen;
2644
+ if (config.onClose !== undefined)
2645
+ this.config.onClose = config.onClose;
2646
+ if (config.onError !== undefined)
2647
+ this.config.onError = config.onError;
2648
+ if (config.onDestroy !== undefined)
2649
+ this.config.onDestroy = config.onDestroy;
2650
+ if (config.onMinimize !== undefined)
2651
+ this.config.onMinimize = config.onMinimize;
2652
+ if (config.onMaximize !== undefined)
2653
+ this.config.onMaximize = config.onMaximize;
2654
+ }
2655
+ /**
2656
+ * Persist open/closed state to sessionStorage
2657
+ */
2658
+ persistOpenState(isOpen) {
2659
+ try {
2660
+ sessionStorage.setItem(openStateKey(this.config.widgetId), isOpen ? 'true' : 'false');
2661
+ }
2662
+ catch {
2663
+ // sessionStorage might not be available
2664
+ }
2665
+ }
2666
+ /**
2667
+ * Clear persisted state from sessionStorage
2668
+ */
2669
+ clearPersistedState() {
2670
+ try {
2671
+ sessionStorage.removeItem(openStateKey(this.config.widgetId));
2672
+ }
2673
+ catch {
2674
+ // sessionStorage might not be available
2675
+ }
2676
+ }
2677
+ /**
2678
+ * Check if widget was previously open (from sessionStorage)
2679
+ */
2680
+ wasOpen() {
2681
+ try {
2682
+ return sessionStorage.getItem(openStateKey(this.config.widgetId)) === 'true';
2683
+ }
2684
+ catch {
2685
+ return false;
2686
+ }
2687
+ }
2379
2688
  /**
2380
2689
  * Open the widget
2381
2690
  */
@@ -2384,8 +2693,6 @@ class WeldSDK {
2384
2693
  console.log('[Weld SDK] Opening widget...');
2385
2694
  this.stateCoordinator.openWidget();
2386
2695
  this.iframeManager.showIframe(IframeType.WIDGET);
2387
- this.iframeManager.showIframe(IframeType.BACKDROP);
2388
- // Keep launcher visible so user can click it to close the widget
2389
2696
  // Send open message to the widget iframe
2390
2697
  const widgetIframe = this.iframeManager.getIframe(IframeType.WIDGET);
2391
2698
  if (widgetIframe?.element?.contentWindow) {
@@ -2396,6 +2703,7 @@ class WeldSDK {
2396
2703
  if (launcherIframe?.element?.contentWindow) {
2397
2704
  launcherIframe.element.contentWindow.postMessage({ type: 'weld:widget-opened' }, '*');
2398
2705
  }
2706
+ this.persistOpenState(true);
2399
2707
  this.config.onOpen?.();
2400
2708
  }
2401
2709
  /**
@@ -2406,8 +2714,6 @@ class WeldSDK {
2406
2714
  console.log('[Weld SDK] Closing widget...');
2407
2715
  this.stateCoordinator.closeWidget();
2408
2716
  this.iframeManager.hideIframe(IframeType.WIDGET);
2409
- this.iframeManager.hideIframe(IframeType.BACKDROP);
2410
- // Launcher stays visible
2411
2717
  // Send close message to the widget iframe
2412
2718
  const widgetIframe = this.iframeManager.getIframe(IframeType.WIDGET);
2413
2719
  if (widgetIframe?.element?.contentWindow) {
@@ -2418,6 +2724,7 @@ class WeldSDK {
2418
2724
  if (launcherIframe?.element?.contentWindow) {
2419
2725
  launcherIframe.element.contentWindow.postMessage({ type: 'weld:widget-closed' }, '*');
2420
2726
  }
2727
+ this.persistOpenState(false);
2421
2728
  this.config.onClose?.();
2422
2729
  }
2423
2730
  /**
@@ -2606,6 +2913,8 @@ class WeldSDK {
2606
2913
  });
2607
2914
  // Broadcast logout to iframes
2608
2915
  this.messageBroker.broadcast('weld:auth:logout', {});
2916
+ // Clear persisted widget state
2917
+ this.clearPersistedState();
2609
2918
  // Clear any stored session data
2610
2919
  try {
2611
2920
  const prefix = 'weld-';
@@ -2747,6 +3056,63 @@ class WeldSDK {
2747
3056
  this.logger.setLevel('warn');
2748
3057
  this.logger.info('Debug mode disabled');
2749
3058
  }
3059
+ /**
3060
+ * Send a page change message to the widget iframe
3061
+ */
3062
+ sendPageChange(url, title) {
3063
+ const widgetIframe = this.iframeManager.getIframe(IframeType.WIDGET);
3064
+ if (widgetIframe?.element?.contentWindow) {
3065
+ widgetIframe.element.contentWindow.postMessage({
3066
+ type: 'weld:page:change',
3067
+ url,
3068
+ title,
3069
+ timestamp: Date.now(),
3070
+ }, '*');
3071
+ }
3072
+ }
3073
+ /**
3074
+ * Start tracking page URL changes (SPA navigations + popstate)
3075
+ */
3076
+ startPageTracking() {
3077
+ let lastUrl = window.location.href;
3078
+ let debounceTimer = null;
3079
+ const notifyChange = () => {
3080
+ const currentUrl = window.location.href;
3081
+ if (currentUrl !== lastUrl) {
3082
+ lastUrl = currentUrl;
3083
+ this.sendPageChange(currentUrl, document.title);
3084
+ }
3085
+ };
3086
+ const debouncedNotify = () => {
3087
+ if (debounceTimer)
3088
+ clearTimeout(debounceTimer);
3089
+ debounceTimer = setTimeout(notifyChange, 300);
3090
+ };
3091
+ // Send initial page
3092
+ this.sendPageChange(window.location.href, document.title);
3093
+ // Monkey-patch history.pushState and history.replaceState
3094
+ const origPushState = history.pushState.bind(history);
3095
+ const origReplaceState = history.replaceState.bind(history);
3096
+ history.pushState = function (...args) {
3097
+ origPushState(...args);
3098
+ debouncedNotify();
3099
+ };
3100
+ history.replaceState = function (...args) {
3101
+ origReplaceState(...args);
3102
+ debouncedNotify();
3103
+ };
3104
+ // Listen for popstate (browser back/forward)
3105
+ const handlePopstate = () => debouncedNotify();
3106
+ window.addEventListener('popstate', handlePopstate);
3107
+ // Store cleanup
3108
+ this.pageTrackingCleanup = () => {
3109
+ if (debounceTimer)
3110
+ clearTimeout(debounceTimer);
3111
+ window.removeEventListener('popstate', handlePopstate);
3112
+ history.pushState = origPushState;
3113
+ history.replaceState = origReplaceState;
3114
+ };
3115
+ }
2750
3116
  /**
2751
3117
  * Ensure SDK is ready before operation
2752
3118
  */
@@ -2755,11 +3121,26 @@ class WeldSDK {
2755
3121
  throw new Error('SDK not ready. Call init() first.');
2756
3122
  }
2757
3123
  }
3124
+ /**
3125
+ * Detach from the current component lifecycle without destroying the widget.
3126
+ * Use this as a React useEffect cleanup — the widget stays alive across navigations.
3127
+ */
3128
+ detach() {
3129
+ // No-op: widget stays alive in the singleton registry
3130
+ this.logger.debug('WeldSDK detached (no-op, widget stays alive)');
3131
+ }
2758
3132
  /**
2759
3133
  * Destroy SDK and cleanup
2760
3134
  */
2761
3135
  destroy() {
2762
3136
  this.logger.info('Destroying WeldSDK');
3137
+ // Remove from singleton registry
3138
+ sdkRegistry.delete(this.config.widgetId);
3139
+ // Clear persisted state
3140
+ this.clearPersistedState();
3141
+ // Stop page tracking
3142
+ this.pageTrackingCleanup?.();
3143
+ this.pageTrackingCleanup = null;
2763
3144
  // Remove event listener using bound handler
2764
3145
  window.removeEventListener('message', this.boundHandleLauncherClick);
2765
3146
  // Unsubscribe from all message broker subscriptions