@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.cjs CHANGED
@@ -245,6 +245,10 @@ class DOMPool {
245
245
  if (poolNode) {
246
246
  poolNode.inUse = false;
247
247
  poolNode.lastUsed = performance.now();
248
+ if (this.pool.length > this.maxSize) {
249
+ this.removePoolNode(poolNode);
250
+ return;
251
+ }
248
252
  // Aggressive cleanup
249
253
  this.reset(poolNode.node);
250
254
  }
@@ -265,12 +269,19 @@ class DOMPool {
265
269
  }
266
270
  }
267
271
  if (lruIndex >= 0) {
268
- const evicted = this.pool.splice(lruIndex, 1)[0];
269
- // Full cleanup before GC
270
- this.deepCleanup(evicted.node);
272
+ this.removePoolNode(this.pool[lruIndex]);
271
273
  if (this.telemetry)
272
274
  this.evictions++;
275
+ return true;
273
276
  }
277
+ return false;
278
+ }
279
+ removePoolNode(poolNode) {
280
+ const index = this.pool.indexOf(poolNode);
281
+ if (index < 0)
282
+ return;
283
+ const [removed] = this.pool.splice(index, 1);
284
+ this.deepCleanup(removed.node);
274
285
  }
275
286
  /**
276
287
  * Default reset: clear content, remove inline styles, remove attributes
@@ -320,7 +331,8 @@ class DOMPool {
320
331
  this.maxSize = size;
321
332
  // Evict excess nodes
322
333
  while (this.pool.length > this.maxSize) {
323
- this.evictLRU();
334
+ if (!this.evictLRU())
335
+ break;
324
336
  }
325
337
  }
326
338
  /**
@@ -356,6 +368,8 @@ class Virtualizer {
356
368
  constructor(container, itemsLength, itemGetter, options) {
357
369
  this.measuredHeights = new Map();
358
370
  this.activeNodes = new Map(); // index -> node mapping
371
+ this.destroyed = false;
372
+ this.recycleRafId = 0;
359
373
  this.container = container;
360
374
  this.itemsLength = itemsLength;
361
375
  this.itemGetter = itemGetter;
@@ -441,6 +455,8 @@ class Virtualizer {
441
455
  }
442
456
  }
443
457
  render(startIndex, endIndex, updateNode) {
458
+ if (this.destroyed)
459
+ return;
444
460
  const frag = document.createDocumentFragment();
445
461
  const activeIndices = new Set();
446
462
  for (let i = startIndex; i <= endIndex; i++) {
@@ -449,16 +465,30 @@ class Virtualizer {
449
465
  frag.appendChild(node);
450
466
  activeIndices.add(i);
451
467
  // Measure on appear (deferred)
452
- queueMicrotask(() => this.measureOnAppear(node, i));
468
+ queueMicrotask(() => {
469
+ if (!this.destroyed) {
470
+ this.measureOnAppear(node, i);
471
+ }
472
+ });
453
473
  }
454
474
  // Translate container by cumulative offset of startIndex
455
475
  const topOffset = this.cumulativeOffset(startIndex);
456
476
  this.container.style.transform = `translate3d(0, ${Math.round(topOffset * 100) / 100}px, 0)`;
457
477
  this.container.replaceChildren(frag);
458
478
  // Recycle nodes not in use
459
- requestAnimationFrame(() => this.releaseExcess(activeIndices));
479
+ if (this.recycleRafId) {
480
+ cancelAnimationFrame(this.recycleRafId);
481
+ }
482
+ this.recycleRafId = requestAnimationFrame(() => {
483
+ this.recycleRafId = 0;
484
+ if (!this.destroyed) {
485
+ this.releaseExcess(activeIndices);
486
+ }
487
+ });
460
488
  }
461
489
  measureOnAppear(node, index) {
490
+ if (this.destroyed || index >= this.itemsLength)
491
+ return;
462
492
  const h = node.offsetHeight;
463
493
  const prev = this.measuredHeights.get(index);
464
494
  const threshold = this.options.measurementThreshold ?? 5;
@@ -486,6 +516,16 @@ class Virtualizer {
486
516
  */
