@smilodon/core 1.9.1 → 1.9.3

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.umd.js CHANGED
@@ -249,6 +249,10 @@
249
249
  if (poolNode) {
250
250
  poolNode.inUse = false;
251
251
  poolNode.lastUsed = performance.now();
252
+ if (this.pool.length > this.maxSize) {
253
+ this.removePoolNode(poolNode);
254
+ return;
255
+ }
252
256
  // Aggressive cleanup
253
257
  this.reset(poolNode.node);
254
258
  }
@@ -269,12 +273,19 @@
269
273
  }
270
274
  }
271
275
  if (lruIndex >= 0) {
272
- const evicted = this.pool.splice(lruIndex, 1)[0];
273
- // Full cleanup before GC
274
- this.deepCleanup(evicted.node);
276
+ this.removePoolNode(this.pool[lruIndex]);
275
277
  if (this.telemetry)
276
278
  this.evictions++;
279
+ return true;
277
280
  }
281
+ return false;
282
+ }
283
+ removePoolNode(poolNode) {
284
+ const index = this.pool.indexOf(poolNode);
285
+ if (index < 0)
286
+ return;
287
+ const [removed] = this.pool.splice(index, 1);
288
+ this.deepCleanup(removed.node);
278
289
  }
279
290
  /**
280
291
  * Default reset: clear content, remove inline styles, remove attributes
@@ -324,7 +335,8 @@
324
335
  this.maxSize = size;
325
336
  // Evict excess nodes
326
337
  while (this.pool.length > this.maxSize) {
327
- this.evictLRU();
338
+ if (!this.evictLRU())
339
+ break;
328
340
  }
329
341
  }
330
342
  /**
@@ -360,6 +372,8 @@
360
372
  constructor(container, itemsLength, itemGetter, options) {
361
373
  this.measuredHeights = new Map();
362
374
  this.activeNodes = new Map(); // index -> node mapping
375
+ this.destroyed = false;
376
+ this.recycleRafId = 0;
363
377
  this.container = container;
364
378
  this.itemsLength = itemsLength;
365
379
  this.itemGetter = itemGetter;
@@ -445,6 +459,8 @@
445
459
  }
446
460
  }
447
461
  render(startIndex, endIndex, updateNode) {
462
+ if (this.destroyed)
463
+ return;
448
464
  const frag = document.createDocumentFragment();
449
465
  const activeIndices = new Set();
450
466
  for (let i = startIndex; i <= endIndex; i++) {
@@ -453,16 +469,30 @@
453
469
  frag.appendChild(node);
454
470
  activeIndices.add(i);
455
471
  // Measure on appear (deferred)
456
- queueMicrotask(() => this.measureOnAppear(node, i));
472
+ queueMicrotask(() => {
473
+ if (!this.destroyed) {
474
+ this.measureOnAppear(node, i);
475
+ }
476
+ });
457
477
  }
458
478
  // Translate container by cumulative offset of startIndex
459
479
  const topOffset = this.cumulativeOffset(startIndex);
460
480
  this.container.style.transform = `translate3d(0, ${Math.round(topOffset * 100) / 100}px, 0)`;
461
481
  this.container.replaceChildren(frag);
462
482
  // Recycle nodes not in use
463
- requestAnimationFrame(() => this.releaseExcess(activeIndices));
483
+ if (this.recycleRafId) {
484
+ cancelAnimationFrame(this.recycleRafId);
485
+ }
486
+ this.recycleRafId = requestAnimationFrame(() => {
487
+ this.recycleRafId = 0;
488
+ if (!this.destroyed) {
489
+ this.releaseExcess(activeIndices);
490
+ }
491
+ });
464
492
  }
465
493
  measureOnAppear(node, index) {
494
+ if (this.destroyed || index >= this.itemsLength)
495
+ return;
466
496
  const h = node.offsetHeight;
467
497
  const prev = this.measuredHeights.get(index);
468
498
  const threshold = this.options.measurementThreshold ?? 5;
@@ -490,6 +520,16 @@
490
520
  */
