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