487
517
  setItemsLength(newLength) {
488
518
  this.itemsLength = newLength;
519
+ for (const index of Array.from(this.measuredHeights.keys())) {
520
+ if (index >= newLength) {
521
+ this.measuredHeights.delete(index);
522
+ }
523
+ }
524
+ for (const index of Array.from(this.activeNodes.keys())) {
525
+ if (index >= newLength) {
526
+ this.releaseNode(index);
527
+ }
528
+ }
489
529
  if (this.fenwick) {
490
530
  this.fenwick.resize(newLength);
491
531
  }
@@ -502,6 +542,11 @@ class Virtualizer {
502
542
  * Cleanup resources
503
543
  */
504
544
  destroy() {
545
+ this.destroyed = true;
546
+ if (this.recycleRafId) {
547
+ cancelAnimationFrame(this.recycleRafId);
548
+ this.recycleRafId = 0;
549
+ }
505
550
  this.pool.clear();
506
551
  this.activeNodes.clear();
507
552
  this.measuredHeights.clear();
@@ -537,30 +582,18 @@ class CustomOptionPool {
537
582
  * @returns Component instance
538
583
  */
539
584
  acquire(factory, item, index, context, container) {
540
- const factoryKey = this._getFactoryKey(factory);
585
+ this.release(index);
541
586
  // Try to find an available component in the pool
542
- const pooled = this._findAvailableComponent(factoryKey);
587
+ const pooled = this._findAvailableComponent(factory);
543
588
  let component;
544
589
  if (pooled) {
545
590
  // Reuse pooled component
546
591
  component = pooled.instance;
547
- pooled.inUse = true;
548
- pooled.lastUsedIndex = index;
549
592
  }
550
593
  else {
551
594
  // Create new component
552
595
  try {
553
596
  component = factory(item, index);
554
- // Add to pool if under limit
555
- const pool = this._pool.get(factoryKey) || [];
556
- if (pool.length < this._maxPoolSize) {
557
- pool.push({
558
- instance: component,
559
- inUse: true,
560
- lastUsedIndex: index
561
- });
562
- this._pool.set(factoryKey, pool);
563
- }
564
597
  }
565
598
  catch (error) {
566
599
  console.error(`[CustomOptionPool] Failed to create component:`, error);
@@ -570,9 +603,25 @@ class CustomOptionPool {
570
603
  // Mount the component
571
604
  try {
572
605
  component.mountOption(container, context);
606
+ if (pooled) {
607
+ pooled.inUse = true;
608
+ pooled.lastUsedIndex = index;
609
+ }
610
+ else {
611
+ this._addToPool(factory, component, index);
612
+ }
573
613
  this._activeComponents.set(index, component);
574
614
  }
575
615
  catch (error) {
616
+ if (pooled) {
617
+ pooled.inUse = false;
618
+ }
619
+ try {
620
+ component.unmountOption();
621
+ }
622
+ catch {
623
+ // ignore cleanup failures after a mount failure
624
+ }
576
625
  console.error(`[CustomOptionPool] Failed to mount component at index ${index}:`, error);
577
626
  throw error;
578
627
  }
@@ -669,18 +718,44 @@ class CustomOptionPool {
669
718
  /**
670
719
  * Find an available component in the pool
671
720
  */
672
- _findAvailableComponent(factoryKey) {
673
- const pool = this._pool.get(factoryKey);
721
+ _findAvailableComponent(factory) {
722
+ const pool = this._pool.get(factory);
674
723
  if (!pool)
675
724
  return undefined;
676
725
  return pool.find(p => !p.inUse);
677
726
  }
678
- /**
679
- * Generate a unique key for a factory function
680
- */
681
- _getFactoryKey(factory) {
682
- // Use function name or create a symbol
683
- return factory.name || `factory_${factory.toString().slice(0, 50)}`;
727
+ _addToPool(factory, component, index) {
728
+ while (this._getTotalPooled() >= this._maxPoolSize) {
729
+ if (!this._evictAvailableComponent())
730
+ return;
731
+ }
732
+ const pool = this._pool.get(factory) || [];
733
+ pool.push({
734
+ instance: component,
735
+ inUse: true,
736
+ lastUsedIndex: index
737
+ });
738
+ this._pool.set(factory, pool);
739
+ }
740
+ _evictAvailableComponent() {
741
+ for (const [factory, pool] of this._pool.entries()) {
742
+ const index = pool.findIndex(p => !p.inUse);
743
+ if (index < 0)
744
+ continue;
745
+ pool.splice(index, 1);
746
+ if (pool.length === 0) {
747
+ this._pool.delete(factory);
748
+ }
749
+ return true;
750
+ }
751
+ return false;
752
+ }
753
+ _getTotalPooled() {
754
+ let total = 0;
755
+ for (const pool of this._pool.values()) {
756
+ total += pool.length;
757
+ }
758
+ return total;
684
759
  }
685
760
  }
686
761
 
@@ -714,6 +789,7 @@ class OptionRenderer {
714
789
  const value = this._config.getValue(item);
715
790
  const label = this._config.getLabel(item);
716
791
  const isDisabled = this._config.getDisabled ? this._config.getDisabled(item) : false;
792
+ this.unmount(index);
717
793
  // Determine if this is a custom component or lightweight option
718
794
  const hasCustomComponent = extendedItem.optionComponent && typeof extendedItem.optionComponent === 'function';
719
795
  if (hasCustomComponent) {
@@ -904,7 +980,7 @@ class OptionRenderer {
904
980
 
905
981
  class NativeSelectElement extends HTMLElement {
906
982
  static get observedAttributes() {
907
- return ['placement', 'strategy', 'portal'];
983
+ return ["placement", "strategy", "portal"];
908
984
  }
909
985
  constructor() {
910
986
  super();
@@ -915,22 +991,23 @@ class NativeSelectElement extends HTMLElement {
915
991
  this._selectedItems = new Map(); // index -> item
916
992
  this._activeIndex = -1;
917
993
  this._multi = false;
918
- this._typeBuffer = '';
919
- this._shadow = this.attachShadow({ mode: 'open' });
920
- this._listRoot = document.createElement('div');
921
- this._listRoot.setAttribute('role', 'listbox');
922
- this._listRoot.setAttribute('tabindex', '0');
994
+ this._typeBuffer = "";
995
+ this._shadow = this.attachShadow({ mode: "open" });
996
+ this._listRoot = document.createElement("div");
997
+ this._listRoot.setAttribute("role", "listbox");
998
+ this._listRoot.setAttribute("tabindex", "0");
923
999
  this._shadow.appendChild(this._listRoot);
924
1000
  // Live region for screen reader announcements
925
- this._liveRegion = document.createElement('div');
926
- this._liveRegion.setAttribute('role', 'status');
927
- this._liveRegion.setAttribute('aria-live', 'polite');
928
- this._liveRegion.style.cssText = 'position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;';
1001
+ this._liveRegion = document.createElement("div");
1002
+ this._liveRegion.setAttribute("role", "status");
1003
+ this._liveRegion.setAttribute("aria-live", "polite");
1004
+ this._liveRegion.style.cssText =
1005
+ "position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden;";
929
1006
  this._shadow.appendChild(this._liveRegion);
930
1007
  this._helpers = createRendererHelpers((item, index) => this._onSelect(item, index));
931
1008
  // Delegated click
932
- this._listRoot.addEventListener('click', (e) => {
933
- const el = e.target.closest('[data-selectable]');
1009
+ this._listRoot.addEventListener("click", (e) => {
1010
+ const el = e.target.closest("[data-selectable]");
934
1011
  if (!el)
935
1012
  return;
936
1013
  const idx = Number(el.dataset.index);
@@ -938,28 +1015,33 @@ class NativeSelectElement extends HTMLElement {
938
1015
  this._onSelect(item, idx);
939
1016
  });
940
1017
  // Keyboard navigation
941
- this._listRoot.addEventListener('keydown', (e) => this._onKeydown(e));
1018
+ this._listRoot.addEventListener("keydown", (e) => this._onKeydown(e));
942
1019
  }
943
1020
  connectedCallback() {
944
1021
  // Initialize ARIA roles and open event
945
- this._listRoot.setAttribute('role', 'listbox');
946
- this._listRoot.setAttribute('aria-label', 'Options list');
1022
+ this._listRoot.setAttribute("role", "listbox");
1023
+ this._listRoot.setAttribute("aria-label", "Options list");
947
1024
  if (this._multi)
948
- this._listRoot.setAttribute('aria-multiselectable', 'true');
1025
+ this._listRoot.setAttribute("aria-multiselectable", "true");
949
1026
  this._initializeOptionRenderer();
950
- this._emit('open', {});
1027
+ this._emit("open", {});
951
1028
  }
952
1029
  disconnectedCallback() {
953
- this._emit('close', {});
1030
+ this._emit("close", {});
954
1031
  // Cleanup unified renderer
955
1032
  if (this._unifiedRenderer) {
956
1033
  this._unifiedRenderer.unmountAll();
957
1034
  }
1035
+ this._virtualizer?.destroy();
1036
+ this._virtualizer = undefined;
958
1037
  // Cleanup: remove listeners if any were added outside constructor
959
1038
  if (this._typeTimeout)
960
1039
  window.clearTimeout(this._typeTimeout);
1040
+ if (this._announceTimeout)
1041
+ window.clearTimeout(this._announceTimeout);
961
1042
  }
962
1043
  _initializeOptionRenderer() {
1044
+ this._unifiedRenderer?.unmountAll();
963
1045
  const getValue = (item) => item?.value ?? item;
964
1046
  const getLabel = (item) => item?.label ?? String(item);
965
1047
  const getDisabled = (item) => item?.disabled ?? false;
@@ -975,39 +1057,43 @@ class NativeSelectElement extends HTMLElement {
975
1057
  },
976
1058
  onCustomEvent: (index, eventName, data) => {
977
1059
  // Emit custom events from option components
978
- this.dispatchEvent(new CustomEvent('option:custom-event', {
1060
+ this.dispatchEvent(new CustomEvent("option:custom-event", {
979
1061
  detail: { index, eventName, data },
980
1062
  bubbles: true,
981
- composed: true
1063
+ composed: true,
982
1064
  }));
983
1065
  },
984
1066
  onError: (index, error) => {
985
1067
  console.error(`[NativeSelect] Error in option ${index}:`, error);
986
- this.dispatchEvent(new CustomEvent('option:mount-error', {
1068
+ this.dispatchEvent(new CustomEvent("option:mount-error", {
987
1069
  detail: { index, error },
988
1070
  bubbles: true,
989
- composed: true
1071
+ composed: true,
990
1072
  }));
991
- }
1073
+ },
992
1074
  };
993
1075
  this._unifiedRenderer = new OptionRenderer(rendererConfig);
994
1076
  }
995
1077
  attributeChangedCallback(name, _oldValue, newValue) {
996
1078
  switch (name) {
997
- case 'placement':
998
- this._options.placement = (newValue ?? undefined);
1079
+ case "placement":
1080
+ this._options.placement = (newValue ??
1081
+ undefined);
999
1082
  break;
1000
- case 'strategy':
1001
- this._options.strategy = (newValue ?? undefined);
1083
+ case "strategy":
1084
+ this._options.strategy = (newValue ??
1085
+ undefined);
1002
1086
  break;
1003
- case 'portal':
1004
- this._options.portal = newValue === 'true' ? true : newValue === 'false' ? false : undefined;
1087
+ case "portal":
1088
+ this._options.portal =
1089
+ newValue === "true" ? true : newValue === "false" ? false : undefined;
1005
1090
  break;
1006
1091
  }
1007
1092
  }
1008
1093
  set items(items) {
1009
1094
  this._items = items ?? [];
1010
1095
  // initialize virtualizer with estimated height (default 48) and buffer
1096
+ this._virtualizer?.destroy();
1011
1097
  this._virtualizer = new Virtualizer(this._listRoot, this._items.length, (i) => this._items[i], { estimatedItemHeight: 48, buffer: 5 });
1012
1098
  this.render();
1013
1099
  }
@@ -1017,10 +1103,10 @@ class NativeSelectElement extends HTMLElement {
1017
1103
  set multi(value) {
1018
1104
  this._multi = value;
1019
1105
  if (value) {
1020
- this._listRoot.setAttribute('aria-multiselectable', 'true');
1106
+ this._listRoot.setAttribute("aria-multiselectable", "true");
1021
1107
  }
1022
1108
  else {
1023
- this._listRoot.removeAttribute('aria-multiselectable');
1109
+ this._listRoot.removeAttribute("aria-multiselectable");
1024
1110
  }
1025
1111
  }
1026
1112
  get multi() {
@@ -1056,7 +1142,7 @@ class NativeSelectElement extends HTMLElement {
1056
1142
  * For multi-select: adds to selection if not already selected
1057
1143
  */
1058
1144
  setValue(value) {
1059
- if (value === null || value === undefined || value === '') {
1145
+ if (value === null || value === undefined || value === "") {
1060
1146
  // Clear selection
1061
1147
  this._selectedSet.clear();
1062
1148
  this._selectedItems.clear();
@@ -1065,8 +1151,8 @@ class NativeSelectElement extends HTMLElement {
1065
1151
  return;
1066
1152
  }
1067
1153
  // Find item by value
1068
- const index = this._items.findIndex(item => {
1069
- if (typeof item === 'object' && item !== null && 'value' in item) {
1154
+ const index = this._items.findIndex((item) => {
1155
+ if (typeof item === "object" && item !== null && "value" in item) {
1070
1156
  return item.value === value;
1071
1157
  }
1072
1158
  return item === value;
@@ -1092,7 +1178,7 @@ class NativeSelectElement extends HTMLElement {
1092
1178
  // Optimized: single-pass iteration, no intermediate arrays
1093
1179
  const values = [];
1094
1180
  for (const item of this._selectedItems.values()) {
1095
- if (typeof item === 'object' && item !== null && 'value' in item) {
1181
+ if (typeof item === "object" && item !== null && "value" in item) {
1096
1182
  values.push(item.value);
1097
1183
  }
1098
1184
  else {
@@ -1107,16 +1193,16 @@ class NativeSelectElement extends HTMLElement {
1107
1193
  const scrollTop = this.scrollTop || 0;
1108
1194
  // Update aria-activedescendant
1109
1195
  if (this._activeIndex >= 0) {
1110
- this._listRoot.setAttribute('aria-activedescendant', `option-${this._activeIndex}`);
1196
+ this._listRoot.setAttribute("aria-activedescendant", `option-${this._activeIndex}`);
1111
1197
  }
1112
1198
  else {
1113
- this._listRoot.removeAttribute('aria-activedescendant');
1199
+ this._listRoot.removeAttribute("aria-activedescendant");
1114
1200
  }
1115
1201
  // Check if any items have custom components
1116
- const hasCustomComponents = this._items.some(item => typeof item === 'object' &&
1202
+ const hasCustomComponents = this._items.some((item) => typeof item === "object" &&
1117
1203
  item !== null &&
1118
- Object.prototype.hasOwnProperty.call(item, 'optionComponent') &&
1119
- typeof item.optionComponent === 'function');
1204
+ Object.prototype.hasOwnProperty.call(item, "optionComponent") &&
1205
+ typeof item.optionComponent === "function");
1120
1206
  // Use unified renderer if we have custom components
1121
1207
  if (hasCustomComponents && this._unifiedRenderer) {
1122
1208
  this._listRoot.replaceChildren(); // Clear existing content
@@ -1125,7 +1211,7 @@ class NativeSelectElement extends HTMLElement {
1125
1211
  const item = this._items[i];
1126
1212
  const isSelected = this._selectedSet.has(i);
1127
1213
  const isFocused = this._activeIndex === i;
1128
- const optionElement = this._unifiedRenderer.render(item, i, isSelected, isFocused, `native-${this.getAttribute('id') || 'default'}`);
1214
+ const optionElement = this._unifiedRenderer.render(item, i, isSelected, isFocused, `native-${this.getAttribute("id") || "default"}`);
1129
1215
  frag.appendChild(optionElement);
1130
1216
  }
1131
1217
  this._listRoot.appendChild(frag);
@@ -1142,14 +1228,14 @@ class NativeSelectElement extends HTMLElement {
1142
1228
  node.replaceChildren(el);
1143
1229
  }
1144
1230
  else if (optionTemplate) {
1145
- const wrapper = document.createElement('div');
1231
+ const wrapper = document.createElement("div");
1146
1232
  wrapper.innerHTML = optionTemplate(item, i);
1147
1233
  const el = wrapper.firstElementChild;
1148
1234
  node.replaceChildren(el ?? document.createTextNode(String(item)));
1149
1235
  }
1150
1236
  else {
1151
1237
  // Handle {label, value} objects or primitives
1152
- const displayText = (typeof item === 'object' && item !== null && 'label' in item)
1238
+ const displayText = typeof item === "object" && item !== null && "label" in item
1153
1239
  ? String(item.label)
1154
1240
  : String(item);
1155
1241
  node.textContent = displayText;
@@ -1162,9 +1248,9 @@ class NativeSelectElement extends HTMLElement {
1162
1248
  const item = this._items[i];
1163
1249
  if (optionRenderer) {
1164
1250
  const el = optionRenderer(item, i, this._helpers);
1165
- if (!el.hasAttribute('data-selectable')) {
1166
- el.setAttribute('data-selectable', '');
1167
- el.setAttribute('data-index', String(i));
1251
+ if (!el.hasAttribute("data-selectable")) {
1252
+ el.setAttribute("data-selectable", "");
1253
+ el.setAttribute("data-index", String(i));
1168
1254
  }
1169
1255
  this._applyOptionAttrs(el, i);
1170
1256
  frag.appendChild(el);
@@ -1177,14 +1263,14 @@ class NativeSelectElement extends HTMLElement {
1177
1263
  return; // rendering complete
1178
1264
  }
1179
1265
  else {
1180
- const el = document.createElement('div');
1266
+ const el = document.createElement("div");
1181
1267
  // Handle {label, value} objects or primitives
1182
- const displayText = (typeof item === 'object' && item !== null && 'label' in item)
1268
+ const displayText = typeof item === "object" && item !== null && "label" in item
1183
1269
  ? String(item.label)
1184
1270
  : String(item);
1185
1271
  el.textContent = displayText;
1186
- el.setAttribute('data-selectable', '');
1187
- el.setAttribute('data-index', String(i));
1272
+ el.setAttribute("data-selectable", "");
1273
+ el.setAttribute("data-index", String(i));
1188
1274
  this._applyOptionAttrs(el, i);
1189
1275
  frag.appendChild(el);
1190
1276
  }
@@ -1192,13 +1278,13 @@ class NativeSelectElement extends HTMLElement {
1192
1278
  this._listRoot.replaceChildren(frag);
1193
1279
  }
1194
1280
  _applyOptionAttrs(node, index) {
1195
- node.setAttribute('role', 'option');
1281
+ node.setAttribute("role", "option");
1196
1282
  node.id = `option-${index}`;
1197
1283
  if (this._selectedSet.has(index)) {
1198
- node.setAttribute('aria-selected', 'true');
1284
+ node.setAttribute("aria-selected", "true");
1199
1285
  }
1200
1286
  else {
1201
- node.setAttribute('aria-selected', 'false');
1287
+ node.setAttribute("aria-selected", "false");
1202
1288
  }
1203
1289
  }
1204
1290
  _applyAriaToAll() {
@@ -1236,13 +1322,13 @@ class NativeSelectElement extends HTMLElement {
1236
1322
  const selected = this._selectedSet.has(index);
1237
1323
  const value = item?.value ?? item;
1238
1324
  const label = item?.label ?? String(item);
1239
- this._emit('select', {
1325
+ this._emit("select", {
1240
1326
  item,
1241
1327
  index,
1242
1328
  value,
1243
1329
  label,
1244
1330
  selected,
1245
- multi: this._multi
1331
+ multi: this._multi,
1246
1332
  });
1247
1333
  // Optimized: single-pass iteration for change event data
1248
1334
  const selectedItems = [];
@@ -1252,50 +1338,50 @@ class NativeSelectElement extends HTMLElement {
1252
1338
  selectedValues.push(item?.value ?? item);
1253
1339
  }
1254
1340
  // Emit 'change' event for better React compatibility
1255
- this._emit('change', {
1341
+ this._emit("change", {
1256
1342
  selectedItems,
1257
1343
  selectedValues,
1258
- selectedIndices: Array.from(this._selectedSet)
1344
+ selectedIndices: Array.from(this._selectedSet),
1259
1345
  });
1260
1346
  this._announce(`Selected ${label}`);
1261
1347
  }
1262
1348
  _onKeydown(e) {
1263
1349
  switch (e.key) {
1264
- case 'ArrowDown':
1350
+ case "ArrowDown":
1265
1351
  e.preventDefault();
1266
1352
  this._moveActive(1);
1267
1353
  break;
1268
- case 'ArrowUp':
1354
+ case "ArrowUp":
1269
1355
  e.preventDefault();
1270
1356
  this._moveActive(-1);
1271
1357
  break;
1272
- case 'Home':
1358
+ case "Home":
1273
1359
  e.preventDefault();
1274
1360
  this._setActive(0);
1275
1361
  break;
1276
- case 'End':
1362
+ case "End":
1277
1363
  e.preventDefault();
1278
1364
  this._setActive(this._items.length - 1);
1279
1365
  break;
1280
- case 'PageDown':
1366
+ case "PageDown":
1281
1367
  e.preventDefault();
1282
1368
  this._moveActive(10);
1283
1369
  break;
1284
- case 'PageUp':
1370
+ case "PageUp":
1285
1371
  e.preventDefault();
1286
1372
  this._moveActive(-10);
1287
1373
  break;
1288
- case 'Enter':
1289
- case ' ':
1374
+ case "Enter":
1375
+ case " ":
1290
1376
  e.preventDefault();
1291
1377
  if (this._activeIndex >= 0) {
1292
1378
  const item = this._items[this._activeIndex];
1293
1379
  this._onSelect(item, this._activeIndex);
1294
1380
  }
1295
1381
  break;
1296
- case 'Escape':
1382
+ case "Escape":
1297
1383
  e.preventDefault();
1298
- this._emit('close', {});
1384
+ this._emit("close", {});
1299
1385
  break;
1300
1386
  default:
1301
1387
  // Type-ahead buffer
@@ -1317,14 +1403,14 @@ class NativeSelectElement extends HTMLElement {
1317
1403
  }
1318
1404
  _scrollToActive() {
1319
1405
  const el = this._shadow.getElementById(`option-${this._activeIndex}`);
1320
- el?.scrollIntoView({ block: 'nearest', inline: 'nearest' });
1406
+ el?.scrollIntoView({ block: "nearest", inline: "nearest" });
1321
1407
  }
1322
1408
  _onType(char) {
1323
1409
  if (this._typeTimeout)
1324
1410
  window.clearTimeout(this._typeTimeout);
1325
1411
  this._typeBuffer += char.toLowerCase();
1326
1412
  this._typeTimeout = window.setTimeout(() => {
1327
- this._typeBuffer = '';
1413
+ this._typeBuffer = "";
1328
1414
  }, 400);
1329
1415
  // Find first matching item
1330
1416
  const match = this._items.findIndex((item) => String(item).toLowerCase().startsWith(this._typeBuffer));
@@ -1335,9 +1421,12 @@ class NativeSelectElement extends HTMLElement {
1335
1421
  _announce(msg) {
1336
1422
  if (this._liveRegion) {
1337
1423
  this._liveRegion.textContent = msg;
1338
- setTimeout(() => {
1424
+ if (this._announceTimeout)
1425
+ window.clearTimeout(this._announceTimeout);
1426
+ this._announceTimeout = window.setTimeout(() => {
1427
+ this._announceTimeout = undefined;
1339
1428
  if (this._liveRegion)
1340
- this._liveRegion.textContent = '';
1429
+ this._liveRegion.textContent = "";
1341
1430
  }, 1000);
1342
1431
  }
1343
1432
  }
@@ -1346,7 +1435,9 @@ class NativeSelectElement extends HTMLElement {
1346
1435
  this._listRoot.focus();
1347
1436
  }
1348
1437
  }
1349
- customElements.define('smilodon-select', NativeSelectElement);
1438
+ if (!customElements.get("smilodon-select")) {
1439
+ customElements.define("smilodon-select", NativeSelectElement);
1440
+ }
1350
1441
 
1351
1442
  /**
1352
1443
  * Global Configuration System for Select Components
@@ -2120,6 +2211,8 @@ class EnhancedSelect extends HTMLElement {
2120
2211
  return this._classMap;
2121
2212
  }
2122
2213
  set classMap(map) {
2214
+ if (this._areClassMapsEqual(this._classMap, map))
2215
+ return;
2123
2216
  this._classMap = map;
2124
2217
  this._setGlobalStylesMirroring(Boolean(this._optionRenderer || map || this._groupHeaderRenderer));
2125
2218
  this._track('style', 'classMapChanged', {
@@ -2139,6 +2232,8 @@ class EnhancedSelect extends HTMLElement {
2139
2232
  return this._groupHeaderRenderer;
2140
2233
  }
2141
2234
  set groupHeaderRenderer(renderer) {
2235
+ if (this._groupHeaderRenderer === renderer)
2236
+ return;
2142
2237
  this._groupHeaderRenderer = renderer;
2143
2238
  this._setGlobalStylesMirroring(Boolean(this._optionRenderer || this._classMap || renderer));
2144
2239
  this._track('style', 'groupHeaderRendererChanged', { enabled: Boolean(renderer) });
@@ -2162,6 +2257,9 @@ class EnhancedSelect extends HTMLElement {
2162
2257
  this._globalStylesContainer = null;
2163
2258
  this._themeContextObserver = null;
2164
2259
  this._globalStylesSyncToken = 0;
2260
+ this._asyncGeneration = 0;
2261
+ this._lifecycleTimers = new Set();
2262
+ this._lifecycleRafs = new Set();
2165
2263
  this._tracking = { events: [], styles: [], limitations: [] };
2166
2264
  this._suppressBlurClose = false;
2167
2265
  this._renderCycleId = 0;
@@ -2175,6 +2273,41 @@ class EnhancedSelect extends HTMLElement {
2175
2273
  startScrollLeft: 0,
2176
2274
  };
2177
2275
  this._liftedAncestors = [];
2276
+ this._onDocumentPointerDown = (e) => {
2277
+ const path = (e.composedPath && e.composedPath()) || [];
2278
+ let clickedInside = false;
2279
+ for (const node of path) {
2280
+ if (node === this || node === this._container) {
2281
+ clickedInside = true;
2282
+ break;
2283
+ }
2284
+ if (node instanceof Node) {
2285
+ try {
2286
+ if (this._shadow && this._shadow.contains(node)) {
2287
+ clickedInside = true;
2288
+ break;
2289
+ }
2290
+ }
2291
+ catch (err) {
2292
+ // ignore
2293
+ }
2294
+ }
2295
+ if (node instanceof Element) {
2296
+ try {
2297
+ if (node.matches('[data-sm-selectable], [data-selectable], [data-sm-state], .input-container, .select-container, .dropdown-arrow-container, .clear-control-button')) {
2298
+ clickedInside = true;
2299
+ break;
2300
+ }
2301
+ }
2302
+ catch (err) {
2303
+ // ignore
2304
+ }
2305
+ }
2306
+ }
2307
+ if (!clickedInside) {
2308
+ this._handleClose();
2309
+ }
2310
+ };
2178
2311
  this._shadow = this.attachShadow({ mode: 'open' });
2179
2312
  this._uniqueId = `enhanced-select-${Math.random().toString(36).substr(2, 9)}`;
2180
2313
  this._rendererHelpers = this._buildRendererHelpers();
@@ -2221,13 +2354,18 @@ class EnhancedSelect extends HTMLElement {
2221
2354
  connectedCallback() {
2222
2355
  // register instance
2223
2356
  EnhancedSelect._instances.add(this);
2357
+ this._connectionController?.abort();
2358
+ this._connectionController = new AbortController();
2359
+ document.addEventListener('pointerdown', this._onDocumentPointerDown, {
2360
+ signal: this._connectionController.signal,
2361
+ });
2224
2362
  // WORKAROUND: Force display style on host element for Angular compatibility
2225
2363
  // Angular's rendering seems to not apply :host styles correctly in some cases
2226
2364
  // Must be done in connectedCallback when element is attached to DOM
2227
2365
  this.style.display = 'block';
2228
2366
  // Sync direction attribute (must be in connectedCallback, not constructor)
2229
2367
  this._syncDirectionConfig();
2230
- if (this._optionRenderer) {
2368
+ if (this._optionRenderer || this._classMap || this._groupHeaderRenderer) {
2231
2369
  this._setGlobalStylesMirroring(true);
2232
2370
  }
2233
2371
  // Load initial data if server-side is enabled
@@ -2248,6 +2386,10 @@ class EnhancedSelect extends HTMLElement {
2248
2386
  disconnectedCallback() {
2249
2387
  // unregister instance
2250
2388
  EnhancedSelect._instances.delete(this);
2389
+ this._connectionController?.abort();
2390
+ this._connectionController = undefined;
2391
+ this._asyncGeneration += 1;
2392
+ this._clearLifecycleTasks();
2251
2393
  // Cleanup observers
2252
2394
  this._resizeObserver?.disconnect();
2253
2395
  this._intersectionObserver?.disconnect();
@@ -2267,8 +2409,8 @@ class EnhancedSelect extends HTMLElement {
2267
2409
  }
2268
2410
  _setGlobalStylesMirroring(enabled) {
2269
2411
  if (this._mirrorGlobalStylesForCustomOptions === enabled) {
2270
- if (enabled) {
2271
- this._mirrorDocumentStylesIntoShadow();
2412
+ if (enabled && this.isConnected && !this._globalStylesObserver) {
2413
+ this._setupGlobalStylesMirroring();
2272
2414
  }
2273
2415
  return;
2274
2416
  }
@@ -2281,6 +2423,36 @@ class EnhancedSelect extends HTMLElement {
2281
2423
  this._teardownGlobalStylesMirroring();
2282
2424
  }
2283
2425
  }
2426
+ _setLifecycleTimeout(callback, delay = 0) {
2427
+ const id = window.setTimeout(() => {
2428
+ this._lifecycleTimers.delete(id);
2429
+ if (!this.isConnected)
2430
+ return;
2431
+ callback();
2432
+ }, delay);
2433
+ this._lifecycleTimers.add(id);
2434
+ return id;
2435
+ }
2436
+ _requestLifecycleFrame(callback) {
2437
+ const id = requestAnimationFrame(() => {
2438
+ this._lifecycleRafs.delete(id);
2439
+ if (!this.isConnected)
2440
+ return;
2441
+ callback();
2442
+ });
2443
+ this._lifecycleRafs.add(id);
2444
+ return id;
2445
+ }
2446
+ _clearLifecycleTasks() {
2447
+ for (const id of this._lifecycleTimers) {
2448
+ clearTimeout(id);
2449
+ }
2450
+ this._lifecycleTimers.clear();
2451
+ for (const id of this._lifecycleRafs) {
2452
+ cancelAnimationFrame(id);
2453
+ }
2454
+ this._lifecycleRafs.clear();
2455
+ }
2284
2456
  _setupGlobalStylesMirroring() {
2285
2457
  if (typeof document === 'undefined')
2286
2458
  return;
@@ -2392,23 +2564,64 @@ class EnhancedSelect extends HTMLElement {
2392
2564
  return this._buildScopedStyleElement(node.textContent || '', String(index));
2393
2565
  }
2394
2566
  if (node instanceof HTMLLinkElement && node.href) {
2395
- try {
2396
- const response = await fetch(node.href, {
2397
- credentials: node.crossOrigin === 'use-credentials' ? 'include' : 'same-origin',
2398
- mode: 'cors',
2399
- });
2400
- if (!response.ok) {
2401
- return null;
2402
- }
2403
- const cssText = await response.text();
2404
- return this._buildScopedStyleElement(cssText, String(index));
2567
+ const credentials = node.crossOrigin === 'use-credentials' ? 'include' : 'same-origin';
2568
+ const cacheKey = `${node.href}|${credentials}`;
2569
+ let cacheEntry = EnhancedSelect._mirroredStylesheetTextCache.get(cacheKey);
2570
+ if (!cacheEntry) {
2571
+ cacheEntry = {
2572
+ promise: fetch(node.href, {
2573
+ credentials,
2574
+ mode: 'cors',
2575
+ })
2576
+ .then((response) => {
2577
+ if (!response.ok)
2578
+ return null;
2579
+ return response.text();
2580
+ })
2581
+ .catch(() => null),
2582
+ lastUsed: Date.now(),
2583
+ };
2584
+ EnhancedSelect._mirroredStylesheetTextCache.set(cacheKey, cacheEntry);
2585
+ EnhancedSelect._pruneMirroredStylesheetTextCache();
2586
+ }
2587
+ else {
2588
+ cacheEntry.lastUsed = Date.now();
2405
2589
  }
2406
- catch (_error) {
2590
+ const cssText = await cacheEntry.promise;
2591
+ if (cssText === null) {
2592
+ EnhancedSelect._mirroredStylesheetTextCache.delete(cacheKey);
2407
2593
  return null;
2408
2594
  }
2595
+ return this._buildScopedStyleElement(cssText, String(index));
2409
2596
  }
2410
2597
  return null;
2411
2598
  }
2599
+ static _pruneMirroredStylesheetTextCache() {
2600
+ while (EnhancedSelect._mirroredStylesheetTextCache.size > EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT) {
2601
+ let lruKey;
2602
+ let oldest = Infinity;
2603
+ for (const [key, entry] of EnhancedSelect._mirroredStylesheetTextCache.entries()) {
2604
+ if (entry.lastUsed < oldest) {
2605
+ oldest = entry.lastUsed;
2606
+ lruKey = key;
2607
+ }
2608
+ }
2609
+ if (!lruKey)
2610
+ return;
2611
+ EnhancedSelect._mirroredStylesheetTextCache.delete(lruKey);
2612
+ }
2613
+ }
2614
+ _areClassMapsEqual(left, right) {
2615
+ if (left === right)
2616
+ return true;
2617
+ if (!left || !right)
2618
+ return false;
2619
+ const leftKeys = Object.keys(left);
2620
+ const rightKeys = Object.keys(right);
2621
+ if (leftKeys.length !== rightKeys.length)
2622
+ return false;
2623
+ return leftKeys.every((key) => left[key] === right[key]);
2624
+ }
2412
2625
  _buildScopedStyleElement(cssText, id) {
2413
2626
  const scopedCss = this._scopeMirroredCssText(cssText);
2414
2627
  if (!scopedCss.trim())
@@ -2658,6 +2871,8 @@ class EnhancedSelect extends HTMLElement {
2658
2871
  }
2659
2872
  _syncStyleConfigVariables() {
2660
2873
  const styles = this._config.styles;
2874
+ if (!styles)
2875
+ return;
2661
2876
  this._applyStyleVariableMap(styles.option, {
2662
2877
  background: '--select-option-bg',
2663
2878
  backgroundColor: '--select-option-bg',
@@ -4688,7 +4903,7 @@ class EnhancedSelect extends HTMLElement {
4688
4903
  return;
4689
4904
  }
4690
4905
  // Delay to allow option click/focus transitions
4691
- setTimeout(() => {
4906
+ this._setLifecycleTimeout(() => {
4692
4907
  if (this._suppressBlurClose) {
4693
4908
  // another pointerdown inside options is in progress; keep open
4694
4909
  return;
@@ -4713,7 +4928,7 @@ class EnhancedSelect extends HTMLElement {
4713
4928
  // sufficient.
4714
4929
  this._optionsContainer.addEventListener('pointerdown', () => {
4715
4930
  this._suppressBlurClose = true;
4716
- setTimeout(() => {
4931
+ this._setLifecycleTimeout(() => {
4717
4932
  this._suppressBlurClose = false;
4718
4933
  }, 150); // Increased timeout to ensure click finishes before blur checks
4719
4934
  });
@@ -4748,42 +4963,6 @@ class EnhancedSelect extends HTMLElement {
4748
4963
  this._optionsContainer.addEventListener('click', handleOptionEvent);
4749
4964
  // Keyboard navigation
4750
4965
  this._input.addEventListener('keydown', (e) => this._handleKeydown(e));
4751
- // Click outside to close — robust detection across shadow DOM and custom renderers
4752
- document.addEventListener('pointerdown', (e) => {
4753
- const path = (e.composedPath && e.composedPath()) || [];
4754
- let clickedInside = false;
4755
- for (const node of path) {
4756
- if (node === this || node === this._container) {
4757
- clickedInside = true;
4758
- break;
4759
- }
4760
- if (node instanceof Node) {
4761
- try {
4762
- if (this._shadow && this._shadow.contains(node)) {
4763
- clickedInside = true;
4764
- break;
4765
- }
4766
- }
4767
- catch (err) {
4768
- // ignore
4769
- }
4770
- }
4771
- if (node instanceof Element) {
4772
- try {
4773
- if (node.matches('[data-sm-selectable], [data-selectable], [data-sm-state], .input-container, .select-container, .dropdown-arrow-container, .clear-control-button')) {
4774
- clickedInside = true;
4775
- break;
4776
- }
4777
- }
4778
- catch (err) {
4779
- // ignore
4780
- }
4781
- }
4782
- }
4783
- if (!clickedInside) {
4784
- this._handleClose();
4785
- }
4786
- });
4787
4966
  }
4788
4967
  _initializeObservers() {
4789
4968
  // Disconnect existing observer if any
@@ -4809,8 +4988,11 @@ class EnhancedSelect extends HTMLElement {
4809
4988
  return;
4810
4989
  }
4811
4990
  this._setBusy(true);
4991
+ const generation = ++this._asyncGeneration;
4812
4992
  try {
4813
4993
  const items = await this._config.serverSide.fetchSelectedItems(this._config.serverSide.initialSelectedValues);
4994
+ if (generation !== this._asyncGeneration || !this.isConnected)
4995
+ return;
4814
4996
  // Add to state
4815
4997
  items.forEach((item, index) => {
4816
4998
  this._state.selectedItems.set(index, item);
@@ -4819,10 +5001,14 @@ class EnhancedSelect extends HTMLElement {
4819
5001
  this._updateInputDisplay();
4820
5002
  }
4821
5003
  catch (error) {
5004
+ if (generation !== this._asyncGeneration || !this.isConnected)
5005
+ return;
4822
5006
  this._handleError(error);
4823
5007
  }
4824
5008
  finally {
4825
- this._setBusy(false);
5009
+ if (generation === this._asyncGeneration && this.isConnected) {
5010
+ this._setBusy(false);
5011
+ }
4826
5012
  }
4827
5013
  }
4828
5014
  _handleOpen() {
@@ -4855,9 +5041,9 @@ class EnhancedSelect extends HTMLElement {
4855
5041
  // Scroll to selected if configured
4856
5042
  if (this._config.scrollToSelected.enabled) {
4857
5043
  // Use requestAnimationFrame for better timing after render
4858
- requestAnimationFrame(() => {
5044
+ this._requestLifecycleFrame(() => {
4859
5045
  // Double RAF to ensure layout is complete
4860
- requestAnimationFrame(() => {
5046
+ this._requestLifecycleFrame(() => {
4861
5047
  this._scrollToSelected();
4862
5048
  });
4863
5049
  });
@@ -4979,6 +5165,9 @@ class EnhancedSelect extends HTMLElement {
4979
5165
  if (!this._isPerfEnabled())
4980
5166
  return;
4981
5167
  performance.measure(name, start, end);
5168
+ performance.clearMarks(start);
5169
+ performance.clearMarks(end);
5170
+ performance.clearMeasures(name);
4982
5171
  }
4983
5172
  _markOpenStart() {
4984
5173
  if (!this._isPerfEnabled())
@@ -5076,7 +5265,7 @@ class EnhancedSelect extends HTMLElement {
5076
5265
  this._state.lastNotifiedQuery = query;
5077
5266
  this._state.lastNotifiedResultCount = count;
5078
5267
  // Use setTimeout to avoid synchronous state updates during render
5079
- setTimeout(() => {
5268
+ this._setLifecycleTimeout(() => {
5080
5269
  this._emit('search', { query, results: filteredItems, count });
5081
5270
  this._config.callbacks.onSearch?.(query);
5082
5271
  }, 0);
@@ -5369,7 +5558,7 @@ class EnhancedSelect extends HTMLElement {
5369
5558
  _announce(message) {
5370
5559
  if (this._liveRegion) {
5371
5560
  this._liveRegion.textContent = message;
5372
- setTimeout(() => {
5561
+ this._setLifecycleTimeout(() => {
5373
5562
  if (this._liveRegion)
5374
5563
  this._liveRegion.textContent = '';
5375
5564
  }, 1000);
@@ -5564,7 +5753,7 @@ class EnhancedSelect extends HTMLElement {
5564
5753
  // Add fade-out animation
5565
5754
  this._optionsContainer.style.opacity = '0';
5566
5755
  this._optionsContainer.style.transition = 'opacity 0.15s ease-out';
5567
- setTimeout(() => {
5756
+ this._setLifecycleTimeout(() => {
5568
5757
  this._renderOptions();
5569
5758
  // Fade back in
5570
5759
  this._optionsContainer.style.opacity = '1';
@@ -5831,8 +6020,10 @@ class EnhancedSelect extends HTMLElement {
5831
6020
  return this._optionRenderer;
5832
6021
  }
5833
6022
  set optionRenderer(renderer) {
6023
+ if (this._optionRenderer === renderer)
6024
+ return;
5834
6025
  this._optionRenderer = renderer;
5835
- this._setGlobalStylesMirroring(Boolean(renderer || this._classMap));
6026
+ this._setGlobalStylesMirroring(Boolean(renderer || this._classMap || this._groupHeaderRenderer));
5836
6027
  this._track('style', 'optionRendererChanged', { enabled: Boolean(renderer) });
5837
6028
  this._renderOptions();
5838
6029
  }
@@ -5861,7 +6052,7 @@ class EnhancedSelect extends HTMLElement {
5861
6052
  // new ones simply appear below.
5862
6053
  this._dropdown.scrollTop = targetScrollTop;
5863
6054
  // Ensure it sticks after layout
5864
- requestAnimationFrame(() => {
6055
+ this._requestLifecycleFrame(() => {
5865
6056
  if (this._dropdown) {
5866
6057
  this._dropdown.scrollTop = targetScrollTop;
5867
6058
  }
@@ -5934,8 +6125,11 @@ class EnhancedSelect extends HTMLElement {
5934
6125
  if (!this._config.serverSide.fetchSelectedItems)
5935
6126
  return;
5936
6127
  this._setBusy(true);
6128
+ const generation = ++this._asyncGeneration;
5937
6129
  try {
5938
6130
  const items = await this._config.serverSide.fetchSelectedItems(values);
6131
+ if (generation !== this._asyncGeneration || !this.isConnected)
6132
+ return;
5939
6133
  this._state.selectedIndices.clear();
5940
6134
  this._state.selectedItems.clear();
5941
6135
  items.forEach((item, index) => {
@@ -5953,10 +6147,14 @@ class EnhancedSelect extends HTMLElement {
5953
6147
  }
5954
6148
  }
5955
6149
  catch (error) {
6150
+ if (generation !== this._asyncGeneration || !this.isConnected)
6151
+ return;
5956
6152
  this._handleError(error);
5957
6153
  }
5958
6154
  finally {
5959
- this._setBusy(false);
6155
+ if (generation === this._asyncGeneration && this.isConnected) {
6156
+ this._setBusy(false);
6157
+ }
5960
6158
  }
5961
6159
  }
5962
6160
  /**
@@ -6072,7 +6270,13 @@ class EnhancedSelect extends HTMLElement {
6072
6270
  if (!Object.prototype.hasOwnProperty.call(source, key))
6073
6271
  continue;
6074
6272
  const sourceValue = source[key];
6273
+ if (sourceValue === undefined)
6274
+ continue;
6075
6275
  const targetValue = result[key];
6276
+ // Optional adapter props are commonly forwarded as undefined. Preserve
6277
+ // the existing/default config in that case instead of erasing a section.
6278
+ if (sourceValue === undefined)
6279
+ continue;
6076
6280
  if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) {
6077
6281
  result[key] = this._mergeConfig(targetValue && typeof targetValue === 'object' ? targetValue : {}, sourceValue);
6078
6282
  }
@@ -6114,8 +6318,9 @@ class EnhancedSelect extends HTMLElement {
6114
6318
  const hasSomethingToClear = (clearSelection && hasSelection) || (clearSearch && hasSearch);
6115
6319
  const hideWhenEmpty = this._config.clearControl.hideWhenEmpty !== false;
6116
6320
  const visible = enabled && (!hideWhenEmpty || hasSomethingToClear);
6117
- this._inputContainer.classList.toggle('has-clear-control', enabled);
6118
- this._arrowContainer.classList.toggle('with-clear-control', enabled);
6321
+ // Reserve the action area only while the clear control is actually visible.
6322
+ this._inputContainer.classList.toggle('has-clear-control', visible);
6323
+ this._arrowContainer.classList.toggle('with-clear-control', visible);
6119
6324
  this._clearControl.hidden = !visible;
6120
6325
  this._clearControl.disabled = !hasSomethingToClear;
6121
6326
  this._clearControl.setAttribute('aria-hidden', String(!visible));
@@ -6293,7 +6498,7 @@ class EnhancedSelect extends HTMLElement {
6293
6498
  }
6294
6499
  this._optionsContainer.appendChild(fragment);
6295
6500
  if (cursor < filteredIndices.length) {
6296
- requestAnimationFrame(renderChunk);
6501
+ this._requestLifecycleFrame(renderChunk);
6297
6502
  }
6298
6503
  else {
6299
6504
  if (renderCycleId !== this._renderCycleId)
@@ -6371,16 +6576,16 @@ class EnhancedSelect extends HTMLElement {
6371
6576
  showRemoveButton: this._config.selection.mode === 'multi' && this._config.selection.showRemoveButton,
6372
6577
  removeButtonIcon: this._config.selection.removeButtonIcon,
6373
6578
  classMap: this.classMap,
6374
- className: this._config.styles.classNames?.option,
6579
+ className: this._config.styles?.classNames?.option,
6375
6580
  });
6376
- if (this._config.styles.classNames?.option) {
6581
+ if (this._config.styles?.classNames?.option) {
6377
6582
  option.classList.add(...this._config.styles.classNames.option.split(' ').filter(Boolean));
6378
6583
  }
6379
6584
  option.setAttribute('dir', this._config.direction ?? 'ltr');
6380
- if (isSelected && this._config.styles.classNames?.selectedOption) {
6585
+ if (isSelected && this._config.styles?.classNames?.selectedOption) {
6381
6586
  option.classList.add(...this._config.styles.classNames.selectedOption.split(' ').filter(Boolean));
6382
6587
  }
6383
- if (this._state.activeIndex === index && this._config.styles.classNames?.activeOption) {
6588
+ if (this._state.activeIndex === index && this._config.styles?.classNames?.activeOption) {
6384
6589
  option.classList.add(...this._config.styles.classNames.activeOption.split(' ').filter(Boolean));
6385
6590
  }
6386
6591
  if (isDisabled && this._config.styles.classNames?.disabledOption) {
@@ -6569,6 +6774,8 @@ class EnhancedSelect extends HTMLElement {
6569
6774
  /** live set of all connected instances; used to auto-close siblings */
6570
6775
  EnhancedSelect._instances = new Set();
6571
6776
  EnhancedSelect._MIRRORED_STYLES_SCOPE_CLASS = 'smilodon-mirrored-styles-scope';
6777
+ EnhancedSelect._MIRRORED_STYLESHEET_CACHE_LIMIT = 32;
6778
+ EnhancedSelect._mirroredStylesheetTextCache = new Map();
6572
6779
  // Register custom element
6573
6780
  if (!customElements.get('enhanced-select')) {
6574
6781
  customElements.define('enhanced-select', EnhancedSelect);
@@ -6926,7 +7133,8 @@ class PerformanceTelemetry {
6926
7133
  this.rafId = 0;
6927
7134
  this.measuring = false;
6928
7135
  this.observer = null;
6929
- this.workTimes = [];
7136
+ this.workTotal = 0;
7137
+ this.workCount = 0;
6930
7138
  /**
6931
7139
  * Measure frame timing via requestAnimationFrame
6932
7140
  */
@@ -6943,7 +7151,6 @@ class PerformanceTelemetry {
6943
7151
  this.lastFrameTime = now;
6944
7152
  this.rafId = requestAnimationFrame(this.measureFrame);
6945
7153
  };
6946
- this.setupObserver();
6947
7154
  }
6948
7155
  /**
6949
7156
  * Setup PerformanceObserver for long tasks
@@ -6953,12 +7160,15 @@ class PerformanceTelemetry {
6953
7160
  return;
6954
7161
  try {
6955
7162
  this.observer = new PerformanceObserver((list) => {
7163
+ if (!this.measuring)
7164
+ return;
6956
7165
  for (const entry of list.getEntries()) {
6957
7166
  if (entry.entryType === 'longtask' && entry.duration > 50) {
6958
7167
  this.longTasks++;
6959
7168
  }
6960
7169
  if (entry.entryType === 'measure') {
6961
- this.workTimes.push(entry.duration);
7170
+ this.workTotal += entry.duration;
7171
+ this.workCount += 1;
6962
7172
  }
6963
7173
  }
6964
7174
  });
@@ -6983,9 +7193,11 @@ class PerformanceTelemetry {
6983
7193
  return;
6984
7194
  this.measuring = true;
6985
7195
  this.frameTimes = [];
6986
- this.workTimes = [];
7196
+ this.workTotal = 0;
7197
+ this.workCount = 0;
6987
7198
  this.longTasks = 0;
6988
7199
  this.lastFrameTime = performance.now();
7200
+ this.setupObserver();
6989
7201
  this.measureFrame();
6990
7202
  }
6991
7203
  /**
@@ -6997,6 +7209,10 @@ class PerformanceTelemetry {
6997
7209
  cancelAnimationFrame(this.rafId);
6998
7210
  this.rafId = 0;
6999
7211
  }
7212
+ if (this.observer) {
7213
+ this.observer.disconnect();
7214
+ this.observer = null;
7215
+ }
7000
7216
  }
7001
7217
  /**
7002
7218
  * Mark start of work for custom measurement
@@ -7008,10 +7224,15 @@ class PerformanceTelemetry {
7008
7224
  * Mark end of work and measure duration
7009
7225
  */
7010
7226
  markEnd(label) {
7011
- performance.mark(`${label}-end`);
7012
- performance.measure(label, `${label}-start`, `${label}-end`);
7013
- const measure = performance.getEntriesByName(label, 'measure')[0];
7014
- return measure ? measure.duration : 0;
7227
+ const startMark = `${label}-start`;
7228
+ const endMark = `${label}-end`;
7229
+ performance.mark(endMark);
7230
+ const measure = performance.measure(label, startMark, endMark);
7231
+ const duration = measure ? measure.duration : 0;
7232
+ performance.clearMarks(startMark);
7233
+ performance.clearMarks(endMark);
7234
+ performance.clearMeasures(label);
7235
+ return duration;
7015
7236
  }
7016
7237
  /**
7017
7238
  * Get current metrics snapshot
@@ -7023,8 +7244,8 @@ class PerformanceTelemetry {
7023
7244
  const fps = avgFrameTime > 0 ? 1000 / avgFrameTime : 0;
7024
7245
  const longFrames = this.frameTimes.filter(t => t > 16.67).length;
7025
7246
  const droppedFrames = this.frameTimes.filter(t => t > 33.33).length; // > 2 frames
7026
- const avgMainThreadWork = this.workTimes.length > 0
7027
- ? this.workTimes.reduce((a, b) => a + b, 0) / this.workTimes.length
7247
+ const avgMainThreadWork = this.workCount > 0
7248
+ ? this.workTotal / this.workCount
7028
7249
  : 0;
7029
7250
  const metrics = {
7030
7251
  frames: {
@@ -7083,7 +7304,8 @@ class PerformanceTelemetry {
7083
7304
  */
7084
7305
  reset() {
7085
7306
  this.frameTimes = [];
7086
- this.workTimes = [];
7307
+ this.workTotal = 0;
7308
+ this.workCount = 0;
7087
7309
  this.longTasks = 0;
7088
7310
  }
7089
7311
  /**