@tahoangphuc111/liquid-glass 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/{chunk-ZECDS4SL.cjs → chunk-2D22LMVV.cjs} +321 -89
  2. package/dist/chunk-2D22LMVV.cjs.map +1 -0
  3. package/dist/{chunk-RMWCG5MB.js → chunk-EOYQFWEA.js} +10 -4
  4. package/dist/chunk-EOYQFWEA.js.map +1 -0
  5. package/dist/{chunk-FB6QOH33.js → chunk-Y5GIJQVW.js} +321 -89
  6. package/dist/chunk-Y5GIJQVW.js.map +1 -0
  7. package/dist/{chunk-KKMJIY4M.cjs → chunk-YEATG3CF.cjs} +16 -10
  8. package/dist/chunk-YEATG3CF.cjs.map +1 -0
  9. package/dist/index.cjs +132 -69
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +7 -5
  12. package/dist/index.d.ts +7 -5
  13. package/dist/index.js +79 -16
  14. package/dist/index.js.map +1 -1
  15. package/dist/next/index.cjs +54 -12
  16. package/dist/next/index.cjs.map +1 -1
  17. package/dist/next/index.d.cts +2 -2
  18. package/dist/next/index.d.ts +2 -2
  19. package/dist/next/index.js +49 -7
  20. package/dist/next/index.js.map +1 -1
  21. package/dist/react/index.cjs +12 -8
  22. package/dist/react/index.cjs.map +1 -1
  23. package/dist/react/index.d.cts +2 -2
  24. package/dist/react/index.d.ts +2 -2
  25. package/dist/react/index.js +7 -3
  26. package/dist/react/index.js.map +1 -1
  27. package/dist/{types-BqXPylfU.d.cts → types-KM3HML4O.d.cts} +1 -0
  28. package/dist/{types-BqXPylfU.d.ts → types-KM3HML4O.d.ts} +1 -0
  29. package/dist/vue/index.cjs +19 -9
  30. package/dist/vue/index.cjs.map +1 -1
  31. package/dist/vue/index.d.cts +2 -2
  32. package/dist/vue/index.d.ts +2 -2
  33. package/dist/vue/index.js +12 -2
  34. package/dist/vue/index.js.map +1 -1
  35. package/package.json +1 -1
  36. package/dist/chunk-FB6QOH33.js.map +0 -1
  37. package/dist/chunk-KKMJIY4M.cjs.map +0 -1
  38. package/dist/chunk-RMWCG5MB.js.map +0 -1
  39. package/dist/chunk-ZECDS4SL.cjs.map +0 -1
@@ -66,13 +66,13 @@ function resolveChromaticAberration(value) {
66
66
  }