491
521
  setItemsLength(newLength) {
492
522
  this.itemsLength = newLength;
523
+ for (const index of Array.from(this.measuredHeights.keys())) {
524
+ if (index >= newLength) {
525
+ this.measuredHeights.delete(index);
526
+ }
527
+ }
528
+ for (const index of Array.from(this.activeNodes.keys())) {
529
+ if (index >= newLength) {
530
+ this.releaseNode(index);
531
+ }
532
+ }
493
533
  if (this.fenwick) {
494
534
  this.fenwick.resize(newLength);
495
535
  }
@@ -506,6 +546,11 @@
506
546
  * Cleanup resources
507
547
  */
508
548
  destroy() {
549
+ this.destroyed = true;
550
+ if (this.recycleRafId) {
551
+ cancelAnimationFrame(this.recycleRafId);
552
+ this.recycleRafId = 0;
553
+ }
509
554
  this.pool.clear();
510
555
  this.activeNodes.clear();
511
556
  this.measuredHeights.clear();
@@ -541,30 +586,18 @@
541
586
  * @returns Component instance
542
587
  */
543
588
  acquire(factory, item, index, context, container) {
544
- const factoryKey = this._getFactoryKey(factory);
589
+ this.release(index);
545
590
  // Try to find an available component in the pool
546
- const pooled = this._findAvailableComponent(factoryKey);
591
+ const pooled = this._findAvailableComponent(factory);
547
592
  let component;
548
593
  if (pooled) {
549
594
  // Reuse pooled component
550
595
  component = pooled.instance;
551
- pooled.inUse = true;
552
- pooled.lastUsedIndex = index;
553
596
  }
554
597
  else {
555
598
  // Create new component
556
599
  try {
557
600
  component = factory(item, index);
558
- // Add to pool if under limit
559
- const pool = this._pool.get(factoryKey) || [];
560
- if (pool.length < this._maxPoolSize) {
561
- pool.push({
562
- instance: component,
563
- inUse: true,
564
- lastUsedIndex: index
565
- });
566
- this._pool.set(factoryKey, pool);
567
- }
568
601
  }
569
602
  catch (error) {
570
603
  console.error(`[CustomOptionPool] Failed to create component:`, error);
@@ -574,9 +607,25 @@
574
607
  // Mount the component
575
608
  try {
576
609
  component.mountOption(container, context);
610
+ if (pooled) {
611
+ pooled.inUse = true;
612
+ pooled.lastUsedIndex = index;
613
+ }
614
+ else {
615
+ this._addToPool(factory, component, index);
616
+ }
577
617
  this._activeComponents.set(index, component);
578
618
  }
579
619
  catch (error) {
620
+ if (pooled) {
621
+ pooled.inUse = false;
622
+ }
623
+ try {
624
+ component.unmountOption();
625
+ }
626
+ catch {
627
+ // ignore cleanup failures after a mount failure
628
+ }
580
629
  console.error(`[CustomOptionPool] Failed to mount component at index ${index}:`, error);
581
630
  throw error;
582
631
  }
@@ -673,18 +722,44 @@
673
722
  /**
674
723
  * Find an available component in the pool
675
724
  */
676
- _findAvailableComponent(factoryKey) {
677
- const pool = this._pool.get(factoryKey);
725
+ _findAvailableComponent(factory) {
726
+ const pool = this._pool.get(factory);
678
727
  if (!pool)
679
728
  return undefined;
680
729
  return pool.find(p => !p.inUse);
681
730
  }
682
- /**
683
- * Generate a unique key for a factory function
684
- */
685
- _getFactoryKey(factory) {
686
- // Use function name or create a symbol
687
- return factory.name || `factory_${factory.toString().slice(0, 50)}`;
731
+ _addToPool(factory, component, index) {
732
+ while (this._getTotalPooled() >= this._maxPoolSize) {
733
+ if (!this._evictAvailableComponent())
734
+ return;
735
+ }
736
+ const pool = this._pool.get(factory) || [];
737
+ pool.push({
738
+ instance: component,
739
+ inUse: true,
740
+ lastUsedIndex: index
741
+ });
742
+ this._pool.set(factory, pool);
743
+ }
744
+ _evictAvailableComponent() {
745
+ for (const [factory, pool] of this._pool.entries()) {
746
+ const index = pool.findIndex(p => !p.inUse);
747
+ if (index < 0)
748
+ continue;
749
+ pool.splice(index, 1);
750
+ if (pool.length === 0) {
751
+ this._pool.delete(factory);
752
+ }
753
+ return true;
754
+ }
755
+ return false;
756
+ }
757
+ _getTotalPooled() {
758
+ let total = 0;
759
+ for (const pool of this._pool.values()) {
760
+ total += pool.length;
761
+ }
762
+ return total;
688
763
  }
689
764
  }
690
765
 
@@ -718,6 +793,7 @@
718
793
  const value = this._config.getValue(item);
719
794
  const label = this._config.getLabel(item);
720
795
  const isDisabled = this._config.getDisabled ? this._config.getDisabled(item) : false;
796
+ this.unmount(index);
721
797
  // Determine if this is a custom component or lightweight option
722
798
  const hasCustomComponent = extendedItem.optionComponent && typeof extendedItem.optionComponent === 'function';
723
799
  if (hasCustomComponent) {
@@ -908,7 +984,7 @@
908
984
 
909
985
  class NativeSelectElement extends HTMLElement {
910
986
  static get observedAttributes() {
911
- return ['placement', 'strategy', 'portal'];
987
+ return ["placement", "strategy", "portal"];
912
988
  }
913
989
  constructor() {
914
990
  super();
@@ -919,22 +995,23 @@
919
995
  this._selectedItems = new Map(); // index -> item
920
996
  this._activeIndex = -1;
921
997
  this._multi = false;
922
- this._typeBuffer = '';
923
- this._shadow = this.attachShadow({ mode: 'open' });
924
- this._listRoot = document.createElement('div');
925
- this._listRoot.setAttribute('role', 'listbox');
926
- this._listRoot.setAttribute('tabindex', '0');
998
+ this._typeBuffer = "";
999
+ this._shadow = this.attachShadow({ mode: "open" });
1000
+ this._listRoot = document.createElement("div");
1001
+ this._listRoot.setAttribute("role", "listbox");
1002
+ this._listRoot.setAttribute("tabindex", "0");
927
1003
  this._shadow.appendChild(this._listRoot);
928
1004
  // Live region for screen reader announcements
929
- this._liveRegion = document.createElement('div');
930
- this._liveRegion.setAttribute('role', 'status');
931
- this._liveRegion.setAttribute('aria-live', 'polite');
932
- this._liveRegion.style.cssText = 'position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;';
1005
+ this._liveRegion = document.createElement("div");
1006
+ this._liveRegion.setAttribute("role", "status");
1007
+ this._liveRegion.setAttribute("aria-live", "polite");
1008
+ this._liveRegion.style.cssText =
1009
+ "position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;";
933
1010
  this._shadow.appendChild(this._liveRegion);
934
1011
  this._helpers = createRendererHelpers((item, index) => this._onSelect(item, index));
935
1012
  // Delegated click
936
- this._listRoot.addEventListener('click', (e) => {
937
- const el = e.target.closest('[data-selectable]');
1013
+ this._listRoot.addEventListener("click", (e) => {
1014
+ const el = e.target.closest("[data-selectable]");
938
1015
  if (!el)
939
1016
  return;
940
1017
  const idx = Number(el.dataset.index);
@@ -942,28 +1019,33 @@
942
1019
  this._onSelect(item, idx);
943
1020
  });
944
1021
  // Keyboard navigation
945
- this._listRoot.addEventListener('keydown', (e) => this._onKeydown(e));
1022
+ this._listRoot.addEventListener("keydown", (e) => this._onKeydown(e));
946
1023
  }
947
1024
  connectedCallback() {
948
1025
  // Initialize ARIA roles and open event
949
- this._listRoot.setAttribute('role', 'listbox');
950
- this._listRoot.setAttribute('aria-label', 'Options list');
1026
+ this._listRoot.setAttribute("role", "listbox");
1027
+ this._listRoot.setAttribute("aria-label", "Options list");
951
1028
  if (this._multi)
952
- this._listRoot.setAttribute('aria-multiselectable', 'true');
1029
+ this._listRoot.setAttribute("aria-multiselectable", "true");
953
1030
  this._initializeOptionRenderer();
954
- this._emit('open', {});
1031
+ this._emit("open", {});
955
1032
  }
956
1033
  disconnectedCallback() {
957
- this._emit('close', {});
1034
+ this._emit("close", {});
958
1035
  // Cleanup unified renderer
959
1036
  if (this._unifiedRenderer) {
960
1037
  this._unifiedRenderer.unmountAll();
961
1038
  }
1039
+ this._virtualizer?.destroy();
1040
+ this._virtualizer = undefined;
962
1041
  // Cleanup: remove listeners if any were added outside constructor
963
1042
  if (this._typeTimeout)
964
1043
  window.clearTimeout(this._typeTimeout);
1044
+ if (this._announceTimeout)
1045
+ window.clearTimeout(this._announceTimeout);
965
1046
  }
966
1047
  _initializeOptionRenderer() {
1048
+ this._unifiedRenderer?.unmountAll();
967
1049
  const getValue = (item) => item?.value ?? item;
968
1050
  const getLabel = (item) => item?.label ?? String(item);
969
1051
  const getDisabled = (item) => item?.disabled ?? false;
@@ -979,39 +1061,43 @@
979
1061
  },
980
1062
  onCustomEvent: (index, eventName, data) => {
981
1063
  // Emit custom events from option components
982
- this.dispatchEvent(new CustomEvent('option:custom-event', {
1064
+ this.dispatchEvent(new CustomEvent("option:custom-event", {
983
1065
  detail: { index, eventName, data },
984
1066
  bubbles: true,
985
- composed: true
1067
+ composed: true,
986
1068
  }));
987
1069
  },
988
1070
  onError: (index, error) => {
989
1071
  console.error(`[NativeSelect] Error in option ${index}:`, error);
990
- this.dispatchEvent(new CustomEvent('option:mount-error', {
1072
+ this.dispatchEvent(new CustomEvent("option:mount-error", {
991
1073
  detail: { index, error },
992
1074
  bubbles: true,
993
- composed: true
1075
+ composed: true,
994
1076
  }));
995
- }
1077
+ },
996
1078
  };
997
1079
  this._unifiedRenderer = new OptionRenderer(rendererConfig);
998
1080
  }
999
1081
  attributeChangedCallback(name, _oldValue, newValue) {
1000
1082
  switch (name) {
1001
- case 'placement':
1002
- this._options.placement = (newValue ?? undefined);
1083
+ case "placement":
1084
+ this._options.placement = (newValue ??
1085
+ undefined);
1003
1086
  break;
1004
- case 'strategy':
1005
- this._options.strategy = (newValue ?? undefined);
1087
+ case "strategy":
1088
+ this._options.strategy = (newValue ??
1089
+ undefined);
1006
1090
  break;
1007
- case 'portal':
1008
- this._options.portal = newValue === 'true' ? true : newValue === 'false' ? false : undefined;
1091
+ case "portal":
1092
+ this._options.portal =
1093
+ newValue === "true" ? true : newValue === "false" ? false : undefined;
1009
1094
  break;
1010
1095
  }
1011
1096
  }
1012
1097
  set items(items) {
1013
1098
  this._items = items ?? [];
1014
1099
  // initialize virtualizer with estimated height (default 48) and buffer
1100
+ this._virtualizer?.destroy();
1015
1101
  this._virtualizer = new Virtualizer(this._listRoot, this._items.length, (i) => this._items[i], { estimatedItemHeight: 48, buffer: 5 });
1016
1102
  this.render();
1017
1103
  }
@@ -1021,10 +1107,10 @@
1021
1107
  set multi(value) {
1022
1108
  this._multi = value;
1023
1109
  if (value) {
1024
- this._listRoot.setAttribute('aria-multiselectable', 'true');
1110
+ this._listRoot.setAttribute("aria-multiselectable", "true");
1025
1111
  }
1026
1112
  else {
1027
- this._listRoot.removeAttribute('aria-multiselectable');
1113
+ this._listRoot.removeAttribute("aria-multiselectable");
1028
1114
  }
1029
1115
  }
1030
1116
  get multi() {
@@ -1060,7 +1146,7 @@
1060
1146
  * For multi-select: adds to selection if not already selected
1061
1147
  */
1062
1148
  setValue(value) {
1063
- if (value === null || value === undefined || value === '') {
1149
+ if (value === null || value === undefined || value === "") {
1064
1150
  // Clear selection
1065
1151
  this._selectedSet.clear();
1066
1152
  this._selectedItems.clear();
@@ -1069,8 +1155,8 @@
1069
1155
  return;
1070
1156
  }
1071
1157
  // Find item by value
1072
- const index = this._items.findIndex(item => {
1073
- if (typeof item === 'object' && item !== null && 'value' in item) {
1158
+ const index = this._items.findIndex((item) => {
1159
+ if (typeof item === "object" && item !== null && "value" in item) {
1074
1160
  return item.value === value;
1075
1161
  }
1076
1162
  return item === value;
@@ -1096,7 +1182,7 @@
1096
1182
  // Optimized: single-pass iteration, no intermediate arrays
1097
1183
  const values = [];
1098
1184
  for (const item of this._selectedItems.values()) {
1099
- if (typeof item === 'object' && item !== null && 'value' in item) {
1185
+ if (typeof item === "object" && item !== null && "value" in item) {
1100
1186
  values.push(item.value);
1101
1187
  }
1102
1188
  else {
@@ -1111,16 +1197,16 @@
1111
1197
  const scrollTop = this.scrollTop || 0;
1112
1198
  // Update aria-activedescendant
1113
1199
  if (this._activeIndex >= 0) {
1114
- this._listRoot.setAttribute('aria-activedescendant', `option-${this._activeIndex}`);
1200
+ this._listRoot.setAttribute("aria-activedescendant", `option-${this._activeIndex}`);
1115
1201
  }
1116
1202
  else {
1117
- this._listRoot.removeAttribute('aria-activedescendant');
1203
+ this._listRoot.removeAttribute("aria-activedescendant");
1118
1204
  }
1119
1205
  // Check if any items have custom components
1120
- const hasCustomComponents = this._items.some(item => typeof item === 'object' &&
1206
+ const hasCustomComponents = this._items.some((item) => typeof item === "object" &&
1121
1207
  item !== null &&
1122
- Object.prototype.hasOwnProperty.call(item, 'optionComponent') &&
1123
- typeof item.optionComponent === 'function');
1208
+ Object.prototype.hasOwnProperty.call(item, "optionComponent") &&
1209
+ typeof item.optionComponent === "function");
1124
1210
  // Use unified renderer if we have custom components
1125
1211
  if (hasCustomComponents && this._unifiedRenderer) {
1126
1212
  this._listRoot.replaceChildren(); // Clear existing content
@@ -1129,7 +1215,7 @@
1129
1215
  const item = this._items[i];
1130
1216
  const isSelected = this._selectedSet.has(i);
1131
1217
  const isFocused = this._activeIndex === i;
1132
- const optionElement = this._unifiedRenderer.render(item, i, isSelected, isFocused, `native-${this.getAttribute('id') || 'default'}`);
1218
+ const optionElement = this._unifiedRenderer.render(item, i, isSelected, isFocused, `native-${this.getAttribute("id") || "default"}`);
1133
1219
  frag.appendChild(optionElement);
1134
1220
  }
1135
1221
  this._listRoot.appendChild(frag);
@@ -1146,14 +1232,14 @@
1146
1232
  node.replaceChildren(el);
1147
1233
  }
1148
1234
  else if (optionTemplate) {
1149
- const wrapper = document.createElement('div');
1235
+ const wrapper = document.createElement("div");
1150
1236
  wrapper.innerHTML = optionTemplate(item, i);
1151
1237
  const el = wrapper.firstElementChild;
1152
1238
  node.replaceChildren(el ?? document.createTextNode(String(item)));
1153
1239
  }
1154
1240
  else {
1155
1241
  // Handle {label, value} objects or primitives
1156
- const displayText = (typeof item === 'object' && item !== null && 'label' in item)
1242
+ const displayText = typeof item === "object" && item !== null && "label" in item
1157
1243
  ? String(item.label)
1158
1244
  : String(item);
1159
1245
  node.textContent = displayText;
@@ -1166,9 +1252,9 @@
1166
1252
  const item = this._items[i];
1167
1253
  if (optionRenderer) {
1168
1254
  const el = optionRenderer(item, i, this._helpers);
1169
- if (!el.hasAttribute('data-selectable')) {
1170
- el.setAttribute('data-selectable', '');
1171
- el.setAttribute('data-index', String(i));
1255
+ if (!el.hasAttribute("data-selectable")) {
1256
+ el.setAttribute("data-selectable", "");
1257
+ el.setAttribute("data-index", String(i));
1172
1258
  }
1173
1259
  this._applyOptionAttrs(el, i);
1174
1260
  frag.appendChild(el);
@@ -1181,14 +1267,14 @@
1181
1267
  return; // rendering complete
1182
1268
  }
1183
1269
  else {
1184
- const el = document.createElement('div');
1270
+ const el = document.createElement("div");
1185
1271
  // Handle {label, value} objects or primitives
1186
- const displayText = (typeof item === 'object' && item !== null && 'label' in item)
1272
+ const displayText = typeof item === "object" && item !== null && "label" in item
1187
1273
  ? String(item.label)
1188
1274
  : String(item);
1189
1275
  el.textContent = displayText;
1190
- el.setAttribute('data-selectable', '');
1191
- el.setAttribute('data-index', String(i));
1276
+ el.setAttribute("data-selectable", "");
1277
+ el.setAttribute("data-index", String(i));
1192
1278
  this._applyOptionAttrs(el, i);
1193
1279
  frag.appendChild(el);
1194
1280
  }
@@ -1196,13 +1282,13 @@
1196
1282
  this._listRoot.replaceChildren(frag);
1197
1283
  }
1198
1284
  _applyOptionAttrs(node, index) {
1199
- node.setAttribute('role', 'option');
1285
+ node.setAttribute("role", "option");
1200
1286
  node.id = `option-${index}`;
1201
1287
  if (this._selectedSet.has(index)) {
1202
- node.setAttribute('aria-selected', 'true');
1288
+ node.setAttribute("aria-selected", "true");
1203
1289
  }
1204
1290
  else {
1205
- node.setAttribute('aria-selected', 'false');
1291
+ node.setAttribute("aria-selected", "false");
1206
1292
  }
1207
1293
  }
1208
1294
  _applyAriaToAll() {
@@ -1240,13 +1326,13 @@
1240
1326
  const selected = this._selectedSet.has(index);
1241
1327
  const value = item?.value ?? item;
1242
1328
  const label = item?.label ?? String(item);
1243
- this._emit('select', {
1329
+ this._emit("select", {
1244
1330
  item,
1245
1331
  index,
1246
1332
  value,
1247
1333
  label,
1248
1334
  selected,
1249
- multi: this._multi
1335
+ multi: this._multi,
1250
1336
  });
1251
1337
  // Optimized: single-pass iteration for change event data
1252
1338
  const selectedItems = [];
@@ -1256,50 +1342,50 @@
1256
1342
  selectedValues.push(item?.value ?? item);
1257
1343
  }
1258
1344
  // Emit 'change' event for better React compatibility
1259
- this._emit('change', {
1345
+ this._emit("change", {
1260
1346
  selectedItems,
1261
1347
  selectedValues,
1262
- selectedIndices: Array.from(this._selectedSet)
1348
+ selectedIndices: Array.from(this._selectedSet),
1263
1349
  });
1264
1350
  this._announce(`Selected ${label}`);
1265
1351
  }
1266
1352
  _onKeydown(e) {
1267
1353
  switch (e.key) {
1268
- case 'ArrowDown':
1354
+ case "ArrowDown":
1269
1355
  e.preventDefault();
1270
1356
  this._moveActive(1);
1271
1357
  break;
1272
- case 'ArrowUp':
1358
+ case "ArrowUp":
1273
1359
  e.preventDefault();
1274
1360
  this._moveActive(-1);
1275
1361
  break;
1276
- case 'Home':
1362
+ case "Home":
1277
1363
  e.preventDefault();
1278
1364
  this._setActive(0);
1279
1365
  break;
1280
- case 'End':
1366
+ case "End":
1281
1367
  e.preventDefault();
1282
1368
  this._setActive(this._items.length - 1);
1283
1369
  break;
1284
- case 'PageDown':
1370
+ case "PageDown":
1285
1371
  e.preventDefault();
1286
1372
  this._moveActive(10);
1287
1373
  break;
1288
- case 'PageUp':
1374
+ case "PageUp":
1289
1375
  e.preventDefault();
1290
1376
  this._moveActive(-10);
1291
1377
  break;
1292
- case 'Enter':
1293
- case ' ':
1378
+ case "Enter":
1379
+ case " ":
1294
1380
  e.preventDefault();
1295
1381
  if (this._activeIndex >= 0) {
1296
1382
  const item = this._items[this._activeIndex];
1297
1383
  this._onSelect(item, this._activeIndex);
1298
1384
  }
1299
1385
  break;
1300
- case 'Escape':
1386
+ case "Escape":
1301
1387
  e.preventDefault();
1302
- this._emit('close', {});
1388
+ this._emit("close", {});
1303
1389
  break;
1304
1390
  default:
1305
1391
  // Type-ahead buffer
@@ -1321,14 +1407,14 @@
1321
1407
  }
1322
1408
  _scrollToActive() {
1323
1409
  const el = this._shadow.getElementById(`option-${this._activeIndex}`);
1324
- el?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
1410
+ el?.scrollIntoView({ block: "nearest", inline: "nearest" });
1325
1411
  }
1326
1412
  _onType(char) {
1327
1413
  if (this._typeTimeout)
1328
1414
  window.clearTimeout(this._typeTimeout);
1329
1415
  this._typeBuffer += char.toLowerCase();
1330
1416
  this._typeTimeout = window.setTimeout(() => {
1331
- this._typeBuffer = '';
1417
+ this._typeBuffer = "";
1332
1418
  }, 400);
1333
1419
  // Find first matching item
1334
1420
  const match = this._items.findIndex((item) => String(item).toLowerCase().startsWith(this._typeBuffer));
@@ -1339,9 +1425,12 @@
1339
1425
  _announce(msg) {
1340
1426
  if (this._liveRegion) {
1341
1427
  this._liveRegion.textContent = msg;
1342
- setTimeout(() => {
1428
+ if (this._announceTimeout)
1429
+ window.clearTimeout(this._announceTimeout);
1430
+ this._announceTimeout = window.setTimeout(() => {
1431
+ this._announceTimeout = undefined;
1343
1432
  if (this._liveRegion)
1344
- this._liveRegion.textContent = '';
1433
+ this._liveRegion.textContent = "";
1345
1434
  }, 1000);
1346
1435
  }
1347
1436
  }
@@ -1350,7 +1439,9 @@
1350
1439
  this._listRoot.focus();
1351
1440
  }
1352
1441
  }
1353
- customElements.define('smilodon-select', NativeSelectElement);
1442
+ if (!customElements.get("smilodon-select")) {
1443
+ customElements.define("smilodon-select", NativeSelectElement);
1444
+ }
1354
1445
 
1355
1446
  /**
1356
1447
  * Global Configuration System for Select Components
@@ -2124,6 +2215,8 @@
2124
2215
  return this._classMap;
2125
2216
  }
2126
2217
  set classMap(map) {
2218
+ if (this._areClassMapsEqual(this._classMap, map))
2219
+ return;
2127
2220
  this._classMap = map;
2128
2221
  this._setGlobalStylesMirroring(Boolean(this._optionRenderer || map || this._groupHeaderRenderer));
2129
2222
  this._track('style', 'classMapChanged', {
@@ -2143,6 +2236,8 @@
2143
2236
  return this._groupHeaderRenderer;
2144
2237
  }
2145
2238
  set groupHeaderRenderer(renderer) {
2239
+ if (this._groupHeaderRenderer === renderer)
2240
+ return;
2146
2241
  this._groupHeaderRenderer = renderer;
2147
2242
  this._setGlobalStylesMirroring(Boolean(this._optionRenderer || this._classMap || renderer));
2148
2243
  this._track('style', 'groupHeaderRendererChanged', { enabled: Boolean(renderer) });
@@ -2166,6 +2261,9 @@
2166
2261
  this._globalStylesContainer = null;
2167
2262
  this._themeContextObserver = null;
2168
2263
  this._globalStylesSyncToken = 0;
2264
+ this._asyncGeneration = 0;
2265
+ this._lifecycleTimers = new Set();
2266
+ this._lifecycleRafs = new Set();
2169
2267
  this._tracking = { events: [], styles: [], limitations: [] };
2170
2268
  this._suppressBlurClose = false;
2171
2269
  this._renderCycleId = 0;
@@ -2179,6 +2277,41 @@
2179
2277
  startScrollLeft: 0,
2180
2278
  };
2181
2279
  this._liftedAncestors = [];
2280
+ this._onDocumentPointerDown = (e) => {
2281
+ const path = (e.composedPath && e.composedPath()) || [];
2282
+ let clickedInside = false;
2283
+ for (const node of path) {
2284
+ if (node === this || node === this._container) {
2285
+ clickedInside = true;
2286
+ break;
2287
+ }
2288
+ if (node instanceof Node) {
2289
+ try {
2290
+ if (this._shadow && this._shadow.contains(node)) {
2291
+ clickedInside = true;
2292
+ break;
2293
+ }
2294
+ }
2295
+ catch (err) {
2296
+ // ignore
2297
+ }
2298
+ }
2299
+ if (node instanceof Element) {
2300
+ try {
2301
+ if (node.matches('[data-sm-selectable], [data-selectable], [data-sm-state], .input-container, .select-container, .dropdown-arrow-container, .clear-control-button')) {
2302
+ clickedInside = true;
2303
+ break;
2304
+ }
2305
+ }
2306
+ catch (err) {
2307
+ // ignore
2308
+ }
2309
+ }
2310
+ }
2311
+ if (!clickedInside) {
2312
+ this._handleClose();
2313
+ }
2314
+ };
2182
2315
  this._shadow = this.attachShadow({ mode: 'open' });
2183
2316
  this._uniqueId = `enhanced-select-${Math.random().toString(36).substr(2, 9)}`;
2184
2317
  this._rendererHelpers = this._buildRendererHelpers();
@@ -2225,13 +2358,18 @@
2225
2358
  connectedCallback() {
2226
2359
  // register instance
2227
2360
  EnhancedSelect._instances.add(this);
2361
+ this._connectionController?.abort();
2362
+ this._connectionController = new AbortController();
2363
+ document.addEventListener('pointerdown', this._onDocumentPointerDown, {
2364
+ signal: this._connectionController.signal,
2365
+ });
2228
2366
  // WORKAROUND: Force display style on host element for Angular compatibility
2229
2367
  // Angular's rendering seems to not apply :host styles correctly in some cases
2230
2368
  // Must be done in connectedCallback when element is attached to DOM
2231
2369
  this.style.display = 'block';
2232
2370
  // Sync direction attribute (must be in connectedCallback, not constructor)
2233
2371
  this._syncDirectionConfig();
2234
- if (this._optionRenderer) {
2372
+ if (this._optionRenderer || this._classMap || this._groupHeaderRenderer) {
2235
2373
  this._setGlobalStylesMirroring(true);
2236
2374
  }
2237
2375
  // Load initial data if server-side is enabled
@@ -2252,6 +2390,10 @@
2252
2390
  disconnectedCallback() {
2253
2391
  // unregister instance
2254
2392
  EnhancedSelect._instances.delete(this);
2393
+ this._connectionController?.abort();
2394
+ this._connectionController = undefined;
2395
+ this._asyncGeneration += 1;
2396
+ this._clearLifecycleTasks();
2255
2397
  // Cleanup observers
2256
2398
  this._resizeObserver?.disconnect();
2257
2399
  this._intersectionObserver?.disconnect();
@@ -2271,8 +2413,8 @@
2271
2413
  }
2272
2414
  _setGlobalStylesMirroring(enabled) {
2273
2415
  if (this._mirrorGlobalStylesForCustomOptions === enabled) {
2274
- if (enabled) {
2275
- this._mirrorDocumentStylesIntoShadow();
2416
+ if (enabled && this.isConnected && !this._globalStylesObserver) {
2417
+ this._setupGlobalStylesMirroring();
2276
2418
  }
2277
2419
  return;
2278
2420
  }
@@ -2285,6 +2427,36 @@
2285
2427
  this._teardownGlobalStylesMirroring();
2286
2428
  }
2287
2429
  }
2430
+ _setLifecycleTimeout(callback, delay = 0) {
2431
+ const id = window.setTimeout(() => {
2432
+ this._lifecycleTimers.delete(id);
2433
+ if (!this.isConnected)
2434
+ return;
2435
+ callback();
2436
+ }, delay);
2437
+ this._lifecycleTimers.add(id);
2438
+ return id;
2439
+ }
2440
+ _requestLifecycleFrame(callback) {
2441
+ const id = requestAnimationFrame(() => {
2442
+ this._lifecycleRafs.delete(id);
2443
+ if (!this.isConnected)
2444
+ return;
2445
+ callback();
2446
+ });
2447
+ this._lifecycleRafs.add(id);
2448
+ return id;
2449
+ }
2450
+ _clearLifecycleTasks() {
2451
+ for (const id of this._lifecycleTimers) {
2452
+ clearTimeout(id);
2453
+ }
2454
+ this._lifecycleTimers.clear();
2455
+ for (const id of this._lifecycleRafs) {
2456
+ cancelAnimationFrame(id);
2457
+ }
2458
+ this._lifecycleRafs.clear();
2459
+ }
2288
2460
  _setupGlobalStylesMirroring() {
2289
2461
  if (typeof document === 'undefined')
2290
2462
  return;
@@ -2396,23 +2568,64 @@
2396
2568
  return this._buildScopedStyleElement(node.textContent || '', String(index));
2397
2569
  }
2398
2570
  if (node instanceof HTMLLinkElement && node.href) {
2399
- try {
2400
- const response = await fetch(node.href, {
2401
- credentials: node.crossOrigin === 'use-credentials' ? 'include' : 'same-origin',
2402
- mode: 'cors',
2403
- });
2404
- if (!response.ok) {
2405
- return null;
2406
- }
2407
- const cssText = await response.text();
2408
- return this._buildScopedStyleElement(cssText, String(index));
2571
+ const credentials = node.crossOrigin === 'use-credentials' ? 'include' : 'same-origin';
2572
+ const cacheKey = `${node.href}|${credentials}`;
2573
+ let cacheEntry = EnhancedSelect._mirroredStylesheetTextCache.get(cacheKey);
2574
+ if (!cacheEntry) {
2575
+ cacheEntry = {
2576
+ promise: fetch(node.href, {
2577
+ credentials,
2578
+ mode: 'cors',
2579
+ })
2580
+ .then((response) => {
2581
+ if (!response.ok)
2582
+ return null;
2583
+ return response.text();
2584
+ })
2585
+ .catch(() => null),
2586
+ lastUsed: Date.now(),
2587
+ };
2588
+ EnhancedSelect._mirroredStylesheetTextCache.set(cacheKey, cacheEntry);
2589
+ EnhancedSelect._pruneMirroredStylesheetTextCache();
2590
+ }
2591
+ else {
2592
+ cacheEntry.lastUsed = Date.now();
2409
2593
  }
2410
- catch (_error) {
2594
+ const cssText = await cacheEntry.promise;
2595
+ if (cssText === null) {
2596
+ EnhancedSelect._mirroredStylesheetTextCache.delete(cacheKey);
2411
2597
  return null;
2412
2598
  }
2599
+ return this._buildScopedStyleElement(cssText, String(index));
2413
2600
  }
2414
2601
  return null;
2415
2602
  }
2603
+ static _pruneMirroredStylesheetTextCache() {
2604
+ while (EnhancedSelect._mirroredStylesheetTextCache.size > EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT) {
2605
+ let lruKey;
2606
+ let oldest = Infinity;
2607
+ for (const [key, entry] of EnhancedSelect._mirroredStylesheetTextCache.entries()) {
2608
+ if (entry.lastUsed < oldest) {
2609
+ oldest = entry.lastUsed;
2610
+ lruKey = key;
2611
+ }
2612
+ }
2613
+ if (!lruKey)
2614
+ return;
2615
+ EnhancedSelect._mirroredStylesheetTextCache.delete(lruKey);
2616
+ }
2617
+ }
2618
+ _areClassMapsEqual(left, right) {
2619
+ if (left === right)
2620
+ return true;
2621
+ if (!left || !right)
2622
+ return false;
2623
+ const leftKeys = Object.keys(left);
2624
+ const rightKeys = Object.keys(right);
2625
+ if (leftKeys.length !== rightKeys.length)
2626
+ return false;
2627
+ return leftKeys.every((key) => left[key] === right[key]);
2628
+ }
2416
2629
  _buildScopedStyleElement(cssText, id) {
2417
2630
  const scopedCss = this._scopeMirroredCssText(cssText);
2418
2631
  if (!scopedCss.trim())
@@ -2662,6 +2875,8 @@
2662
2875
  }
2663
2876
  _syncStyleConfigVariables() {
2664
2877
  const styles = this._config.styles;
2878
+ if (!styles)
2879
+ return;
2665
2880
  this._applyStyleVariableMap(styles.option, {
2666
2881
  background: '--select-option-bg',
2667
2882
  backgroundColor: '--select-option-bg',
@@ -4692,7 +4907,7 @@
4692
4907
  return;
4693
4908
  }
4694
4909
  // Delay to allow option click/focus transitions
4695
- setTimeout(() => {
4910
+ this._setLifecycleTimeout(() => {
4696
4911
  if (this._suppressBlurClose) {
4697
4912
  // another pointerdown inside options is in progress; keep open
4698
4913
  return;
@@ -4717,7 +4932,7 @@
4717
4932
  // sufficient.
4718
4933
  this._optionsContainer.addEventListener('pointerdown', () => {
4719
4934
  this._suppressBlurClose = true;
4720
- setTimeout(() => {
4935
+ this._setLifecycleTimeout(() => {
4721
4936
  this._suppressBlurClose = false;
4722
4937
  }, 150); // Increased timeout to ensure click finishes before blur checks
4723
4938
  });
@@ -4752,42 +4967,6 @@
4752
4967
  this._optionsContainer.addEventListener('click', handleOptionEvent);
4753
4968
  // Keyboard navigation
4754
4969
  this._input.addEventListener('keydown', (e) => this._handleKeydown(e));
4755
- // Click outside to close — robust detection across shadow DOM and custom renderers
4756
- document.addEventListener('pointerdown', (e) => {
4757
- const path = (e.composedPath && e.composedPath()) || [];
4758
- let clickedInside = false;
4759
- for (const node of path) {
4760
- if (node === this || node === this._container) {
4761
- clickedInside = true;
4762
- break;
4763
- }
4764
- if (node instanceof Node) {
4765
- try {
4766
- if (this._shadow && this._shadow.contains(node)) {
4767
- clickedInside = true;
4768
- break;
4769
- }
4770
- }
4771
- catch (err) {
4772
- // ignore
4773
- }
4774
- }
4775
- if (node instanceof Element) {
4776
- try {
4777
- if (node.matches('[data-sm-selectable], [data-selectable], [data-sm-state], .input-container, .select-container, .dropdown-arrow-container, .clear-control-button')) {
4778
- clickedInside = true;
4779
- break;
4780
- }
4781
- }
4782
- catch (err) {
4783
- // ignore
4784
- }
4785
- }
4786
- }
4787
- if (!clickedInside) {
4788
- this._handleClose();
4789
- }
4790
- });
4791
4970
  }
4792
4971
  _initializeObservers() {
4793
4972
  // Disconnect existing observer if any
@@ -4813,8 +4992,11 @@
4813
4992
  return;
4814
4993
  }
4815
4994
  this._setBusy(true);
4995
+ const generation = ++this._asyncGeneration;
4816
4996
  try {
4817
4997
  const items = await this._config.serverSide.fetchSelectedItems(this._config.serverSide.initialSelectedValues);
4998
+ if (generation !== this._asyncGeneration || !this.isConnected)
4999
+ return;
4818
5000
  // Add to state
4819
5001
  items.forEach((item, index) => {
4820
5002
  this._state.selectedItems.set(index, item);
@@ -4823,10 +5005,14 @@
4823
5005
  this._updateInputDisplay();
4824
5006
  }
4825
5007
  catch (error) {
5008
+ if (generation !== this._asyncGeneration || !this.isConnected)
5009
+ return;
4826
5010
  this._handleError(error);
4827
5011
  }
4828
5012
  finally {
4829
- this._setBusy(false);
5013
+ if (generation === this._asyncGeneration && this.isConnected) {
5014
+ this._setBusy(false);
5015
+ }
4830
5016
  }
4831
5017
  }
4832
5018
  _handleOpen() {
@@ -4859,9 +5045,9 @@
4859
5045
  // Scroll to selected if configured
4860
5046
  if (this._config.scrollToSelected.enabled) {
4861
5047
  // Use requestAnimationFrame for better timing after render
4862
- requestAnimationFrame(() => {
5048
+ this._requestLifecycleFrame(() => {
4863
5049
  // Double RAF to ensure layout is complete
4864
- requestAnimationFrame(() => {
5050
+ this._requestLifecycleFrame(() => {
4865
5051
  this._scrollToSelected();
4866
5052
  });
4867
5053
  });
@@ -4983,6 +5169,9 @@
4983
5169
  if (!this._isPerfEnabled())
4984
5170
  return;
4985
5171
  performance.measure(name, start, end);
5172
+ performance.clearMarks(start);
5173
+ performance.clearMarks(end);
5174
+ performance.clearMeasures(name);
4986
5175
  }
4987
5176
  _markOpenStart() {
4988
5177
  if (!this._isPerfEnabled())
@@ -5080,7 +5269,7 @@
5080
5269
  this._state.lastNotifiedQuery = query;
5081
5270
  this._state.lastNotifiedResultCount = count;
5082
5271
  // Use setTimeout to avoid synchronous state updates during render
5083
- setTimeout(() => {
5272
+ this._setLifecycleTimeout(() => {
5084
5273
  this._emit('search', { query, results: filteredItems, count });
5085
5274
  this._config.callbacks.onSearch?.(query);
5086
5275
  }, 0);
@@ -5373,7 +5562,7 @@
5373
5562
  _announce(message) {
5374
5563
  if (this._liveRegion) {
5375
5564
  this._liveRegion.textContent = message;
5376
- setTimeout(() => {
5565
+ this._setLifecycleTimeout(() => {
5377
5566
  if (this._liveRegion)
5378
5567
  this._liveRegion.textContent = '';
5379
5568
  }, 1000);
@@ -5568,7 +5757,7 @@
5568
5757
  // Add fade-out animation
5569
5758
  this._optionsContainer.style.opacity = '0';
5570
5759
  this._optionsContainer.style.transition = 'opacity 0.15s ease-out';
5571
- setTimeout(() => {
5760
+ this._setLifecycleTimeout(() => {
5572
5761
  this._renderOptions();
5573
5762
  // Fade back in
5574
5763
  this._optionsContainer.style.opacity = '1';
@@ -5835,8 +6024,10 @@
5835
6024
  return this._optionRenderer;
5836
6025
  }
5837
6026
  set optionRenderer(renderer) {
6027
+ if (this._optionRenderer === renderer)
6028
+ return;
5838
6029
  this._optionRenderer = renderer;
5839
- this._setGlobalStylesMirroring(Boolean(renderer || this._classMap));
6030
+ this._setGlobalStylesMirroring(Boolean(renderer || this._classMap || this._groupHeaderRenderer));
5840
6031
  this._track('style', 'optionRendererChanged', { enabled: Boolean(renderer) });
5841
6032
  this._renderOptions();
5842
6033
  }
@@ -5865,7 +6056,7 @@
5865
6056
  // new ones simply appear below.
5866
6057
  this._dropdown.scrollTop = targetScrollTop;
5867
6058
  // Ensure it sticks after layout
5868
- requestAnimationFrame(() => {
6059
+ this._requestLifecycleFrame(() => {
5869
6060
  if (this._dropdown) {
5870
6061
  this._dropdown.scrollTop = targetScrollTop;
5871
6062
  }
@@ -5938,8 +6129,11 @@
5938
6129
  if (!this._config.serverSide.fetchSelectedItems)
5939
6130
  return;
5940
6131
  this._setBusy(true);
6132
+ const generation = ++this._asyncGeneration;
5941
6133
  try {
5942
6134
  const items = await this._config.serverSide.fetchSelectedItems(values);
6135
+ if (generation !== this._asyncGeneration || !this.isConnected)
6136
+ return;
5943
6137
  this._state.selectedIndices.clear();
5944
6138
  this._state.selectedItems.clear();
5945
6139
  items.forEach((item, index) => {
@@ -5957,10 +6151,14 @@
5957
6151
  }
5958
6152
  }
5959
6153
  catch (error) {
6154
+ if (generation !== this._asyncGeneration || !this.isConnected)
6155
+ return;
5960
6156
  this._handleError(error);
5961
6157
  }
5962
6158
  finally {
5963
- this._setBusy(false);
6159
+ if (generation === this._asyncGeneration && this.isConnected) {
6160
+ this._setBusy(false);
6161
+ }
5964
6162
  }
5965
6163
  }
5966
6164
  /**
@@ -6076,7 +6274,13 @@
6076
6274
  if (!Object.prototype.hasOwnProperty.call(source, key))
6077
6275
  continue;
6078
6276
  const sourceValue = source[key];
6277
+ if (sourceValue === undefined)
6278
+ continue;
6079
6279
  const targetValue = result[key];
6280
+ // Optional adapter props are commonly forwarded as undefined. Preserve
6281
+ // the existing/default config in that case instead of erasing a section.
6282
+ if (sourceValue === undefined)
6283
+ continue;
6080
6284
  if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) {
6081
6285
  result[key] = this._mergeConfig(targetValue && typeof targetValue === 'object' ? targetValue : {}, sourceValue);
6082
6286
  }
@@ -6118,8 +6322,9 @@
6118
6322
  const hasSomethingToClear = (clearSelection && hasSelection) || (clearSearch && hasSearch);
6119
6323
  const hideWhenEmpty = this._config.clearControl.hideWhenEmpty !== false;
6120
6324
  const visible = enabled && (!hideWhenEmpty || hasSomethingToClear);
6121
- this._inputContainer.classList.toggle('has-clear-control', enabled);
6122
- this._arrowContainer.classList.toggle('with-clear-control', enabled);
6325
+ // Reserve the action area only while the clear control is actually visible.
6326
+ this._inputContainer.classList.toggle('has-clear-control', visible);
6327
+ this._arrowContainer.classList.toggle('with-clear-control', visible);
6123
6328
  this._clearControl.hidden = !visible;
6124
6329
  this._clearControl.disabled = !hasSomethingToClear;
6125
6330
  this._clearControl.setAttribute('aria-hidden', String(!visible));
@@ -6297,7 +6502,7 @@
6297
6502
  }
6298
6503
  this._optionsContainer.appendChild(fragment);
6299
6504
  if (cursor < filteredIndices.length) {
6300
- requestAnimationFrame(renderChunk);
6505
+ this._requestLifecycleFrame(renderChunk);
6301
6506
  }
6302
6507
  else {
6303
6508
  if (renderCycleId !== this._renderCycleId)
@@ -6375,16 +6580,16 @@
6375
6580
  showRemoveButton: this._config.selection.mode === 'multi' && this._config.selection.showRemoveButton,
6376
6581
  removeButtonIcon: this._config.selection.removeButtonIcon,
6377
6582
  classMap: this.classMap,
6378
- className: this._config.styles.classNames?.option,
6583
+ className: this._config.styles?.classNames?.option,
6379
6584
  });
6380
- if (this._config.styles.classNames?.option) {
6585
+ if (this._config.styles?.classNames?.option) {
6381
6586
  option.classList.add(...this._config.styles.classNames.option.split(' ').filter(Boolean));
6382
6587
  }
6383
6588
  option.setAttribute('dir', this._config.direction ?? 'ltr');
6384
- if (isSelected && this._config.styles.classNames?.selectedOption) {
6589
+ if (isSelected && this._config.styles?.classNames?.selectedOption) {
6385
6590
  option.classList.add(...this._config.styles.classNames.selectedOption.split(' ').filter(Boolean));
6386
6591
  }
6387
- if (this._state.activeIndex === index && this._config.styles.classNames?.activeOption) {
6592
+ if (this._state.activeIndex === index && this._config.styles?.classNames?.activeOption) {
6388
6593
  option.classList.add(...this._config.styles.classNames.activeOption.split(' ').filter(Boolean));
6389
6594
  }
6390
6595
  if (isDisabled && this._config.styles.classNames?.disabledOption) {
@@ -6573,6 +6778,8 @@
6573
6778
  /** live set of all connected instances; used to auto-close siblings */
6574
6779
  EnhancedSelect._instances = new Set();
6575
6780
  EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS = 'smilodon-mirrored-styles-scope';
6781
+ EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT = 32;
6782
+ EnhancedSelect._mirroredStylesheetTextCache = new Map();
6576
6783
  // Register custom element
6577
6784
  if (!customElements.get('enhanced-select')) {
6578
6785
  customElements.define('enhanced-select', EnhancedSelect);
@@ -6930,7 +7137,8 @@
6930
7137
  this.rafId = 0;
6931
7138
  this.measuring = false;
6932
7139
  this.observer = null;
6933
- this.workTimes = [];
7140
+ this.workTotal = 0;
7141
+ this.workCount = 0;
6934
7142
  /**
6935
7143
  * Measure frame timing via requestAnimationFrame
6936
7144
  */
@@ -6947,7 +7155,6 @@
6947
7155
  this.lastFrameTime = now;
6948
7156
  this.rafId = requestAnimationFrame(this.measureFrame);
6949
7157
  };
6950
- this.setupObserver();
6951
7158
  }
6952
7159
  /**
6953
7160
  * Setup PerformanceObserver for long tasks
@@ -6957,12 +7164,15 @@
6957
7164
  return;
6958
7165
  try {
6959
7166
  this.observer = new PerformanceObserver((list) => {
7167
+ if (!this.measuring)
7168
+ return;
6960
7169
  for (const entry of list.getEntries()) {
6961
7170
  if (entry.entryType === 'longtask' && entry.duration > 50) {
6962
7171
  this.longTasks++;
6963
7172
  }
6964
7173
  if (entry.entryType === 'measure') {
6965
- this.workTimes.push(entry.duration);
7174
+ this.workTotal += entry.duration;
7175
+ this.workCount += 1;
6966
7176
  }
6967
7177
  }
6968
7178
  });
@@ -6987,9 +7197,11 @@
6987
7197
  return;
6988
7198
  this.measuring = true;
6989
7199
  this.frameTimes = [];
6990
- this.workTimes = [];
7200
+ this.workTotal = 0;
7201
+ this.workCount = 0;
6991
7202
  this.longTasks = 0;
6992
7203
  this.lastFrameTime = performance.now();
7204
+ this.setupObserver();
6993
7205
  this.measureFrame();
6994
7206
  }
6995
7207
  /**
@@ -7001,6 +7213,10 @@
7001
7213
  cancelAnimationFrame(this.rafId);
7002
7214
  this.rafId = 0;
7003
7215
  }
7216
+ if (this.observer) {
7217
+ this.observer.disconnect();
7218
+ this.observer = null;
7219
+ }
7004
7220
  }
7005
7221
  /**
7006
7222
  * Mark start of work for custom measurement
@@ -7012,10 +7228,15 @@
7012
7228
  * Mark end of work and measure duration
7013
7229
  */
7014
7230
  markEnd(label) {
7015
- performance.mark(`${label}-end`);
7016
- performance.measure(label, `${label}-start`, `${label}-end`);
7017
- const measure = performance.getEntriesByName(label, 'measure')[0];
7018
- return measure ? measure.duration : 0;
7231
+ const startMark = `${label}-start`;
7232
+ const endMark = `${label}-end`;
7233
+ performance.mark(endMark);
7234
+ const measure = performance.measure(label, startMark, endMark);
7235
+ const duration = measure ? measure.duration : 0;
7236
+ performance.clearMarks(startMark);
7237
+ performance.clearMarks(endMark);
7238
+ performance.clearMeasures(label);
7239
+ return duration;
7019
7240
  }
7020
7241
  /**
7021
7242
  * Get current metrics snapshot
@@ -7027,8 +7248,8 @@
7027
7248
  const fps = avgFrameTime > 0 ? 1000 / avgFrameTime : 0;
7028
7249
  const longFrames = this.frameTimes.filter(t => t > 16.67).length;
7029
7250
  const droppedFrames = this.frameTimes.filter(t => t > 33.33).length; // > 2 frames
7030
- const avgMainThreadWork = this.workTimes.length > 0
7031
- ? this.workTimes.reduce((a, b) => a + b, 0) / this.workTimes.length
7251
+ const avgMainThreadWork = this.workCount > 0
7252
+ ? this.workTotal / this.workCount
7032
7253
  : 0;
7033
7254
  const metrics = {
7034
7255
  frames: {
@@ -7087,7 +7308,8 @@
7087
7308
  */
7088
7309
  reset() {
7089
7310
  this.frameTimes = [];
7090
- this.workTimes = [];
7311
+ this.workTotal = 0;
7312
+ this.workCount = 0;
7091
7313
  this.longTasks = 0;
7092
7314
  }
7093
7315
  /**