67
67
  function resolveGlassConfig(options = {}) {
68
68
  const surface = options.surface ?? DEFAULT_GLASS_CONFIG.surface;
69
- const thickness = options.thickness ?? DEFAULT_GLASS_CONFIG.thickness;
70
- const bezel = options.bezel ?? DEFAULT_GLASS_CONFIG.bezel;
71
- const scaleRatio = options.scaleRatio ?? DEFAULT_GLASS_CONFIG.scaleRatio;
72
- const maxScaleMultiplier = options.maxScaleMultiplier ?? DEFAULT_GLASS_CONFIG.maxScaleMultiplier;
73
- const blur = options.blur ?? DEFAULT_GLASS_CONFIG.blur;
74
- const ior = options.ior ?? DEFAULT_GLASS_CONFIG.ior;
75
- const radius = options.radius ?? DEFAULT_GLASS_CONFIG.radius;
69
+ const thickness = Number.isFinite(options.thickness) ? options.thickness : DEFAULT_GLASS_CONFIG.thickness;
70
+ const bezel = Number.isFinite(options.bezel) ? options.bezel : DEFAULT_GLASS_CONFIG.bezel;
71
+ const scaleRatio = Number.isFinite(options.scaleRatio) ? options.scaleRatio : DEFAULT_GLASS_CONFIG.scaleRatio;
72
+ const maxScaleMultiplier = Number.isFinite(options.maxScaleMultiplier) ? options.maxScaleMultiplier : DEFAULT_GLASS_CONFIG.maxScaleMultiplier;
73
+ const blur = Number.isFinite(options.blur) ? options.blur : DEFAULT_GLASS_CONFIG.blur;
74
+ const ior = Number.isFinite(options.ior) ? options.ior : DEFAULT_GLASS_CONFIG.ior;
75
+ const radius = Number.isFinite(options.radius) ? options.radius : DEFAULT_GLASS_CONFIG.radius;
76
76
  const pill = options.pill ?? DEFAULT_GLASS_CONFIG.pill;
77
77
  const hollow = options.hollow ?? DEFAULT_GLASS_CONFIG.hollow;
78
78
  const alwaysOn = options.alwaysOn ?? DEFAULT_GLASS_CONFIG.alwaysOn;
@@ -255,13 +255,18 @@ function initWasmSimdModule() {
255
255
  }
256
256
  const bytes = decodeBase64ToUint8(WASM_SIMD_BASE64);
257
257
  if (!bytes) return;
258
+ const wasmBufferSource = bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength ? bytes : bytes.slice();
259
+ if (!WebAssembly.validate(wasmBufferSource)) {
260
+ return;
261
+ }
258
262
  try {
259
- const module = new WebAssembly.Module(bytes.buffer);
263
+ const module = new WebAssembly.Module(wasmBufferSource);
260
264
  const instance = new WebAssembly.Instance(module);
261
265
  bindWasmInstance(instance);
262
266
  } catch {
263
- WebAssembly.instantiate(bytes.buffer).then((result) => {
264
- bindWasmInstance(result.instance);
267
+ WebAssembly.instantiate(wasmBufferSource).then((result) => {
268
+ const instance = "instance" in result ? result.instance : result;
269
+ bindWasmInstance(instance);
265
270
  }).catch((error) => {
266
271
  console.warn("[LiquidGlass] WASM async instantiation failed:", error);
267
272
  });
@@ -276,6 +281,11 @@ function getWasmDisplacementBmp(targetW, targetH, radius, clampedBezel, thicknes
276
281
  if (!wasmReady || !wasmExports || !wasmBmpU8View || !wasmF32View) {
277
282
  return null;
278
283
  }
284
+ if (wasmF32View.buffer.byteLength === 0 || wasmBmpU8View.buffer.byteLength === 0) {
285
+ const bmpOffset = typeof wasmExports.getBmpOffset === "function" ? wasmExports.getBmpOffset() : 84992;
286
+ wasmF32View = new Float32Array(wasmExports.memory.buffer);
287
+ wasmBmpU8View = new Uint8Array(wasmExports.memory.buffer, bmpOffset);
288
+ }
279
289
  let surfaceId = 0;
280
290
  if (surface === "convex_circle") surfaceId = 1;
281
291
  else if (surface === "linear") surfaceId = 2;
@@ -304,6 +314,11 @@ function getWasmDisplacementBmp(targetW, targetH, radius, clampedBezel, thicknes
304
314
  surfaceId,
305
315
  flags
306
316
  );
317
+ if (wasmBmpU8View.buffer.byteLength === 0 || wasmF32View.buffer.byteLength === 0) {
318
+ const bmpOffset = typeof wasmExports.getBmpOffset === "function" ? wasmExports.getBmpOffset() : 84992;
319
+ wasmF32View = new Float32Array(wasmExports.memory.buffer);
320
+ wasmBmpU8View = new Uint8Array(wasmExports.memory.buffer, bmpOffset);
321
+ }
307
322
  const bmpView = wasmBmpU8View.subarray(0, bmpByteLength);
308
323
  const blob = new Blob([bmpView], { type: "image/bmp" });
309
324
  const maxDisplacement = wasmF32View[wasmMaxDisplacementOffset >> 2] || 1;
@@ -349,6 +364,7 @@ function setTierChangeCallback(callback) {
349
364
  onTierChange = callback;
350
365
  }
351
366
  function scheduleQualityRecovery() {
367
+ if (exports.isGlassDowngraded) return;
352
368
  if (typeof requestIdleCallback !== "function") return;
353
369
  if (idleTimer !== null) {
354
370
  if (typeof cancelIdleCallback === "function") {
@@ -359,6 +375,7 @@ function scheduleQualityRecovery() {
359
375
  idleTimer = requestIdleCallback(
360
376
  (deadline) => {
361
377
  idleTimer = null;
378
+ if (exports.isGlassDowngraded) return;
362
379
  if (deadline.timeRemaining() > 40 && !deadline.didTimeout) {
363
380
  if (exports.qualityTier > 0) {
364
381
  applyQualityTier(0);
@@ -387,7 +404,8 @@ function recordJankFrame(timestamp) {
387
404
  if (jankCount < 8) jankCount++;
388
405
  let recent = 0;
389
406
  for (let i = 0; i < jankCount; i++) {
390
- if (timestamp - jankTimestamps[i] <= JANK_WINDOW_MS) {
407
+ const diff = timestamp - jankTimestamps[i];
408
+ if (diff >= 0 && diff <= JANK_WINDOW_MS) {
391
409
  recent++;
392
410
  }
393
411
  }
@@ -468,6 +486,8 @@ function getMediaQueries() {
468
486
  }
469
487
  var isBatteryLow = false;
470
488
  var batteryListenerAttached = false;
489
+ var activeBatteryManager = null;
490
+ var activeBatteryListener = null;
471
491
  var onBatteryChange = null;
472
492
  function setBatteryRefreshCallback(callback) {
473
493
  onBatteryChange = callback;
@@ -478,6 +498,8 @@ function attachBatteryListener() {
478
498
  if (typeof nav.getBattery !== "function") return;
479
499
  batteryListenerAttached = true;
480
500
  nav.getBattery().then((battery) => {
501
+ if (!batteryListenerAttached) return;
502
+ activeBatteryManager = battery;
481
503
  const updateBattery = () => {
482
504
  const wasLow = isBatteryLow;
483
505
  isBatteryLow = battery.level <= 0.2 && !battery.charging;
@@ -485,10 +507,12 @@ function attachBatteryListener() {
485
507
  onBatteryChange?.();
486
508
  }
487
509
  };
510
+ activeBatteryListener = updateBattery;
488
511
  updateBattery();
489
512
  battery.addEventListener("levelchange", updateBattery);
490
513
  battery.addEventListener("chargingchange", updateBattery);
491
514
  }).catch(() => {
515
+ batteryListenerAttached = false;
492
516
  });
493
517
  }
494
518
  function isConstrainedDevice() {
@@ -570,6 +594,13 @@ function detachGlobalListeners() {
570
594
  window.removeEventListener("focus", notifyUserActivity);
571
595
  window.removeEventListener("blur", onBlur);
572
596
  window.removeEventListener("resize", onResize);
597
+ if (activeBatteryManager && activeBatteryListener) {
598
+ activeBatteryManager.removeEventListener?.("levelchange", activeBatteryListener);
599
+ activeBatteryManager.removeEventListener?.("chargingchange", activeBatteryListener);
600
+ activeBatteryManager = null;
601
+ activeBatteryListener = null;
602
+ }
603
+ batteryListenerAttached = false;
573
604
  disconnectLoafTelemetry();
574
605
  }
575
606
 
@@ -606,6 +637,7 @@ function resetArchetypeHotSlots() {
606
637
  lastArchVal1 = null;
607
638
  lastArchVal2 = null;
608
639
  }
640
+ var getNowMs = () => typeof performance !== "undefined" ? performance.now() : Date.now();
609
641
  function scheduleLruEviction(delay = LRU_IDLE_EVICT_MS) {
610
642
  if (lruEvictionTimer !== null) return;
611
643
  lruEvictionTimer = setTimeout(processLruEviction, delay);
@@ -618,7 +650,7 @@ function clearLruEvictionTimer() {
618
650
  }
619
651
  function processLruEviction() {
620
652
  lruEvictionTimer = null;
621
- const now = performance.now();
653
+ const now = getNowMs();
622
654
  let nextDelay = LRU_IDLE_EVICT_MS;
623
655
  for (const key of lruUnusedFilterKeys) {
624
656
  const record = sharedFilters.get(key);
@@ -817,7 +849,7 @@ function acquireSharedFilter(options, tier = 0) {
817
849
  halfMinDim,
818
850
  svgDefs
819
851
  } = options;
820
- const now = performance.now();
852
+ const now = getNowMs();
821
853
  const existingRecord = sharedFilters.get(sharedKey);
822
854
  if (existingRecord !== void 0) {
823
855
  if (existingRecord.refCount >= 1 && (existingRecord.actualW !== actualW || existingRecord.actualH !== actualH)) {
@@ -1131,7 +1163,7 @@ function releaseSharedFilter(key, expectedRecord = null) {
1131
1163
  record.refCount--;
1132
1164
  if (record.refCount <= 0) {
1133
1165
  record.refCount = 0;
1134
- record.lastUsed = performance.now();
1166
+ record.lastUsed = getNowMs();
1135
1167
  lruUnusedFilterKeys.delete(key);
1136
1168
  lruUnusedFilterKeys.add(key);
1137
1169
  while (lruUnusedFilterKeys.size > MAX_LRU_FILTERS) {
@@ -1886,14 +1918,14 @@ function scheduleRebuildLiquidGlass(entries) {
1886
1918
  });
1887
1919
  }
1888
1920
  if (dirtyElements.size === 0) return;
1889
- const now = performance.now();
1921
+ const now = typeof performance !== "undefined" ? performance.now() : Date.now();
1890
1922
  if (resizeLiquidTimer !== null) clearTimeout(resizeLiquidTimer);
1891
1923
  if (now - resizeLastScheduleTime > 250) {
1892
1924
  resizeLastScheduleTime = now;
1893
1925
  requestAnimationFrame(() => void flushDirtyElements());
1894
1926
  } else {
1895
1927
  resizeLiquidTimer = setTimeout(() => {
1896
- resizeLastScheduleTime = performance.now();
1928
+ resizeLastScheduleTime = typeof performance !== "undefined" ? performance.now() : Date.now();
1897
1929
  requestAnimationFrame(() => void flushDirtyElements());
1898
1930
  }, 120);
1899
1931
  }
@@ -3227,7 +3259,11 @@ function createSceneCaptureController(sourceElement, getQualityOptions) {
3227
3259
  cancelAnimationFrame(captureFrame);
3228
3260
  captureFrame = null;
3229
3261
  }
3230
- captureCanvas = null;
3262
+ if (captureCanvas) {
3263
+ captureCanvas.width = 0;
3264
+ captureCanvas.height = 0;
3265
+ captureCanvas = null;
3266
+ }
3231
3267
  }
3232
3268
  };
3233
3269
  }
@@ -3254,7 +3290,8 @@ function evaluateOpticalProfile(depth, surface, ior) {
3254
3290
  const denom = 1 + depth * (0.725 + 0.21 * depth);
3255
3291
  const tilt = mask / (denom * denom);
3256
3292
  const xy = Math.min(0.98, Math.max(0, tilt * (0.5 + 0.5 * Math.min(2, slope))));
3257
- const eta = 1 / Math.max(1.01, ior);
3293
+ const safeIor = Number.isFinite(ior) ? Math.max(1.01, ior) : 1.49;
3294
+ const eta = 1 / safeIor;
3258
3295
  const displacement = (1 - eta * eta) * tilt / (1 + eta * Math.sqrt(1 + slope * slope));
3259
3296
  return [xy, displacement];
3260
3297
  }
@@ -3262,7 +3299,8 @@ function buildOpticalLut(surface, ior, size = OPTICAL_LUT_SIZE) {
3262
3299
  if (!Number.isInteger(size) || size < 2) {
3263
3300
  throw new RangeError("Optical LUT size must be an integer of at least 2");
3264
3301
  }
3265
- const key = `${surface}:${Math.max(1.01, ior)}:${size}`;
3302
+ const safeIor = Number.isFinite(ior) ? Math.max(1.01, ior) : 1.49;
3303
+ const key = `${surface}:${safeIor.toFixed(3)}:${size}`;
3266
3304
  const cached = opticalLutCache.get(key);
3267
3305
  if (cached) {
3268
3306
  opticalLutCache.delete(key);
@@ -3271,7 +3309,7 @@ function buildOpticalLut(surface, ior, size = OPTICAL_LUT_SIZE) {
3271
3309
  }
3272
3310
  const data = new Uint8Array(size * 4);
3273
3311
  for (let index = 0; index < size; index++) {
3274
- const [xy, displacement] = evaluateOpticalProfile(index / (size - 1), surface, ior);
3312
+ const [xy, displacement] = evaluateOpticalProfile(index / (size - 1), surface, safeIor);
3275
3313
  const normal = Math.round(xy * 65535);
3276
3314
  const offset = Math.round(displacement * 65535);
3277
3315
  data[index * 4] = normal >>> 8;
@@ -3456,8 +3494,8 @@ function createSampleEntry(gl, program) {
3456
3494
  lastBlurOffset1Y: Number.NaN,
3457
3495
  lastBlurOffset2X: Number.NaN,
3458
3496
  lastBlurOffset2Y: Number.NaN,
3459
- lastLightTiltHorizontal: 0,
3460
- lastLightTiltVertical: 0
3497
+ lastLightTiltHorizontal: Number.NaN,
3498
+ lastLightTiltVertical: Number.NaN
3461
3499
  };
3462
3500
  }
3463
3501
  function resolveSurfaceId(surface) {
@@ -4550,12 +4588,13 @@ function parseCssColorToRgb(colorStr = "#ffffff") {
4550
4588
  ];
4551
4589
  }
4552
4590
  }
4553
- const rgbMatch = trimmed.match(/rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i);
4591
+ const rgbMatch = trimmed.match(/rgba?\(\s*([\d.]+%?)[,\s]+([\d.]+%?)[,\s]+([\d.]+%?)/i);
4554
4592
  if (rgbMatch) {
4593
+ const parseChannel = (channelStr) => channelStr.endsWith("%") ? Math.min(1, Math.max(0, parseFloat(channelStr) / 100)) : Math.min(1, Math.max(0, parseFloat(channelStr) / 255));
4555
4594
  return [
4556
- Math.min(1, Math.max(0, Number(rgbMatch[1]) / 255)),
4557
- Math.min(1, Math.max(0, Number(rgbMatch[2]) / 255)),
4558
- Math.min(1, Math.max(0, Number(rgbMatch[3]) / 255))
4595
+ parseChannel(rgbMatch[1]),
4596
+ parseChannel(rgbMatch[2]),
4597
+ parseChannel(rgbMatch[3])
4559
4598
  ];
4560
4599
  }
4561
4600
  return [1, 1, 1];
@@ -4655,10 +4694,10 @@ var GlassWebglRenderer = class _GlassWebglRenderer {
4655
4694
  lastBlurOffset2X = Number.NaN;
4656
4695
  lastBlurOffset2Y = Number.NaN;
4657
4696
  lastDirectBlurClamp = -1;
4658
- lastLightTiltHorizontal = 0;
4659
- lastLightTiltVertical = 0;
4697
+ lastLightTiltHorizontal = Number.NaN;
4698
+ lastLightTiltVertical = Number.NaN;
4660
4699
  lastBleedPx = -1;
4661
- lastPeerCount = 0;
4700
+ lastPeerCount = -1;
4662
4701
  peerBoundsBuffer = new Float32Array(16);
4663
4702
  peerPropsBuffer = new Float32Array(16);
4664
4703
  disposed = false;
@@ -4785,7 +4824,7 @@ var GlassWebglRenderer = class _GlassWebglRenderer {
4785
4824
  this.hasSceneTextureData = false;
4786
4825
  return;
4787
4826
  }
4788
- if (!sourceCanvas || sourceCanvas.width === 0 || sourceCanvas.height === 0) {
4827
+ if (!sourceCanvas || sourceCanvas.width <= 0 || sourceCanvas.height <= 0) {
4789
4828
  this.hasSceneTextureData = false;
4790
4829
  return;
4791
4830
  }
@@ -5241,7 +5280,11 @@ var GlassWebglRenderer = class _GlassWebglRenderer {
5241
5280
  this.blurDownsampleProgram = null;
5242
5281
  }
5243
5282
  this.boundSceneTexture = null;
5244
- this.uploadCanvas = null;
5283
+ if (this.uploadCanvas) {
5284
+ this.uploadCanvas.width = 0;
5285
+ this.uploadCanvas.height = 0;
5286
+ this.uploadCanvas = null;
5287
+ }
5245
5288
  this.transferCache?.dispose();
5246
5289
  this.transferCache = null;
5247
5290
  this.gl.deleteTexture(this.opticalTexture);
@@ -5289,7 +5332,16 @@ function registerCoalescenceParticipant(participant) {
5289
5332
  const node = participantNodes.get(participant.element);
5290
5333
  if (!node) return;
5291
5334
  participantNodes.delete(participant.element);
5292
- if (node.lastPeerCount > 0) {
5335
+ let hadAnyActivePeers = node.lastPeerCount > 0;
5336
+ if (!hadAnyActivePeers) {
5337
+ for (const other of participantNodes.values()) {
5338
+ if (other.lastPeerCount > 0) {
5339
+ hadAnyActivePeers = true;
5340
+ break;
5341
+ }
5342
+ }
5343
+ }
5344
+ if (hadAnyActivePeers) {
5293
5345
  for (const other of participantNodes.values()) {
5294
5346
  other.participant.notifyPeerUpdate();
5295
5347
  }
@@ -5429,6 +5481,10 @@ var RELEASE_GAMMA = 6.75;
5429
5481
  var SETTLE_DISPLACEMENT = 3e-4;
5430
5482
  var SETTLE_VELOCITY = 3e-3;
5431
5483
  function stepSpring(value, velocity, target, dtSeconds, params) {
5484
+ if (!Number.isFinite(value) || !Number.isFinite(velocity) || !Number.isFinite(target)) {
5485
+ return { value: Number.isFinite(target) ? target : 0, velocity: 0, settled: true };
5486
+ }
5487
+ const safeDt = Number.isFinite(dtSeconds) && dtSeconds > 0 ? dtSeconds : 0.016;
5432
5488
  const {
5433
5489
  stiffness,
5434
5490
  gamma,
@@ -5436,21 +5492,21 @@ function stepSpring(value, velocity, target, dtSeconds, params) {
5436
5492
  settleVelocity = SETTLE_VELOCITY
5437
5493
  } = params;
5438
5494
  const offset = value - target;
5439
- const decay = Math.exp(-gamma * dtSeconds);
5495
+ const decay = Math.exp(-gamma * safeDt);
5440
5496
  const discriminant = stiffness - gamma * gamma;
5441
5497
  let nextOffset;
5442
5498
  let nextVelocity;
5443
5499
  if (discriminant > 1e-4) {
5444
5500
  const omegaD = Math.sqrt(discriminant);
5445
5501
  const invOmegaD = 1 / omegaD;
5446
- const phase = omegaD * dtSeconds;
5502
+ const phase = omegaD * safeDt;
5447
5503
  const cosPhase = Math.cos(phase);
5448
5504
  const sinOverOmega = Math.sin(phase) * invOmegaD;
5449
5505
  nextOffset = decay * (offset * (cosPhase + gamma * sinOverOmega) + velocity * sinOverOmega);
5450
5506
  nextVelocity = decay * (velocity * (cosPhase - gamma * sinOverOmega) - stiffness * offset * sinOverOmega);
5451
5507
  } else {
5452
- nextOffset = decay * (offset * (1 + gamma * dtSeconds) + velocity * dtSeconds);
5453
- nextVelocity = decay * (velocity * (1 - gamma * dtSeconds) - gamma * gamma * offset * dtSeconds);
5508
+ nextOffset = decay * (offset * (1 + gamma * safeDt) + velocity * safeDt);
5509
+ nextVelocity = decay * (velocity * (1 - gamma * safeDt) - gamma * gamma * offset * safeDt);
5454
5510
  }
5455
5511
  const nextValue = target + nextOffset;
5456
5512
  const settled = Math.abs(nextOffset) < settleDisplacement && Math.abs(nextVelocity) < settleVelocity;
@@ -5698,7 +5754,10 @@ function createInteractiveSpring(onFrame, onRest) {
5698
5754
  if (destroyed) return;
5699
5755
  destroyed = true;
5700
5756
  stopLoop();
5701
- onRest();
5757
+ try {
5758
+ onRest();
5759
+ } catch {
5760
+ }
5702
5761
  }
5703
5762
  };
5704
5763
  }
@@ -5737,11 +5796,15 @@ function findBestStandbyCandidate() {
5737
5796
  return bestVisible;
5738
5797
  }
5739
5798
  function promoteStandbyIfPossible() {
5740
- if (activeEntries.size >= maxActiveContexts) return;
5741
- const candidate = findBestStandbyCandidate();
5742
- if (!candidate) return;
5743
- standbyEntries.delete(candidate.token);
5744
- candidate.restoreWebgl();
5799
+ while (activeEntries.size < maxActiveContexts) {
5800
+ const candidate = findBestStandbyCandidate();
5801
+ if (!candidate) break;
5802
+ standbyEntries.delete(candidate.token);
5803
+ candidate.restoreWebgl();
5804
+ if (!activeEntries.has(candidate.token)) {
5805
+ break;
5806
+ }
5807
+ }
5745
5808
  }
5746
5809
  function acquireWebglSlot(entry, allowEvictVisible = true) {
5747
5810
  entry.lastUsedOrder = ++sequenceCounter;
@@ -5879,6 +5942,7 @@ function createLiquidGlass(element, initialOptions = {}) {
5879
5942
  let renderFrameId = null;
5880
5943
  let lastSceneBackdropKey = "";
5881
5944
  let listenersAttached2 = false;
5945
+ let webglWindowListenersAttached = false;
5882
5946
  let isViewportVisible = true;
5883
5947
  let pendingVisibleRender = false;
5884
5948
  let unobserveVisibility = null;
@@ -5944,10 +6008,21 @@ function createLiquidGlass(element, initialOptions = {}) {
5944
6008
  };
5945
6009
  const computeSceneRect = () => {
5946
6010
  const source = sceneEl ?? options.sceneElement;
5947
- if (!source || !source.isConnected) return void 0;
6011
+ const activeSceneCanvas = externalSceneCanvas ?? capturedSceneCanvas;
6012
+ if (!source || !source.isConnected) {
6013
+ if (activeSceneCanvas && activeSceneCanvas.width > 0 && activeSceneCanvas.height > 0) {
6014
+ return { relX: 0, relY: 0, relW: 1, relH: 1 };
6015
+ }
6016
+ return void 0;
6017
+ }
5948
6018
  const sourceRect = source.getBoundingClientRect();
5949
6019
  const elRect = element.getBoundingClientRect();
5950
- if (sourceRect.width < 2 || sourceRect.height < 2) return void 0;
6020
+ if (sourceRect.width < 2 || sourceRect.height < 2) {
6021
+ if (activeSceneCanvas && activeSceneCanvas.width > 0 && activeSceneCanvas.height > 0) {
6022
+ return { relX: 0, relY: 0, relW: 1, relH: 1 };
6023
+ }
6024
+ return void 0;
6025
+ }
5951
6026
  const width = element.offsetWidth || elRect.width;
5952
6027
  const height = element.offsetHeight || elRect.height;
5953
6028
  const elCenterX = (elRect.left + elRect.right) * 0.5;
@@ -6032,6 +6107,8 @@ function createLiquidGlass(element, initialOptions = {}) {
6032
6107
  element.setAttribute("data-lg-webgl-scene", hasSceneTex ? "1" : "0");
6033
6108
  if (!hasSceneTex && config.coreFilter) {
6034
6109
  element.style.setProperty("--lg-filter", config.coreFilter);
6110
+ } else {
6111
+ element.style.removeProperty("--lg-filter");
6035
6112
  }
6036
6113
  webglRenderer.render({
6037
6114
  width,
@@ -6113,7 +6190,8 @@ function createLiquidGlass(element, initialOptions = {}) {
6113
6190
  cancelAnimationFrame(scrollFrameId);
6114
6191
  scrollFrameId = null;
6115
6192
  }
6116
- if (typeof window !== "undefined") {
6193
+ if (typeof window !== "undefined" && webglWindowListenersAttached) {
6194
+ webglWindowListenersAttached = false;
6117
6195
  window.removeEventListener("scroll", onViewportScrollOrResize);
6118
6196
  window.removeEventListener("resize", onViewportScrollOrResize);
6119
6197
  }
@@ -6259,7 +6337,8 @@ function createLiquidGlass(element, initialOptions = {}) {
6259
6337
  if (!unobserveVisibility) {
6260
6338
  unobserveVisibility = observeElementVisibility(element, handleVisibilityChange2);
6261
6339
  }
6262
- if (typeof window !== "undefined") {
6340
+ if (typeof window !== "undefined" && !webglWindowListenersAttached) {
6341
+ webglWindowListenersAttached = true;
6263
6342
  window.addEventListener("scroll", onViewportScrollOrResize, { passive: true });
6264
6343
  window.addEventListener("resize", onViewportScrollOrResize, { passive: true });
6265
6344
  }
@@ -6288,6 +6367,7 @@ function createLiquidGlass(element, initialOptions = {}) {
6288
6367
  const isInteractiveElement = () => options.interactive ?? isButtonElement();
6289
6368
  const onInteractivePointerDown = (event) => {
6290
6369
  if (event.pointerType === "mouse" && event.button !== 0) return;
6370
+ if (isPointerDragging || activeDragPointerId !== null) return;
6291
6371
  hasDraggedBeyondThreshold = false;
6292
6372
  springController?.press();
6293
6373
  const dragMode = resolveDragMode();
@@ -6372,11 +6452,18 @@ function createLiquidGlass(element, initialOptions = {}) {
6372
6452
  }
6373
6453
  };
6374
6454
  const onInteractivePointerUp = (event) => {
6455
+ if (activeDragPointerId !== null && event.pointerId !== activeDragPointerId) {
6456
+ return;
6457
+ }
6375
6458
  finishDragInteraction(event, false);
6376
6459
  springController?.release(true);
6377
6460
  };
6378
6461
  const onInteractivePointerCancel = (event) => {
6379
6462
  if (isPointerDragging && event.type === "pointerleave") return;
6463
+ const pointerEvent = event;
6464
+ if (typeof pointerEvent.pointerId === "number" && activeDragPointerId !== null && pointerEvent.pointerId !== activeDragPointerId && event.type !== "blur") {
6465
+ return;
6466
+ }
6380
6467
  finishDragInteraction(event, true);
6381
6468
  springController?.setTilt(0, 0);
6382
6469
  springController?.release(false);
@@ -6411,6 +6498,12 @@ function createLiquidGlass(element, initialOptions = {}) {
6411
6498
  element.removeEventListener("keyup", onInteractiveKeyUp);
6412
6499
  element.removeEventListener("blur", onInteractivePointerCancel);
6413
6500
  }
6501
+ if (activeDragPointerId !== null) {
6502
+ try {
6503
+ element.releasePointerCapture?.(activeDragPointerId);
6504
+ } catch {
6505
+ }
6506
+ }
6414
6507
  springController?.destroy();
6415
6508
  springController = null;
6416
6509
  isPointerDragging = false;
@@ -6455,10 +6548,8 @@ function createLiquidGlass(element, initialOptions = {}) {
6455
6548
  "--lg-stretch-matrix",
6456
6549
  `matrix(${m11.toFixed(4)}, ${m12.toFixed(4)}, ${m21.toFixed(4)}, ${m22.toFixed(4)}, 0, 0)`
6457
6550
  );
6458
- if (frame.dragX !== 0 || frame.dragY !== 0) {
6459
- element.style.setProperty("--lg-drag-x", `${frame.dragX.toFixed(2)}px`);
6460
- element.style.setProperty("--lg-drag-y", `${frame.dragY.toFixed(2)}px`);
6461
- }
6551
+ element.style.setProperty("--lg-drag-x", `${frame.dragX.toFixed(2)}px`);
6552
+ element.style.setProperty("--lg-drag-y", `${frame.dragY.toFixed(2)}px`);
6462
6553
  element.style.setProperty("--lg-press-glow", frame.glow.toFixed(3));
6463
6554
  const prevGlow = pressGlow;
6464
6555
  const prevTiltH = lightTiltHorizontal;
@@ -6604,6 +6695,9 @@ function createLiquidGlass(element, initialOptions = {}) {
6604
6695
  },
6605
6696
  refresh() {
6606
6697
  if (destroyed) return;
6698
+ cachedRadiusStr = null;
6699
+ const existingState = elementStateMap.get(element);
6700
+ if (existingState) existingState.cachedRadiusStr = null;
6607
6701
  const targetEngine = resolveGlassEngine(options.engine ?? "auto", hasSceneInput());
6608
6702
  if (targetEngine !== activeEngine) {
6609
6703
  if (targetEngine === "webgl" && activeEngine === "css" && isWebglSlotOnStandby(webglPoolEntry)) {
@@ -6621,9 +6715,6 @@ function createLiquidGlass(element, initialOptions = {}) {
6621
6715
  syncCoalescenceState(0, true);
6622
6716
  scheduleWebglRender();
6623
6717
  } else if (activeEngine === "wasm-svg") {
6624
- cachedRadiusStr = null;
6625
- const existingState = elementStateMap.get(element);
6626
- if (existingState) existingState.cachedRadiusStr = null;
6627
6718
  registerManagedElement(element, config);
6628
6719
  syncCoalescenceState(0, true);
6629
6720
  applyCoalescenceVisuals();
@@ -6647,6 +6738,11 @@ function createLiquidGlass(element, initialOptions = {}) {
6647
6738
  localSceneCapture = null;
6648
6739
  capturedSceneCanvas = null;
6649
6740
  }
6741
+ const targetEngine = resolveGlassEngine(options.engine ?? "auto", hasSceneInput());
6742
+ if (targetEngine !== activeEngine) {
6743
+ applyEngine();
6744
+ return;
6745
+ }
6650
6746
  if (activeEngine === "webgl" && webglRenderer) {
6651
6747
  if (!canvas && (sceneEl || options.sceneElement)) {
6652
6748
  mountWebgl();
@@ -6654,7 +6750,7 @@ function createLiquidGlass(element, initialOptions = {}) {
6654
6750
  webglRenderer.setSceneCanvas(canvas);
6655
6751
  scheduleWebglRender();
6656
6752
  }
6657
- } else if ((options.engine ?? "auto") === "auto") {
6753
+ } else {
6658
6754
  applyEngine();
6659
6755
  }
6660
6756
  },
@@ -6796,9 +6892,10 @@ function computeMidpointDetent(rawPos, anchors) {
6796
6892
  }
6797
6893
  const normSegment = (rawPos - segmentStart) / segmentSpan;
6798
6894
  if (normSegment > 0.35 && normSegment < 0.65) {
6799
- const offsetFromMid = normSegment - 0.5;
6800
- const offsetSquared = offsetFromMid * offsetFromMid;
6801
- return rawPos + offsetFromMid * (6.283185307 - offsetSquared * (10.33542556 - 5.1003304 * offsetSquared));
6895
+ const x = (normSegment - 0.5) / 0.15;
6896
+ const oneMinusX2 = 1 - x * x;
6897
+ const deflection = segmentSpan * 0.05 * (oneMinusX2 * oneMinusX2) * x;
6898
+ return rawPos + deflection;
6802
6899
  }
6803
6900
  return rawPos;
6804
6901
  }
@@ -6824,27 +6921,45 @@ function interpolateGliderWidth(posPx, anchors) {
6824
6921
  }
6825
6922
  return lastAnchor.width;
6826
6923
  }
6827
- function findClosestAnchorIndex(posPx, anchors) {
6924
+ function isItemDisabled(el) {
6925
+ if (!el) return false;
6926
+ return el.hasAttribute("disabled") || el.disabled === true || el.getAttribute("aria-disabled") === "true" || el.classList.contains("disabled") || el.classList.contains("is-disabled");
6927
+ }
6928
+ function findClosestAnchorIndex(posPx, anchors, fallbackIndex = 0) {
6828
6929
  if (anchors.length <= 1) {
6829
- return 0;
6930
+ if (anchors.length === 1 && !isItemDisabled(anchors[0].element)) {
6931
+ return 0;
6932
+ }
6933
+ return fallbackIndex;
6830
6934
  }
6831
- let bestIndex = 0;
6832
- let bestDistance = Math.abs(anchors[0].left - posPx);
6833
- for (let idx = 1; idx < anchors.length; idx += 1) {
6935
+ let bestIndex = -1;
6936
+ let bestDistance = Infinity;
6937
+ for (let idx = 0; idx < anchors.length; idx += 1) {
6938
+ if (isItemDisabled(anchors[idx].element)) {
6939
+ continue;
6940
+ }
6834
6941
  const distance = Math.abs(anchors[idx].left - posPx);
6835
6942
  if (distance < bestDistance) {
6836
6943
  bestDistance = distance;
6837
6944
  bestIndex = idx;
6838
6945
  }
6839
6946
  }
6840
- return bestIndex;
6947
+ if (bestIndex >= 0) {
6948
+ return bestIndex;
6949
+ }
6950
+ if (fallbackIndex >= 0 && fallbackIndex < anchors.length && !isItemDisabled(anchors[fallbackIndex].element)) {
6951
+ return fallbackIndex;
6952
+ }
6953
+ const firstEnabled = anchors.findIndex((anchor) => !isItemDisabled(anchor.element));
6954
+ return firstEnabled >= 0 ? firstEnabled : fallbackIndex;
6841
6955
  }
6842
6956
  function createGlassSwitch(element, options = {}) {
6843
6957
  element.classList.add("lg-switch");
6844
- if (!element.getAttribute("role")) {
6958
+ const assignedRole = !element.getAttribute("role");
6959
+ if (assignedRole) {
6845
6960
  element.setAttribute("role", "tablist");
6846
6961
  }
6847
- const itemSelector = options.itemSelector ?? "[data-switch-item], .lg-switch-item, button, a, [role='tab']";
6962
+ let itemSelector = options.itemSelector ?? "[data-switch-item], .lg-switch-item, button, a, [role='tab']";
6848
6963
  const existingGlider = options.gliderElement ?? element.querySelector(":scope > .lg-switch-glider");
6849
6964
  const createdGlider = !existingGlider;
6850
6965
  const gliderEl = existingGlider ?? document.createElement("span");
@@ -6861,6 +6976,7 @@ function createGlassSwitch(element, options = {}) {
6861
6976
  tintOpacity: 0.08,
6862
6977
  highlight: 0.32,
6863
6978
  ...baseGlassOptions,
6979
+ onEngineChange: void 0,
6864
6980
  pill: true,
6865
6981
  interactive: false,
6866
6982
  draggable: false,
@@ -6917,6 +7033,7 @@ function createGlassSwitch(element, options = {}) {
6917
7033
  }
6918
7034
  let anchors = [];
6919
7035
  let currentIndex = 0;
7036
+ let pendingWantedValue = options.value ?? options.defaultValue;
6920
7037
  let baseOffsetLeft = CONTAINER_PADDING_PX;
6921
7038
  let posX = 0;
6922
7039
  let velX = 0;
@@ -6950,14 +7067,22 @@ function createGlassSwitch(element, options = {}) {
6950
7067
  let lastFrameTime = 0;
6951
7068
  let isDestroyed = false;
6952
7069
  function measureAnchors() {
6953
- const candidates = Array.from(element.querySelectorAll(itemSelector)).filter(
7070
+ const rawCandidates = Array.from(element.querySelectorAll(itemSelector)).filter(
6954
7071
  (candidate) => candidate !== gliderEl && !gliderEl.contains(candidate)
6955
7072
  );
7073
+ const candidates = rawCandidates.filter(
7074
+ (candidate) => !rawCandidates.some((other) => other !== candidate && other.contains(candidate))
7075
+ );
6956
7076
  if (candidates.length === 0) {
6957
7077
  anchors = [];
7078
+ currentIndex = 0;
7079
+ targetPosX = 0;
6958
7080
  baseOffsetLeft = CONTAINER_PADDING_PX;
7081
+ gliderEl.style.left = `${baseOffsetLeft}px`;
7082
+ gliderEl.style.opacity = "0";
6959
7083
  return;
6960
7084
  }
7085
+ gliderEl.style.opacity = "";
6961
7086
  const firstOffset = candidates[0].offsetLeft;
6962
7087
  const firstWidth = candidates[0].offsetWidth;
6963
7088
  const hasLayoutGeometry = candidates.some(
@@ -6980,6 +7105,26 @@ function createGlassSwitch(element, options = {}) {
6980
7105
  anchors[idx].left = idx * FALLBACK_ITEM_WIDTH_PX;
6981
7106
  }
6982
7107
  }
7108
+ if (pendingWantedValue !== void 0) {
7109
+ const matchedIndex = anchors.findIndex(
7110
+ (anchor) => anchor.value === pendingWantedValue
7111
+ );
7112
+ if (matchedIndex >= 0) {
7113
+ if (!isItemDisabled(anchors[matchedIndex].element)) {
7114
+ currentIndex = matchedIndex;
7115
+ }
7116
+ pendingWantedValue = void 0;
7117
+ }
7118
+ }
7119
+ if (currentIndex >= anchors.length) {
7120
+ currentIndex = Math.max(0, anchors.length - 1);
7121
+ }
7122
+ if (anchors.length > 0 && isItemDisabled(anchors[currentIndex]?.element)) {
7123
+ const firstEnabled = anchors.findIndex((anchor) => !isItemDisabled(anchor.element));
7124
+ if (firstEnabled >= 0) {
7125
+ currentIndex = firstEnabled;
7126
+ }
7127
+ }
6983
7128
  }
6984
7129
  function getTravelSpan() {
6985
7130
  if (anchors.length < 2) {
@@ -7002,7 +7147,7 @@ function createGlassSwitch(element, options = {}) {
7002
7147
  lastSweepQuant = sweepQuant;
7003
7148
  element.style.setProperty("--sweep", `${(sweepQuant * 0.1).toFixed(1)}%`);
7004
7149
  }
7005
- const closestIndex = findClosestAnchorIndex(visualPosX, anchors);
7150
+ const closestIndex = findClosestAnchorIndex(visualPosX, anchors, currentIndex);
7006
7151
  if (force || closestIndex !== lastHighlightIndex) {
7007
7152
  lastHighlightIndex = closestIndex;
7008
7153
  for (let idx = 0; idx < anchors.length; idx += 1) {
@@ -7206,6 +7351,7 @@ function createGlassSwitch(element, options = {}) {
7206
7351
  const boundedIndex = Math.max(0, Math.min(anchors.length - 1, nextIndex));
7207
7352
  const previousIndex = currentIndex;
7208
7353
  currentIndex = boundedIndex;
7354
+ pendingWantedValue = void 0;
7209
7355
  const targetAnchor = anchors[boundedIndex];
7210
7356
  targetPosX = targetAnchor.left;
7211
7357
  if (!animate || reducedMotionQuery2?.matches) {
@@ -7230,19 +7376,34 @@ function createGlassSwitch(element, options = {}) {
7230
7376
  }
7231
7377
  }
7232
7378
  function cleanupWindowPointerListeners() {
7379
+ if (typeof window === "undefined") {
7380
+ return;
7381
+ }
7233
7382
  window.removeEventListener("pointermove", handlePointerMove);
7234
7383
  window.removeEventListener("pointerup", handlePointerEnd);
7235
7384
  window.removeEventListener("pointercancel", handlePointerCancel);
7236
7385
  window.removeEventListener("blur", handleWindowBlur);
7237
7386
  }
7238
7387
  function handlePointerDown(event) {
7239
- if (isDestroyed || anchors.length === 0) {
7388
+ if (isDestroyed || isPointerDown) {
7240
7389
  return;
7241
7390
  }
7242
7391
  if (event.button !== 0 && event.pointerType === "mouse") {
7243
7392
  return;
7244
7393
  }
7245
7394
  measureAnchors();
7395
+ if (anchors.length === 0) {
7396
+ return;
7397
+ }
7398
+ const eventTarget = event.target;
7399
+ if (eventTarget) {
7400
+ const hitAnchor = anchors.find(
7401
+ (anchor) => anchor.element === eventTarget || anchor.element.contains(eventTarget)
7402
+ );
7403
+ if (hitAnchor && isItemDisabled(hitAnchor.element)) {
7404
+ return;
7405
+ }
7406
+ }
7246
7407
  isPointerDown = true;
7247
7408
  isDragging = false;
7248
7409
  activePointerId = event.pointerId;
@@ -7269,6 +7430,9 @@ function createGlassSwitch(element, options = {}) {
7269
7430
  if (!isPointerDown || isDestroyed) {
7270
7431
  return;
7271
7432
  }
7433
+ if (activePointerId !== -1 && event.pointerId !== activePointerId) {
7434
+ return;
7435
+ }
7272
7436
  const deltaX = event.clientX - startPointerX;
7273
7437
  const now = performance.now();
7274
7438
  const elapsedMs = now - lastPointerTime;
@@ -7317,10 +7481,13 @@ function createGlassSwitch(element, options = {}) {
7317
7481
  activePointerId = -1;
7318
7482
  }
7319
7483
  function handlePointerEnd(event) {
7320
- cleanupWindowPointerListeners();
7321
7484
  if (!isPointerDown) {
7322
7485
  return;
7323
7486
  }
7487
+ if (activePointerId !== -1 && event.pointerId !== activePointerId) {
7488
+ return;
7489
+ }
7490
+ cleanupWindowPointerListeners();
7324
7491
  isPointerDown = false;
7325
7492
  element.classList.remove("is-pressed");
7326
7493
  if (isDragging) {
@@ -7333,7 +7500,7 @@ function createGlassSwitch(element, options = {}) {
7333
7500
  const rawReleaseVel = Math.abs(smoothedDragVel) > 0.05 ? smoothedDragVel : deltaX / totalElapsedMs;
7334
7501
  const releaseVel = Math.max(-3, Math.min(3, rawReleaseVel));
7335
7502
  const projectedPosX = posX + releaseVel * 1e3 * 0.12;
7336
- const nextIndex = findClosestAnchorIndex(projectedPosX, anchors);
7503
+ const nextIndex = findClosestAnchorIndex(projectedPosX, anchors, currentIndex);
7337
7504
  velX = releaseVel * 1e3;
7338
7505
  targetSwell = 1;
7339
7506
  holdSwellUntil = 0;
@@ -7345,11 +7512,14 @@ function createGlassSwitch(element, options = {}) {
7345
7512
  startLoop();
7346
7513
  }
7347
7514
  }
7348
- function handlePointerCancel() {
7349
- cleanupWindowPointerListeners();
7515
+ function handlePointerCancel(event) {
7350
7516
  if (!isPointerDown) {
7351
7517
  return;
7352
7518
  }
7519
+ if (event && activePointerId !== -1 && event.pointerId !== activePointerId) {
7520
+ return;
7521
+ }
7522
+ cleanupWindowPointerListeners();
7353
7523
  isPointerDown = false;
7354
7524
  isDragging = false;
7355
7525
  element.classList.remove("is-pressed", "is-dragging");
@@ -7371,28 +7541,59 @@ function createGlassSwitch(element, options = {}) {
7371
7541
  if (!eventTarget) {
7372
7542
  return;
7373
7543
  }
7374
- const matchedIndex = anchors.findIndex(
7544
+ if (anchors.length === 0) {
7545
+ measureAnchors();
7546
+ }
7547
+ let matchedIndex = anchors.findIndex(
7375
7548
  (anchor) => anchor.element === eventTarget || anchor.element.contains(eventTarget)
7376
7549
  );
7550
+ if (matchedIndex === -1) {
7551
+ measureAnchors();
7552
+ matchedIndex = anchors.findIndex(
7553
+ (anchor) => anchor.element === eventTarget || anchor.element.contains(eventTarget)
7554
+ );
7555
+ }
7377
7556
  if (matchedIndex === -1) {
7378
7557
  return;
7379
7558
  }
7380
- measureAnchors();
7559
+ if (isItemDisabled(anchors[matchedIndex].element)) {
7560
+ event.preventDefault();
7561
+ return;
7562
+ }
7381
7563
  commitActiveIndex(matchedIndex, true, true, true);
7382
7564
  }
7383
7565
  function handleKeyDown(event) {
7566
+ if (anchors.length === 0) {
7567
+ measureAnchors();
7568
+ }
7384
7569
  if (anchors.length === 0) {
7385
7570
  return;
7386
7571
  }
7387
7572
  let targetIndex = -1;
7388
- if (event.key === "ArrowRight") {
7389
- targetIndex = Math.min(anchors.length - 1, currentIndex + 1);
7390
- } else if (event.key === "ArrowLeft") {
7391
- targetIndex = Math.max(0, currentIndex - 1);
7573
+ if (event.key === "ArrowRight" || event.key === "ArrowDown") {
7574
+ let next = currentIndex + 1;
7575
+ while (next < anchors.length && isItemDisabled(anchors[next].element)) {
7576
+ next++;
7577
+ }
7578
+ if (next < anchors.length) targetIndex = next;
7579
+ } else if (event.key === "ArrowLeft" || event.key === "ArrowUp") {
7580
+ let prev = currentIndex - 1;
7581
+ while (prev >= 0 && isItemDisabled(anchors[prev].element)) {
7582
+ prev--;
7583
+ }
7584
+ if (prev >= 0) targetIndex = prev;
7392
7585
  } else if (event.key === "Home") {
7393
- targetIndex = 0;
7586
+ let first = 0;
7587
+ while (first < anchors.length && isItemDisabled(anchors[first].element)) {
7588
+ first++;
7589
+ }
7590
+ if (first < anchors.length) targetIndex = first;
7394
7591
  } else if (event.key === "End") {
7395
- targetIndex = anchors.length - 1;
7592
+ let last = anchors.length - 1;
7593
+ while (last >= 0 && isItemDisabled(anchors[last].element)) {
7594
+ last--;
7595
+ }
7596
+ if (last >= 0) targetIndex = last;
7396
7597
  }
7397
7598
  if (targetIndex === -1) {
7398
7599
  return;
@@ -7408,7 +7609,15 @@ function createGlassSwitch(element, options = {}) {
7408
7609
  const matchedInitial = anchors.findIndex(
7409
7610
  (anchor) => anchor.value === initialWantedValue
7410
7611
  );
7411
- currentIndex = matchedInitial >= 0 ? matchedInitial : 0;
7612
+ if (matchedInitial >= 0 && !isItemDisabled(anchors[matchedInitial].element)) {
7613
+ currentIndex = matchedInitial;
7614
+ }
7615
+ }
7616
+ if (anchors.length > 0 && isItemDisabled(anchors[currentIndex]?.element)) {
7617
+ const firstEnabled = anchors.findIndex((anchor) => !isItemDisabled(anchor.element));
7618
+ if (firstEnabled >= 0) {
7619
+ currentIndex = firstEnabled;
7620
+ }
7412
7621
  }
7413
7622
  if (anchors.length > 0) {
7414
7623
  posX = anchors[currentIndex].left;
@@ -7424,10 +7633,12 @@ function createGlassSwitch(element, options = {}) {
7424
7633
  return;
7425
7634
  }
7426
7635
  measureAnchors();
7427
- if (anchors.length > 0 && !rafId) {
7428
- posX = anchors[currentIndex]?.left ?? 0;
7429
- targetPosX = posX;
7430
- renderGliderTransform(true);
7636
+ if (anchors.length > 0) {
7637
+ targetPosX = anchors[currentIndex]?.left ?? 0;
7638
+ if (!rafId) {
7639
+ posX = targetPosX;
7640
+ renderGliderTransform(true);
7641
+ }
7431
7642
  }
7432
7643
  }) : null;
7433
7644
  resizeObserver?.observe(element);
@@ -7439,12 +7650,13 @@ function createGlassSwitch(element, options = {}) {
7439
7650
  return gliderGlass.engine;
7440
7651
  },
7441
7652
  get value() {
7442
- return anchors[currentIndex]?.value ?? "";
7653
+ return anchors[currentIndex]?.value ?? pendingWantedValue ?? "";
7443
7654
  },
7444
7655
  get activeIndex() {
7445
7656
  return currentIndex;
7446
7657
  },
7447
7658
  setValue(value, animate = true) {
7659
+ pendingWantedValue = value;
7448
7660
  measureAnchors();
7449
7661
  const foundIndex = anchors.findIndex((anchor) => anchor.value === value);
7450
7662
  if (foundIndex >= 0) {
@@ -7452,6 +7664,7 @@ function createGlassSwitch(element, options = {}) {
7452
7664
  }
7453
7665
  },
7454
7666
  setActiveIndex(index, animate = true) {
7667
+ pendingWantedValue = void 0;
7455
7668
  measureAnchors();
7456
7669
  commitActiveIndex(index, animate, true, true);
7457
7670
  },
@@ -7459,12 +7672,17 @@ function createGlassSwitch(element, options = {}) {
7459
7672
  if (nextOptions.onChange !== void 0) {
7460
7673
  onChangeCallback = nextOptions.onChange;
7461
7674
  }
7675
+ if (nextOptions.itemSelector !== void 0 && nextOptions.itemSelector !== itemSelector) {
7676
+ itemSelector = nextOptions.itemSelector;
7677
+ measureAnchors();
7678
+ }
7462
7679
  if (nextOptions.value !== void 0) {
7680
+ pendingWantedValue = nextOptions.value;
7463
7681
  measureAnchors();
7464
7682
  const foundIndex = anchors.findIndex(
7465
7683
  (anchor) => anchor.value === nextOptions.value
7466
7684
  );
7467
- if (foundIndex >= 0 && foundIndex !== currentIndex) {
7685
+ if (foundIndex >= 0 && (foundIndex !== currentIndex || posX !== anchors[foundIndex].left)) {
7468
7686
  commitActiveIndex(foundIndex, true, false, true);
7469
7687
  }
7470
7688
  }
@@ -7472,6 +7690,7 @@ function createGlassSwitch(element, options = {}) {
7472
7690
  if (Object.keys(glassPatch).length > 0) {
7473
7691
  trackGlass.update({
7474
7692
  ...glassPatch,
7693
+ onEngineChange: void 0,
7475
7694
  pill: true,
7476
7695
  interactive: false,
7477
7696
  draggable: false,
@@ -7512,6 +7731,16 @@ function createGlassSwitch(element, options = {}) {
7512
7731
  trackGlass.destroy();
7513
7732
  if (createdGlider) {
7514
7733
  gliderEl.remove();
7734
+ } else {
7735
+ gliderEl.style.removeProperty("--p");
7736
+ gliderEl.style.removeProperty("transform");
7737
+ gliderEl.style.removeProperty("width");
7738
+ gliderEl.style.removeProperty("left");
7739
+ gliderEl.style.removeProperty("opacity");
7740
+ gliderEl.style.removeProperty("will-change");
7741
+ }
7742
+ if (assignedRole) {
7743
+ element.removeAttribute("role");
7515
7744
  }
7516
7745
  element.classList.remove(
7517
7746
  "lg-switch",
@@ -7521,6 +7750,9 @@ function createGlassSwitch(element, options = {}) {
7521
7750
  );
7522
7751
  element.style.removeProperty("--sweep");
7523
7752
  for (const anchor of anchors) {
7753
+ anchor.element.classList.remove("active");
7754
+ anchor.element.removeAttribute("aria-selected");
7755
+ anchor.element.removeAttribute("aria-pressed");
7524
7756
  anchor.element.style.removeProperty("--lg-switch-coverage");
7525
7757
  anchor.element.style.removeProperty("--lg-switch-hit-start");
7526
7758
  anchor.element.style.removeProperty("--lg-switch-hit-end");
@@ -7574,5 +7806,5 @@ exports.resolveGlassEngine = resolveGlassEngine;
7574
7806
  exports.revokeBlobUrlSafely = revokeBlobUrlSafely;
7575
7807
  exports.stepSpring = stepSpring;
7576
7808
  exports.unregisterManagedElement = unregisterManagedElement;
7577
- //# sourceMappingURL=chunk-ZECDS4SL.cjs.map
7578
- //# sourceMappingURL=chunk-ZECDS4SL.cjs.map
7809
+ //# sourceMappingURL=chunk-2D22LMVV.cjs.map
7810
+ //# sourceMappingURL=chunk-2D22LMVV.cjs.map