@yunlefun-home/air-conditioner-widget 0.4.3 → 0.4.4

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.
@@ -154,6 +154,7 @@ var AirConditionerWidget = (function(exports) {
154
154
  const readyTimeoutMs = 1500;
155
155
  const fallbackTweenStepMs = 100;
156
156
  const curveLength = 64;
157
+ const defaultAudioCache = /* @__PURE__ */ new Map();
157
158
  function sourceUrl(element) {
158
159
  return element?.currentSrc || element?.src || "";
159
160
  }
@@ -165,7 +166,12 @@ var AirConditionerWidget = (function(exports) {
165
166
  function createDefaultAudioContext() {
166
167
  const scope = globalThis;
167
168
  const AudioContextConstructor = scope.AudioContext ?? scope.webkitAudioContext;
168
- return AudioContextConstructor ? new AudioContextConstructor() : null;
169
+ if (!AudioContextConstructor) return null;
170
+ try {
171
+ return new AudioContextConstructor({ latencyHint: "interactive" });
172
+ } catch {
173
+ return new AudioContextConstructor();
174
+ }
169
175
  }
170
176
  /**
171
177
  * 合成一声很轻的「嗒」:音高快速下滑的正弦波,短促起音、指数衰减,像水珠落在窗台上。
@@ -187,6 +193,32 @@ var AirConditionerWidget = (function(exports) {
187
193
  oscillator.onended = () => gain.disconnect();
188
194
  }
189
195
  /**
196
+ * 样本还没解码出来时的按键声:很短的一声「嘀」,不依赖文件。
197
+ * 每次调用都是新的振荡器,连按不会互相等待。
198
+ */
199
+ function playClick(context, output) {
200
+ if (typeof context.createOscillator !== "function") return false;
201
+ try {
202
+ const start = context.currentTime;
203
+ const oscillator = context.createOscillator();
204
+ const gain = context.createGain();
205
+ oscillator.type = "sine";
206
+ oscillator.frequency.setValueAtTime(2400, start);
207
+ oscillator.frequency.exponentialRampToValueAtTime(1400, start + .02);
208
+ gain.gain.setValueAtTime(1e-4, start);
209
+ gain.gain.exponentialRampToValueAtTime(.15, start + .002);
210
+ gain.gain.exponentialRampToValueAtTime(1e-4, start + .045);
211
+ oscillator.connect(gain);
212
+ gain.connect(output);
213
+ oscillator.start(start);
214
+ oscillator.stop(start + .05);
215
+ oscillator.onended = () => gain.disconnect();
216
+ return true;
217
+ } catch {
218
+ return false;
219
+ }
220
+ }
221
+ /**
190
222
  * 等功率淡入 / 淡出曲线,噪声类声音交叉淡化时中段不会变小。
191
223
  */
192
224
  function fadeCurve(direction) {
@@ -205,6 +237,20 @@ var AirConditionerWidget = (function(exports) {
205
237
  element.load();
206
238
  Promise.resolve(element.play()).catch(() => {});
207
239
  }
240
+ /**
241
+ * 重播一段已经挂在元素上的短音效。
242
+ * `load()` 会丢掉预加载的数据并重新选资源,按键「嘀」声因此会晚一拍。
243
+ */
244
+ function replayElement(element) {
245
+ if (!element) return;
246
+ try {
247
+ if (element.currentTime > 0) {
248
+ element.pause?.();
249
+ element.currentTime = 0;
250
+ }
251
+ } catch {}
252
+ Promise.resolve(element.play()).catch(() => {});
253
+ }
208
254
  function stopElement(element) {
209
255
  if (!element) return;
210
256
  if (element.pause) element.pause();
@@ -217,7 +263,8 @@ var AirConditionerWidget = (function(exports) {
217
263
  * 风声变小、并不定时随压缩机发力起伏。环境不支持或音频无法获取时退回
218
264
  * `<audio>` 元素。
219
265
  *
220
- * 需在用户交互(点击遥控器)里首次调用,浏览器才允许发声。
266
+ * 创建控制器时就会开始下载并解码,此时不会出声。浏览器要等用户手势里
267
+ * `resume()` 之后才允许播放,因此第一次 `beep()` / 开关机仍需发生在点击回调中。
221
268
  *
222
269
  * @param elements 三个音频元素;Web Audio 会从它们的 `src` 获取音频
223
270
  * @param options 声音模式与可替换的环境依赖
@@ -236,6 +283,10 @@ var AirConditionerWidget = (function(exports) {
236
283
  /** 每次开关机自增,丢弃过期的异步回调 */
237
284
  let session = 0;
238
285
  const timers = /* @__PURE__ */ new Set();
286
+ /** 同一地址只拉取一次;decodeAudioData 会拆掉传入的 buffer,所以每次给它一份拷贝 */
287
+ const audioCache = options.loadAudioData ? /* @__PURE__ */ new Map() : defaultAudioCache;
288
+ /** 第一次按下时提前 resume,等 click 里真正 beep 时设备已经醒了 */
289
+ let stopUnlock;
239
290
  /** `<audio>` 播放时的风声相对音量 */
240
291
  let fallbackFanLevel = 1;
241
292
  let fallbackTween;
@@ -280,44 +331,81 @@ var AirConditionerWidget = (function(exports) {
280
331
  function ensureEngine() {
281
332
  if (engine !== void 0) return engine;
282
333
  engine = createEngine();
334
+ if (engine) stopUnlock = armGestureUnlock();
283
335
  return engine;
284
336
  }
337
+ /** 手势里唤醒音频设备。已经在跑时什么都不做。 */
338
+ function unlockPlayback() {
339
+ const web = ensureEngine();
340
+ if (web) resume(web);
341
+ }
342
+ function loadCached(url) {
343
+ let pending = audioCache.get(url);
344
+ if (!pending) {
345
+ const load = options.loadAudioData ?? fetchAudioData;
346
+ pending = new Promise((resolve, reject) => {
347
+ try {
348
+ resolve(load(url));
349
+ } catch (error) {
350
+ reject(error);
351
+ }
352
+ }).catch((error) => {
353
+ audioCache.delete(url);
354
+ throw error;
355
+ });
356
+ audioCache.set(url, pending);
357
+ }
358
+ return pending.then((data) => data.slice(0));
359
+ }
285
360
  function createEngine() {
286
361
  if (options.webAudio === false) return null;
287
- let context;
288
362
  try {
289
- context = (options.createAudioContext ?? createDefaultAudioContext)();
363
+ const context = (options.createAudioContext ?? createDefaultAudioContext)();
364
+ if (!context) return null;
365
+ const master = context.createGain();
366
+ master.gain.value = volume();
367
+ master.connect(context.destination);
368
+ const buffers = {};
369
+ const decode = async (name) => {
370
+ const url = sourceUrl(elements[name]);
371
+ if (!url || buffers[name]) return;
372
+ try {
373
+ buffers[name] = await context.decodeAudioData(await loadCached(url));
374
+ } catch {}
375
+ };
376
+ return {
377
+ context,
378
+ master,
379
+ buffers,
380
+ ready: Promise.all([
381
+ "beep",
382
+ "start",
383
+ "work"
384
+ ].map(decode)).then(() => Boolean(buffers.start && buffers.work))
385
+ };
290
386
  } catch {
291
387
  return null;
292
388
  }
293
- if (!context) return null;
294
- const master = context.createGain();
295
- master.gain.value = volume();
296
- master.connect(context.destination);
297
- const buffers = {};
298
- const load = options.loadAudioData ?? fetchAudioData;
299
- const decode = async (name) => {
300
- const url = sourceUrl(elements[name]);
301
- if (!url) return;
302
- try {
303
- buffers[name] = await context.decodeAudioData(await load(url));
304
- } catch {}
305
- };
306
- const ready = Promise.all([
307
- "beep",
308
- "start",
309
- "work"
310
- ].map(decode)).then(() => Boolean(buffers.start && buffers.work));
311
- return {
312
- context,
313
- master,
314
- buffers,
315
- ready
316
- };
317
389
  }
318
390
  function resume(web) {
319
391
  if (web.context.state === "suspended") Promise.resolve(web.context.resume()).catch(() => {});
320
392
  }
393
+ /**
394
+ * pointerdown / keydown 比 click 更早,也比温度键的按下回调更早(捕获阶段)。
395
+ * 监听一直留着:手机切走再回来时上下文会重新被挂起。
396
+ */
397
+ function armGestureUnlock() {
398
+ if (typeof document === "undefined") return () => {};
399
+ const onGesture = () => {
400
+ unlockPlayback();
401
+ };
402
+ document.addEventListener("pointerdown", onGesture, true);
403
+ document.addEventListener("keydown", onGesture, true);
404
+ return () => {
405
+ document.removeEventListener("pointerdown", onGesture, true);
406
+ document.removeEventListener("keydown", onGesture, true);
407
+ };
408
+ }
321
409
  function waitReady(web) {
322
410
  return Promise.race([web.ready, new Promise((resolve) => setTimeout(resolve, readyTimeoutMs, false))]);
323
411
  }
@@ -394,7 +482,7 @@ var AirConditionerWidget = (function(exports) {
394
482
  quiet();
395
483
  }, soundTimings.settleAfterMs);
396
484
  }
397
- function startWeb(web) {
485
+ function startWeb(web, withStart = true) {
398
486
  const output = web.context.createGain();
399
487
  output.connect(web.master);
400
488
  const fan = web.context.createGain();
@@ -407,9 +495,14 @@ var AirConditionerWidget = (function(exports) {
407
495
  };
408
496
  run = target;
409
497
  const now = web.context.currentTime;
410
- track(target, playBuffer(web, web.buffers.start, output, now));
411
- loopFan(web, target, now + soundTimings.startDelayMs / 1e3);
412
- later(startFanCycle, soundTimings.startDelayMs);
498
+ if (withStart) {
499
+ track(target, playBuffer(web, web.buffers.start, output, now));
500
+ loopFan(web, target, now + soundTimings.startDelayMs / 1e3);
501
+ later(startFanCycle, soundTimings.startDelayMs);
502
+ } else {
503
+ loopFan(web, target, now);
504
+ startFanCycle();
505
+ }
413
506
  }
414
507
  function stopWeb(fadeMs) {
415
508
  const target = run;
@@ -428,12 +521,10 @@ var AirConditionerWidget = (function(exports) {
428
521
  });
429
522
  setTimeout(() => target.output.disconnect(), fadeMs + 100);
430
523
  }
431
- function startFallback() {
524
+ function startFallback(withStart = true) {
432
525
  const { start, work } = elements;
433
526
  stopElement(work);
434
- applyElementVolume(start);
435
- playElement(start);
436
- later(() => {
527
+ const beginWork = () => {
437
528
  if (!work) return;
438
529
  fallbackFanLevel = 0;
439
530
  applyElementVolume(work, 0);
@@ -441,14 +532,21 @@ var AirConditionerWidget = (function(exports) {
441
532
  playElement(work);
442
533
  tweenFallbackFan(initialFanLevel(), soundTimings.loopCrossfadeMs);
443
534
  startFanCycle();
444
- }, soundTimings.startDelayMs);
535
+ };
536
+ if (!withStart) {
537
+ beginWork();
538
+ return;
539
+ }
540
+ applyElementVolume(start);
541
+ playElement(start);
542
+ later(beginWork, soundTimings.startDelayMs);
445
543
  }
446
544
  function stopFallback(fadeMs) {
447
545
  stopElement(elements.start);
448
546
  if (fadeMs > 0) tweenFallbackFan(0, fadeMs, () => stopElement(elements.work));
449
547
  else stopElement(elements.work);
450
548
  }
451
- function powerOn() {
549
+ function powerOn(withStart = true) {
452
550
  const id = ++session;
453
551
  fanRunning = false;
454
552
  fanCycle++;
@@ -458,14 +556,14 @@ var AirConditionerWidget = (function(exports) {
458
556
  stopFallback(0);
459
557
  const web = ensureEngine();
460
558
  if (!web) {
461
- startFallback();
559
+ startFallback(withStart);
462
560
  return;
463
561
  }
464
562
  resume(web);
465
563
  waitReady(web).then((ok) => {
466
564
  if (id !== session) return;
467
- if (ok) startWeb(web);
468
- else startFallback();
565
+ if (ok) startWeb(web, withStart);
566
+ else startFallback(withStart);
469
567
  });
470
568
  }
471
569
  function powerOff() {
@@ -476,31 +574,43 @@ var AirConditionerWidget = (function(exports) {
476
574
  stopWeb(soundTimings.stopFadeMs);
477
575
  stopFallback(soundTimings.stopFadeMs);
478
576
  }
577
+ if (options.webAudio !== false) ensureEngine();
479
578
  return {
579
+ unlock() {
580
+ unlockPlayback();
581
+ },
480
582
  beep() {
481
583
  if (soundMode === "mute") return;
482
584
  const web = ensureEngine();
483
585
  if (web) {
484
586
  resume(web);
485
587
  if (web.buffers.beep) {
486
- playBuffer(web, web.buffers.beep, web.master, web.context.currentTime);
588
+ const source = playBuffer(web, web.buffers.beep, web.master, web.context.currentTime);
589
+ source.onended = () => {
590
+ try {
591
+ source.disconnect();
592
+ } catch {}
593
+ };
487
594
  return;
488
595
  }
596
+ if (playClick(web.context, web.master)) return;
489
597
  }
490
598
  applyElementVolume(elements.beep);
491
- playElement(elements.beep);
599
+ replayElement(elements.beep);
492
600
  },
493
601
  drip() {
494
602
  if (soundMode !== "normal") return;
495
603
  const web = ensureEngine();
496
- if (!web || typeof web.context.createOscillator !== "function") return;
497
- resume(web);
604
+ if (!web || web.context.state !== "running" || typeof web.context.createOscillator !== "function") return;
498
605
  playDrip(web.context, web.master);
499
606
  },
500
607
  toggleStatusAudio(previousStatus) {
501
608
  if (previousStatus) powerOff();
502
609
  else powerOn();
503
610
  },
611
+ resumeFan() {
612
+ powerOn(false);
613
+ },
504
614
  setSoundMode(mode) {
505
615
  soundMode = mode;
506
616
  if (engine) engine.master.gain.setTargetAtTime(volume(), engine.context.currentTime, .08);
@@ -529,6 +639,8 @@ var AirConditionerWidget = (function(exports) {
529
639
  cancelFallbackTween();
530
640
  stopWeb(0);
531
641
  stopFallback(0);
642
+ stopUnlock?.();
643
+ stopUnlock = void 0;
532
644
  if (engine && !options.createAudioContext) Promise.resolve(engine.context.close()).catch(() => {});
533
645
  engine = null;
534
646
  }
@@ -646,23 +758,38 @@ var AirConditionerWidget = (function(exports) {
646
758
  const matchMedia = globalThis.matchMedia;
647
759
  if (typeof matchMedia !== "function" || !matchMedia(finePointerQuery).matches || matchMedia("(prefers-reduced-motion: reduce)").matches) return () => {};
648
760
  let frame = 0;
649
- const schedule = (rotateX, rotateY) => {
650
- cancelAnimationFrame(frame);
651
- frame = requestAnimationFrame(() => onTilt(rotateX, rotateY));
761
+ let pendingX = 0;
762
+ let pendingY = 0;
763
+ let tilted = false;
764
+ const apply = (rotateX, rotateY) => {
765
+ tilted = rotateX !== 0 || rotateY !== 0;
766
+ onTilt(rotateX, rotateY);
652
767
  };
653
768
  const onMove = (event) => {
654
- const rect = target.getBoundingClientRect();
655
- if (!rect.width || !rect.height) return;
656
- const x = (event.clientX - rect.left) / rect.width - .5;
657
- const y = (event.clientY - rect.top) / rect.height - .5;
658
- const round = (value) => Math.round(value * 100) / 100;
659
- schedule(round(-y * 2 * maxTilt), round(x * 2 * maxTilt));
769
+ pendingX = event.clientX;
770
+ pendingY = event.clientY;
771
+ if (frame) return;
772
+ frame = requestAnimationFrame(() => {
773
+ frame = 0;
774
+ const rect = target.getBoundingClientRect();
775
+ if (!rect.width || !rect.height) return;
776
+ const x = (pendingX - rect.left) / rect.width - .5;
777
+ const y = (pendingY - rect.top) / rect.height - .5;
778
+ const round = (value) => Math.round(value * 100) / 100;
779
+ apply(round(-y * 2 * maxTilt), round(x * 2 * maxTilt));
780
+ });
781
+ };
782
+ const onLeave = () => {
783
+ if (frame) {
784
+ cancelAnimationFrame(frame);
785
+ frame = 0;
786
+ }
787
+ if (tilted) apply(0, 0);
660
788
  };
661
- const onLeave = () => schedule(0, 0);
662
- target.addEventListener("pointermove", onMove);
663
- target.addEventListener("pointerleave", onLeave);
789
+ target.addEventListener("pointermove", onMove, { passive: true });
790
+ target.addEventListener("pointerleave", onLeave, { passive: true });
664
791
  return () => {
665
- cancelAnimationFrame(frame);
792
+ onLeave();
666
793
  target.removeEventListener("pointermove", onMove);
667
794
  target.removeEventListener("pointerleave", onLeave);
668
795
  };
@@ -683,27 +810,34 @@ var AirConditionerWidget = (function(exports) {
683
810
  let timer;
684
811
  let wait = interval;
685
812
  let last;
813
+ let disposed = false;
814
+ let generation = 0;
686
815
  const stop = () => {
816
+ generation++;
687
817
  clearTimeout(timer);
688
818
  timer = void 0;
689
819
  };
690
- const tick = () => {
820
+ const tick = (press) => {
821
+ if (disposed || press !== generation) return;
691
822
  if (value && value() === last) return stop();
692
823
  last = value?.();
693
824
  fire();
825
+ if (disposed || press !== generation) return;
694
826
  wait = Math.max(minInterval, wait * .85);
695
- timer = setTimeout(tick, wait);
827
+ timer = setTimeout(tick, wait, press);
696
828
  };
697
829
  const onPointerDown = (event) => {
698
- if (event.button !== 0) return;
830
+ if (disposed || event.button !== 0) return;
699
831
  stop();
832
+ const press = generation;
700
833
  last = value?.();
701
834
  fire();
835
+ if (disposed || press !== generation) return;
702
836
  wait = interval;
703
- timer = setTimeout(tick, delay);
837
+ timer = setTimeout(tick, delay, press);
704
838
  };
705
839
  const onClick = (event) => {
706
- if (event.detail === 0) fire();
840
+ if (!disposed && event.detail === 0) fire();
707
841
  };
708
842
  const onContextMenu = (event) => event.preventDefault();
709
843
  element.addEventListener("pointerdown", onPointerDown);
@@ -713,6 +847,7 @@ var AirConditionerWidget = (function(exports) {
713
847
  element.addEventListener("click", onClick);
714
848
  element.addEventListener("contextmenu", onContextMenu);
715
849
  return () => {
850
+ disposed = true;
716
851
  stop();
717
852
  element.removeEventListener("pointerdown", onPointerDown);
718
853
  element.removeEventListener("pointerup", stop);
@@ -963,7 +1098,7 @@ var AirConditionerWidget = (function(exports) {
963
1098
  ...persistedState,
964
1099
  ...options.initialState
965
1100
  }, limits);
966
- const listeners = /* @__PURE__ */ new Set();
1101
+ const listeners = /* @__PURE__ */ new Map();
967
1102
  return {
968
1103
  getState() {
969
1104
  return state;
@@ -980,14 +1115,18 @@ var AirConditionerWidget = (function(exports) {
980
1115
  };
981
1116
  state = nextState;
982
1117
  writeAcState(storage, storageKey, nextState);
983
- listeners.forEach((listener) => listener(event));
1118
+ for (const [listener, subscription] of [...listeners]) if (listeners.get(listener) === subscription) listener(event);
984
1119
  if (notification) options.onNotify?.(notification, event);
985
1120
  return event;
986
1121
  },
987
1122
  subscribe(listener) {
988
- listeners.add(listener);
1123
+ let subscription = listeners.get(listener);
1124
+ if (!subscription) {
1125
+ subscription = Symbol("subscription");
1126
+ listeners.set(listener, subscription);
1127
+ }
989
1128
  return () => {
990
- listeners.delete(listener);
1129
+ if (listeners.get(listener) === subscription) listeners.delete(listener);
991
1130
  };
992
1131
  }
993
1132
  };
@@ -1277,19 +1416,21 @@ var AirConditionerWidget = (function(exports) {
1277
1416
  }
1278
1417
  /* @ac-motion-tokens:end */
1279
1418
 
1280
- html.dark .acw-root,
1419
+ :host-context(html.dark) .acw-root,
1281
1420
  .acw-root.dark {
1282
1421
  --acw-text-color: #fafafa;
1283
1422
  }
1284
1423
 
1285
- html.dark .acw-mist,
1424
+ :host-context(html.dark) .acw-mist,
1286
1425
  .acw-root.dark .acw-mist {
1287
- --acw-mist-color: rgba(214, 234, 252, 0.5);
1426
+ --acw-mist-color: rgba(196, 228, 255, 0.58);
1427
+ mix-blend-mode: screen;
1288
1428
  }
1289
1429
 
1290
1430
  @media (prefers-color-scheme: dark) {
1291
1431
  .acw-root:not(.light) .acw-mist {
1292
- --acw-mist-color: rgba(214, 234, 252, 0.5);
1432
+ --acw-mist-color: rgba(196, 228, 255, 0.58);
1433
+ mix-blend-mode: screen;
1293
1434
  }
1294
1435
  }
1295
1436
 
@@ -1299,32 +1440,42 @@ html.dark .acw-mist,
1299
1440
  }
1300
1441
  }
1301
1442
 
1302
- /* 暗色下换成深色纸,仍按模式着色 */
1303
- html.dark .acw-note,
1443
+ /* 暗色下保持白色家电一体的柔光浅纸,仅略微压暗底色并加深阴影 */
1444
+ :host-context(html.dark) .acw-note,
1304
1445
  .acw-root.dark .acw-note {
1305
- --acw-note-bg: #1d2733;
1306
- --acw-note-text: #e3ecf5;
1307
- --acw-note-accent: #64b5f6;
1446
+ --acw-note-bg: #ecf2f9;
1447
+ --acw-note-bg-bottom: #e0e9f3;
1448
+ --acw-note-text: #1e293b;
1449
+ --acw-note-accent: #2f7fd6;
1450
+ --acw-note-shadow:
1451
+ 0 10px 24px -8px rgba(0, 0, 0, 0.6),
1452
+ 0 2px 4px rgba(0, 0, 0, 0.35);
1308
1453
  }
1309
1454
 
1310
- html.dark .acw-note[data-mode="hot"],
1455
+ :host-context(html.dark) .acw-note[data-mode="hot"],
1311
1456
  .acw-root.dark .acw-note[data-mode="hot"] {
1312
- --acw-note-bg: #2d241d;
1313
- --acw-note-text: #f5e9de;
1314
- --acw-note-accent: #ffb74d;
1457
+ --acw-note-bg: #f6ede3;
1458
+ --acw-note-bg-bottom: #ede0d2;
1459
+ --acw-note-text: #3b2a1e;
1460
+ --acw-note-accent: #d9772b;
1315
1461
  }
1316
1462
 
1317
1463
  @media (prefers-color-scheme: dark) {
1318
1464
  .acw-root:not(.light) .acw-note {
1319
- --acw-note-bg: #1d2733;
1320
- --acw-note-text: #e3ecf5;
1321
- --acw-note-accent: #64b5f6;
1465
+ --acw-note-bg: #ecf2f9;
1466
+ --acw-note-bg-bottom: #e0e9f3;
1467
+ --acw-note-text: #1e293b;
1468
+ --acw-note-accent: #2f7fd6;
1469
+ --acw-note-shadow:
1470
+ 0 10px 24px -8px rgba(0, 0, 0, 0.6),
1471
+ 0 2px 4px rgba(0, 0, 0, 0.35);
1322
1472
  }
1323
1473
 
1324
1474
  .acw-root:not(.light) .acw-note[data-mode="hot"] {
1325
- --acw-note-bg: #2d241d;
1326
- --acw-note-text: #f5e9de;
1327
- --acw-note-accent: #ffb74d;
1475
+ --acw-note-bg: #f6ede3;
1476
+ --acw-note-bg-bottom: #ede0d2;
1477
+ --acw-note-text: #3b2a1e;
1478
+ --acw-note-accent: #d9772b;
1328
1479
  }
1329
1480
  }
1330
1481
 
@@ -1608,7 +1759,7 @@ html.dark .acw-note[data-mode="hot"],
1608
1759
  animation-play-state: paused;
1609
1760
  }
1610
1761
 
1611
- .acw-unit[data-status="on"][data-mode="cold"] .acw-mist i {
1762
+ .acw-unit[data-status="on"][data-mode="cold"][data-mist="on"] .acw-mist i {
1612
1763
  animation-play-state: running;
1613
1764
  }
1614
1765
 
@@ -1772,11 +1923,11 @@ html.dark .acw-note[data-mode="hot"],
1772
1923
  pointer-events: none;
1773
1924
  }
1774
1925
 
1775
- .acw-unit[data-status="on"] .acw-selftest {
1926
+ .acw-unit[data-status="on"]:not([data-skip-selftest]) .acw-selftest {
1776
1927
  animation: acw-selftest 560ms steps(1, end) both;
1777
1928
  }
1778
1929
 
1779
- .acw-unit[data-status="on"] .acw-readout {
1930
+ .acw-unit[data-status="on"]:not([data-skip-selftest]) .acw-readout {
1780
1931
  animation: acw-selftest-reveal 560ms steps(1, end) both;
1781
1932
  }
1782
1933
 
@@ -2040,8 +2191,8 @@ html.dark .acw-note[data-mode="hot"],
2040
2191
  opacity: 1;
2041
2192
  }
2042
2193
 
2043
- .acw-unit[data-status="on"] .acw-wind-line::before,
2044
- .acw-unit[data-status="on"] .acw-wind-line::after {
2194
+ .acw-unit[data-status="on"][data-mode="cold"] .acw-wind-line::before,
2195
+ .acw-unit[data-status="on"][data-mode="hot"] .acw-wind-line::after {
2045
2196
  animation-play-state: running;
2046
2197
  }
2047
2198
 
@@ -2424,6 +2575,9 @@ html.dark .acw-note[data-mode="hot"],
2424
2575
  --acw-note-bg: #f4f9ff;
2425
2576
  --acw-note-text: #22313f;
2426
2577
  --acw-note-accent: #1e88e5;
2578
+ --acw-note-shadow:
2579
+ 0 1px 0 rgba(0, 0, 0, 0.04),
2580
+ 0 10px 18px -10px rgba(0, 0, 0, 0.45);
2427
2581
  /* 顶边落在出风线的下半截:风线仍在纸条上方,看起来是被风推出来的 */
2428
2582
  position: absolute;
2429
2583
  top: calc(-1 * var(--acw-note-lift, 42px));
@@ -2438,11 +2592,9 @@ html.dark .acw-note[data-mode="hot"],
2438
2592
  max-width: min(300px, 92%);
2439
2593
  padding: 9px 14px 8px 9px;
2440
2594
  border-radius: 3px 3px 10px 10px;
2441
- background: var(--acw-note-bg);
2595
+ background: linear-gradient(to bottom, var(--acw-note-bg), var(--acw-note-bg-bottom, var(--acw-note-bg)));
2442
2596
  color: var(--acw-note-text);
2443
- box-shadow:
2444
- 0 1px 0 rgba(0, 0, 0, 0.04),
2445
- 0 10px 18px -10px rgba(0, 0, 0, 0.45);
2597
+ box-shadow: var(--acw-note-shadow);
2446
2598
  font-size: 13px;
2447
2599
  line-height: 1.35;
2448
2600
  translate: -50% 0;
@@ -2653,7 +2805,7 @@ html.dark .acw-note[data-mode="hot"],
2653
2805
  `;
2654
2806
  //#endregion
2655
2807
  //#region src/cdn-assets.ts
2656
- const base = `https://cdn.jsdelivr.net/npm/@yunlefun-home/air-conditioner-widget@0.4.3/dist/embed`;
2808
+ const base = `https://cdn.jsdelivr.net/npm/@yunlefun-home/air-conditioner-widget@0.4.4/dist/embed`;
2657
2809
  /** Optional CDN resources pinned to this installed package's exact version. */
2658
2810
  const cdnAssets = {
2659
2811
  assetsBaseUrl: `${base}/assets`,
@@ -2701,17 +2853,31 @@ html.dark .acw-note[data-mode="hot"],
2701
2853
  ${dotRow(acEnergyLabel.footer)}
2702
2854
  </div>`;
2703
2855
  }
2856
+ let sharedStyleSheet;
2857
+ function getSharedStyleSheet() {
2858
+ if (sharedStyleSheet !== void 0) return sharedStyleSheet;
2859
+ try {
2860
+ if (typeof CSSStyleSheet === "function" && "replaceSync" in CSSStyleSheet.prototype) {
2861
+ const sheet = new CSSStyleSheet();
2862
+ sheet.replaceSync(`${widgetStyleText}${floatingStyleText}`);
2863
+ sharedStyleSheet = sheet;
2864
+ return sheet;
2865
+ }
2866
+ } catch {}
2867
+ sharedStyleSheet = null;
2868
+ return null;
2869
+ }
2704
2870
  /**
2705
2871
  * 只在挂载时写入一次的骨架(结构与 Vue 版 AirConditionerWidget 一致);之后的状态变化通过
2706
2872
  * `updateWidget` 增量更新,这样 CSS 过渡才能播放,按钮的键盘焦点也不会因整块重建而丢失。
2707
2873
  */
2708
2874
  function widgetTemplate(view) {
2709
- const audio = view.audio ? `<audio data-audio="beep" src="${escapeHtml(view.audio.beep)}" preload="auto"></audio>
2710
- <audio data-audio="start" src="${escapeHtml(view.audio.start)}" preload="auto"></audio>
2711
- <audio data-audio="work" src="${escapeHtml(view.audio.work)}" preload="auto"></audio>` : "";
2875
+ const audio = view.audio ? `<audio data-audio="beep" src="${escapeHtml(view.audio.beep)}" preload="none"></audio>
2876
+ <audio data-audio="start" src="${escapeHtml(view.audio.start)}" preload="none"></audio>
2877
+ <audio data-audio="work" src="${escapeHtml(view.audio.work)}" preload="none"></audio>` : "";
2712
2878
  const logo = view.logoUrl ? `<div class="acw-logo"><a href="${escapeHtml(view.logoHref)}" target="_blank" rel="noreferrer noopener"${view.title ? ` title="${escapeHtml(view.title)}"` : ""} aria-label="${escapeHtml(view.title ?? "Air Conditioner")}"><img src="${escapeHtml(view.logoUrl)}" alt=""></a></div>` : "";
2713
2879
  return `
2714
- <style>${widgetStyleText}${floatingStyleText}</style>
2880
+ ${view.inlineStyle ? `<style>${widgetStyleText}${floatingStyleText}</style>` : ""}
2715
2881
  <div class="acw-root">
2716
2882
  ${audio}
2717
2883
  <div class="acw-unit">
@@ -2744,7 +2910,7 @@ html.dark .acw-note[data-mode="hot"],
2744
2910
  <div class="acw-lcd" role="img">
2745
2911
  <div class="acw-lcd-main">
2746
2912
  <span class="acw-lcd-mode-slot"></span>
2747
- <span class="acw-lcd-temp acw-digit"></span>
2913
+ <span class="acw-lcd-temp acw-digit"><span class="acw-lcd-temp-value"></span><small>°C</small></span>
2748
2914
  </div>
2749
2915
  <div class="acw-lcd-status" aria-hidden="true">
2750
2916
  <span class="acw-lcd-wind"><i></i><i></i><i></i><b>自动</b></span>
@@ -2772,6 +2938,29 @@ html.dark .acw-note[data-mode="hot"],
2772
2938
  </div>
2773
2939
  `;
2774
2940
  }
2941
+ function collectWidgetRefs(shadowRoot) {
2942
+ return {
2943
+ root: shadowRoot.querySelector(".acw-root"),
2944
+ unit: shadowRoot.querySelector(".acw-unit"),
2945
+ modeIcon: shadowRoot.querySelector(".acw-mode-icon"),
2946
+ temperature: shadowRoot.querySelector(".acw-temperature"),
2947
+ led: shadowRoot.querySelector(".acw-led"),
2948
+ wind: shadowRoot.querySelector(".acw-wind"),
2949
+ lcd: shadowRoot.querySelector(".acw-lcd"),
2950
+ lcdTempValue: shadowRoot.querySelector(".acw-lcd-temp-value"),
2951
+ lcdModeSlot: shadowRoot.querySelector(".acw-lcd-mode-slot"),
2952
+ lcdSoundSlot: shadowRoot.querySelector(".acw-lcd-sound-slot"),
2953
+ powerButton: shadowRoot.querySelector(".acw-button-power"),
2954
+ coldButton: shadowRoot.querySelector(".acw-button-cold"),
2955
+ hotButton: shadowRoot.querySelector(".acw-button-hot"),
2956
+ fanButton: shadowRoot.querySelector(".acw-button-fan"),
2957
+ swingButton: shadowRoot.querySelector(".acw-button-swing"),
2958
+ soundButton: shadowRoot.querySelector(".acw-button-sound"),
2959
+ remoteToggle: shadowRoot.querySelector(".acw-remote-toggle"),
2960
+ remoteToggleLabel: shadowRoot.querySelector(".acw-toggle-label"),
2961
+ remotePanel: shadowRoot.querySelector(".acw-remote-panel")
2962
+ };
2963
+ }
2775
2964
  /**
2776
2965
  * 用新节点替换旧节点,以便重新播放进入动画。
2777
2966
  */
@@ -2779,69 +2968,71 @@ html.dark .acw-note[data-mode="hot"],
2779
2968
  const next = current.cloneNode(false);
2780
2969
  next.textContent = text;
2781
2970
  next.setAttribute(...attribute);
2971
+ next.addEventListener("animationend", () => next.removeAttribute(attribute[0]), { once: true });
2782
2972
  current.replaceWith(next);
2973
+ return next;
2783
2974
  }
2784
- function updateWidget(root, state, previous) {
2975
+ function updateWidget(refs, state, previous) {
2785
2976
  const status = state.status ? "on" : "off";
2786
- for (const element of root.querySelectorAll(".acw-root, .acw-unit")) {
2977
+ const fan = state.fan ?? "auto";
2978
+ for (const element of [refs.root, refs.unit]) {
2787
2979
  element.dataset.mode = state.mode;
2788
2980
  element.dataset.status = status;
2789
2981
  element.dataset.swing = state.swing ? "on" : "off";
2790
- element.dataset.fan = state.fan ?? "auto";
2982
+ element.dataset.fan = fan;
2791
2983
  }
2792
- const mode = root.querySelector(".acw-mode-icon");
2793
- if (!previous) mode.textContent = acModeIcons[state.mode];
2794
- else if (previous.mode !== state.mode) replaceAnimated(mode, acModeIcons[state.mode], ["data-animate", ""]);
2795
- const temperature = root.querySelector(".acw-temperature");
2796
- if (!previous) temperature.textContent = String(state.temperature);
2797
- else if (previous.temperature !== state.temperature) replaceAnimated(temperature, String(state.temperature), ["data-dir", state.temperature > previous.temperature ? "up" : "down"]);
2798
- const unit = root.querySelector(".acw-unit");
2984
+ if (!state.status || previous && previous.status !== state.status) refs.unit.removeAttribute("data-skip-selftest");
2985
+ if (!previous) {
2986
+ refs.modeIcon.textContent = acModeIcons[state.mode];
2987
+ refs.modeIcon.removeAttribute("data-animate");
2988
+ } else if (previous.mode !== state.mode) refs.modeIcon = replaceAnimated(refs.modeIcon, acModeIcons[state.mode], ["data-animate", ""]);
2989
+ if (!previous) {
2990
+ refs.temperature.textContent = String(state.temperature);
2991
+ refs.temperature.removeAttribute("data-dir");
2992
+ } else if (previous.temperature !== state.temperature) refs.temperature = replaceAnimated(refs.temperature, String(state.temperature), ["data-dir", state.temperature > previous.temperature ? "up" : "down"]);
2799
2993
  const condensation = getAcCondensationStyle(state);
2800
- unit.dataset.drip = condensation.drip;
2801
- unit.style.setProperty("--acw-mist", String(condensation.mist));
2802
- if (condensation.dripCycle) unit.style.setProperty("--acw-drip-cycle", condensation.dripCycle);
2803
- else unit.style.removeProperty("--acw-drip-cycle");
2804
- root.querySelector(".acw-led").setAttribute("aria-label", status);
2805
- root.querySelector(".acw-wind").setAttribute("aria-hidden", state.status ? "false" : "true");
2806
- updateRemote(root, state, previous);
2994
+ refs.unit.dataset.drip = condensation.drip;
2995
+ refs.unit.dataset.mist = condensation.mist > 0 ? "on" : "off";
2996
+ refs.unit.style.setProperty("--acw-mist", String(condensation.mist));
2997
+ if (condensation.dripCycle) refs.unit.style.setProperty("--acw-drip-cycle", condensation.dripCycle);
2998
+ else refs.unit.style.removeProperty("--acw-drip-cycle");
2999
+ refs.led.setAttribute("aria-label", status);
3000
+ refs.wind.setAttribute("aria-hidden", state.status ? "false" : "true");
3001
+ updateRemote(refs, state, previous);
2807
3002
  }
2808
3003
  /**
2809
3004
  * 遥控器:小屏与按键状态,结构与 Vue / React 的 RemoteControl 一致。
2810
3005
  */
2811
- function updateRemote(root, state, previous) {
3006
+ function updateRemote(refs, state, previous) {
2812
3007
  const text = getAcRemoteText(state);
2813
- const lcd = root.querySelector(".acw-lcd");
2814
- lcd.setAttribute("aria-label", text.display);
2815
- lcd.dataset.status = state.status ? "on" : "off";
2816
- lcd.dataset.mode = state.mode;
2817
- lcd.dataset.swing = state.swing ? "on" : "off";
2818
- lcd.dataset.fan = state.fan ?? "auto";
2819
- root.querySelector(".acw-lcd-temp").innerHTML = `${state.temperature}<small>°C</small>`;
2820
- const power = root.querySelector(".acw-button-power");
2821
- power.classList.toggle("acw-button-on", state.status);
2822
- power.setAttribute("aria-pressed", String(state.status));
2823
- power.title = text.power;
3008
+ refs.lcd.setAttribute("aria-label", text.display);
3009
+ refs.lcd.dataset.status = state.status ? "on" : "off";
3010
+ refs.lcd.dataset.mode = state.mode;
3011
+ refs.lcd.dataset.swing = state.swing ? "on" : "off";
3012
+ refs.lcd.dataset.fan = state.fan ?? "auto";
3013
+ refs.lcdTempValue.textContent = String(state.temperature);
3014
+ refs.powerButton.classList.toggle("acw-button-on", state.status);
3015
+ refs.powerButton.setAttribute("aria-pressed", String(state.status));
3016
+ refs.powerButton.title = text.power;
2824
3017
  if (previous?.mode !== state.mode) {
2825
- root.querySelector(".acw-lcd-mode-slot").innerHTML = icon(state.mode, 22, "acw-lcd-mode");
2826
- for (const mode of ["cold", "hot"]) root.querySelector(`.acw-button-${mode}`).setAttribute("aria-pressed", String(state.mode === mode));
3018
+ refs.lcdModeSlot.innerHTML = icon(state.mode, 22, "acw-lcd-mode");
3019
+ refs.coldButton.setAttribute("aria-pressed", String(state.mode === "cold"));
3020
+ refs.hotButton.setAttribute("aria-pressed", String(state.mode === "hot"));
2827
3021
  }
2828
3022
  if (previous?.fan !== state.fan) {
2829
- const fan = root.querySelector(".acw-button-fan");
2830
- fan.dataset.fan = state.fan ?? "auto";
2831
- fan.title = text.fan;
3023
+ refs.fanButton.dataset.fan = state.fan ?? "auto";
3024
+ refs.fanButton.title = text.fan;
2832
3025
  }
2833
3026
  if (previous?.swing !== state.swing) {
2834
- const swing = root.querySelector(".acw-button-swing");
2835
- swing.setAttribute("aria-pressed", String(state.swing));
2836
- swing.title = text.swing;
3027
+ refs.swingButton.setAttribute("aria-pressed", String(state.swing));
3028
+ refs.swingButton.title = text.swing;
2837
3029
  }
2838
3030
  if (previous?.sound !== state.sound) {
2839
- const sound = root.querySelector(".acw-button-sound");
2840
- sound.dataset.sound = state.sound;
2841
- sound.title = text.sound;
2842
- sound.innerHTML = icon(acSoundIcons[state.sound], 20);
2843
- root.querySelector(".acw-lcd-sound-slot").innerHTML = icon(acSoundIcons[state.sound], 14, "acw-lcd-sound");
2844
- root.querySelector(".acw-lcd-sound").setAttribute("data-sound", state.sound);
3031
+ refs.soundButton.dataset.sound = state.sound;
3032
+ refs.soundButton.title = text.sound;
3033
+ refs.soundButton.innerHTML = icon(acSoundIcons[state.sound], 20);
3034
+ refs.lcdSoundSlot.innerHTML = icon(acSoundIcons[state.sound], 14, "acw-lcd-sound");
3035
+ refs.lcdSoundSlot.querySelector(".acw-lcd-sound").setAttribute("data-sound", state.sound);
2845
3036
  }
2846
3037
  }
2847
3038
  /** 纸条停留多久后被风吹走,以及吹走动画的时长(与样式里的 acw-note-away 一致) */
@@ -2851,34 +3042,67 @@ html.dark .acw-note[data-mode="hot"],
2851
3042
  * 按 core 的呈现方式显示一条提示:节能建议是「出风口吹出的小纸条」,温度到上下限时
2852
3043
  * 小屏抖一下,设置变化只给读屏播报(结构与 Vue / React 一致)。
2853
3044
  */
2854
- function presentNotification(root, notification, how, state) {
2855
- if (how === "skip") return;
2856
- if (how === "shake") shakeLcd(root);
2857
- if (how !== "note") {
2858
- root.querySelector(".acw-notification-region .acw-sr-only").textContent = notification.message;
2859
- return;
2860
- }
3045
+ function createNotificationView(root) {
2861
3046
  const region = root.querySelector(".acw-notification-region");
2862
- region.querySelector(".acw-note")?.remove();
2863
- const note = document.createElement("div");
2864
- note.className = "acw-note";
2865
- note.dataset.severity = notification.severity;
2866
- note.dataset.mode = state.mode;
2867
- note.innerHTML = `<span class="acw-note-icon" aria-hidden="true">${icon("leaf", 14)}</span><span class="acw-note-text"><strong></strong>${notification.detail ? "<small></small>" : ""}</span>`;
2868
- note.querySelector("strong").textContent = notification.message;
2869
- if (notification.detail) note.querySelector("small").textContent = notification.detail;
2870
- region.prepend(note);
2871
- setTimeout(() => {
2872
- note.dataset.leaving = "";
2873
- setTimeout(() => note.remove(), noteAwayMs);
2874
- }, noteStayMs);
2875
- }
2876
- function shakeLcd(root) {
2877
3047
  const lcd = root.querySelector(".acw-lcd");
2878
- lcd.removeAttribute("data-alert");
2879
- lcd.offsetWidth;
2880
- lcd.setAttribute("data-alert", "");
2881
- setTimeout(() => lcd.removeAttribute("data-alert"), 400);
3048
+ const announce = region.querySelector(".acw-sr-only");
3049
+ const present = createAcNotificationPresenter();
3050
+ let disposed = false;
3051
+ let note;
3052
+ let noteTimer;
3053
+ let shakeTimer;
3054
+ return {
3055
+ present(notification, state) {
3056
+ if (disposed) return;
3057
+ const how = present(notification, state);
3058
+ if (how === "skip") return;
3059
+ if (how === "shake") {
3060
+ clearTimeout(shakeTimer);
3061
+ lcd.removeAttribute("data-alert");
3062
+ lcd.offsetWidth;
3063
+ lcd.setAttribute("data-alert", "");
3064
+ shakeTimer = setTimeout(() => {
3065
+ shakeTimer = void 0;
3066
+ if (!disposed) lcd.removeAttribute("data-alert");
3067
+ }, 400);
3068
+ }
3069
+ if (how !== "note") {
3070
+ announce.textContent = notification.message;
3071
+ return;
3072
+ }
3073
+ clearTimeout(noteTimer);
3074
+ note?.remove();
3075
+ const next = document.createElement("div");
3076
+ note = next;
3077
+ next.className = "acw-note";
3078
+ next.dataset.severity = notification.severity;
3079
+ next.dataset.mode = state.mode;
3080
+ next.innerHTML = `<span class="acw-note-icon" aria-hidden="true">${icon("leaf", 14)}</span><span class="acw-note-text"><strong></strong>${notification.detail ? "<small></small>" : ""}</span>`;
3081
+ next.querySelector("strong").textContent = notification.message;
3082
+ if (notification.detail) next.querySelector("small").textContent = notification.detail;
3083
+ region.prepend(next);
3084
+ noteTimer = setTimeout(() => {
3085
+ if (disposed || note !== next) return;
3086
+ next.dataset.leaving = "";
3087
+ noteTimer = setTimeout(() => {
3088
+ if (disposed || note !== next) return;
3089
+ next.remove();
3090
+ note = void 0;
3091
+ noteTimer = void 0;
3092
+ }, noteAwayMs);
3093
+ }, noteStayMs);
3094
+ },
3095
+ dispose() {
3096
+ disposed = true;
3097
+ clearTimeout(noteTimer);
3098
+ clearTimeout(shakeTimer);
3099
+ noteTimer = shakeTimer = void 0;
3100
+ note?.remove();
3101
+ note = void 0;
3102
+ lcd.removeAttribute("data-alert");
3103
+ announce.textContent = "";
3104
+ }
3105
+ };
2882
3106
  }
2883
3107
  function boolAttribute(value, fallback) {
2884
3108
  if (value === null) return fallback;
@@ -2919,9 +3143,12 @@ html.dark .acw-note[data-mode="hot"],
2919
3143
  store;
2920
3144
  unsubscribe;
2921
3145
  renderedState;
3146
+ refs;
2922
3147
  stopObservers = [];
2923
3148
  audio;
2924
- present = createAcNotificationPresenter();
3149
+ audioRunning = false;
3150
+ notificationView;
3151
+ notificationOwners = /* @__PURE__ */ new WeakMap();
2925
3152
  placement;
2926
3153
  static get observedAttributes() {
2927
3154
  return [
@@ -2935,22 +3162,36 @@ html.dark .acw-note[data-mode="hot"],
2935
3162
  ];
2936
3163
  }
2937
3164
  connectedCallback() {
3165
+ this.teardownConnection();
2938
3166
  const assetsBaseUrl = options.assetsBaseUrl ?? "/assets";
2939
3167
  const enableAudio = options.enableAudio ?? true;
2940
3168
  ensureDigitFont(assetsBaseUrl);
2941
- if (!this.shadowRoot) this.attachShadow({ mode: "open" }).innerHTML = widgetTemplate({
2942
- title: this.getAttribute("title") ?? options.title,
2943
- logoUrl: options.logoUrl ?? "/yun-logo.svg",
2944
- logoHref: options.logoHref ?? "https://github.com/YunYouJun/air-conditioner",
2945
- showEnergyLabel: options.showEnergyLabel ?? true,
2946
- audio: enableAudio ? resolveAcAudioAssets(`${assetsBaseUrl}/audio`, options.audioExt ?? "m4a") : void 0
2947
- });
2948
- this.store = createAirConditionerStore({
3169
+ if (!this.shadowRoot) {
3170
+ const root = this.attachShadow({ mode: "open" });
3171
+ const sheet = getSharedStyleSheet();
3172
+ const supportsAdopted = Boolean(sheet && "adoptedStyleSheets" in root);
3173
+ root.innerHTML = widgetTemplate({
3174
+ title: this.getAttribute("title") ?? options.title,
3175
+ logoUrl: options.logoUrl ?? "/yun-logo.svg",
3176
+ logoHref: options.logoHref ?? "https://github.com/YunYouJun/air-conditioner",
3177
+ showEnergyLabel: options.showEnergyLabel ?? true,
3178
+ audio: enableAudio ? resolveAcAudioAssets(`${assetsBaseUrl}/audio`, options.audioExt ?? "m4a") : void 0,
3179
+ inlineStyle: !supportsAdopted
3180
+ });
3181
+ if (supportsAdopted && sheet) root.adoptedStyleSheets = [sheet];
3182
+ }
3183
+ this.refs ||= collectWidgetRefs(this.shadowRoot);
3184
+ const notificationView = createNotificationView(this.shadowRoot);
3185
+ this.notificationView = notificationView;
3186
+ const reconnecting = Boolean(this.store);
3187
+ this.store ||= createAirConditionerStore({
2949
3188
  ...options,
2950
3189
  storageKey: this.getAttribute("storage-key") ?? options.storageKey,
2951
3190
  initialState: getInitialState(this, options.initialState),
2952
3191
  onNotify: (notification, event) => {
2953
- if (this.shadowRoot) presentNotification(this.shadowRoot, notification, this.present(notification, event.state), event.state);
3192
+ const owner = this.notificationOwners.get(event);
3193
+ this.notificationOwners.delete(event);
3194
+ owner?.present(notification, event.state);
2954
3195
  this.dispatchEvent(new CustomEvent("ac-notify", {
2955
3196
  detail: {
2956
3197
  notification,
@@ -2963,6 +3204,7 @@ html.dark .acw-note[data-mode="hot"],
2963
3204
  }
2964
3205
  });
2965
3206
  this.unsubscribe = this.store.subscribe((event) => {
3207
+ if (event.notification) this.notificationOwners.set(event, notificationView);
2966
3208
  this.render();
2967
3209
  this.playAudio(event);
2968
3210
  this.dispatchEvent(new CustomEvent("ac-change", {
@@ -2971,16 +3213,20 @@ html.dark .acw-note[data-mode="hot"],
2971
3213
  composed: true
2972
3214
  }));
2973
3215
  });
3216
+ this.shadowRoot?.addEventListener("pointerdown", this.onWarm, true);
3217
+ this.shadowRoot?.addEventListener("keydown", this.onWarm, true);
2974
3218
  this.shadowRoot?.addEventListener("click", this.onClick);
2975
3219
  this.shadowRoot?.addEventListener("keydown", this.onKeyDown);
2976
3220
  this.shadowRoot?.addEventListener("animationiteration", this.onDrip);
3221
+ const initial = this.store.getState();
3222
+ if (!initial.status) this.audioRunning = false;
3223
+ if (reconnecting && initial.status) this.refs.unit.setAttribute("data-skip-selftest", "");
3224
+ if (reconnecting && this.audioRunning && initial.status) this.ensureAudio(initial.sound, initial.fan ?? "auto")?.resumeFan();
2977
3225
  this.updatePlacement();
2978
3226
  this.renderedState = void 0;
2979
3227
  this.render();
2980
- this.stopObservers.forEach((stop) => stop());
2981
- this.stopObservers = [];
2982
- const unit = this.shadowRoot?.querySelector(".acw-unit");
2983
- if (unit) this.stopObservers.push(observeAcScale(unit, acShellSize.compact.width, (scale) => {
3228
+ const unit = this.refs.unit;
3229
+ this.stopObservers.push(observeAcScale(unit, acShellSize.compact.width, (scale) => {
2984
3230
  unit.style.setProperty("--acw-scale", String(scale));
2985
3231
  }), observeAcTilt(unit, (x, y) => {
2986
3232
  unit.style.setProperty("--acw-tilt-x", `${x}deg`);
@@ -2993,11 +3239,19 @@ html.dark .acw-note[data-mode="hot"],
2993
3239
  }
2994
3240
  }
2995
3241
  disconnectedCallback() {
3242
+ this.teardownConnection();
3243
+ }
3244
+ teardownConnection() {
3245
+ this.notificationView?.dispose();
3246
+ this.notificationView = void 0;
2996
3247
  this.unsubscribe?.();
3248
+ this.unsubscribe = void 0;
2997
3249
  this.audio?.dispose();
2998
3250
  this.audio = void 0;
2999
3251
  this.stopObservers.forEach((stop) => stop());
3000
3252
  this.stopObservers = [];
3253
+ this.shadowRoot?.removeEventListener("pointerdown", this.onWarm, true);
3254
+ this.shadowRoot?.removeEventListener("keydown", this.onWarm, true);
3001
3255
  this.shadowRoot?.removeEventListener("click", this.onClick);
3002
3256
  this.shadowRoot?.removeEventListener("keydown", this.onKeyDown);
3003
3257
  this.shadowRoot?.removeEventListener("animationiteration", this.onDrip);
@@ -3017,10 +3271,14 @@ html.dark .acw-note[data-mode="hot"],
3017
3271
  payload: getInitialState(this, this.store.getState())
3018
3272
  });
3019
3273
  }
3274
+ /** 捕获阶段唤醒音频,赶在 click 和温度键的 pointerdown 发声之前。 */
3275
+ onWarm = () => {
3276
+ const state = this.store?.getState();
3277
+ this.ensureAudio(state?.sound, state?.fan ?? "auto")?.unlock();
3278
+ };
3020
3279
  onClick = (event) => {
3021
3280
  if (event.target?.closest(".acw-remote-toggle")) {
3022
- const panel = this.shadowRoot?.querySelector(".acw-remote-panel");
3023
- if (panel) this.setRemoteOpen(Boolean(panel.hidden));
3281
+ if (this.refs) this.setRemoteOpen(Boolean(this.refs.remotePanel.hidden));
3024
3282
  return;
3025
3283
  }
3026
3284
  const action = (event.target?.closest("[data-action]"))?.dataset.action;
@@ -3034,60 +3292,69 @@ html.dark .acw-note[data-mode="hot"],
3034
3292
  else if (action === "cycleSound" || action === "toggleSwing" || action === "cycleFan") this.store.dispatch({ type: action });
3035
3293
  };
3036
3294
  updatePlacement() {
3037
- if (!this.shadowRoot) return;
3295
+ if (!this.shadowRoot || !this.refs) return;
3038
3296
  const value = this.getAttribute("placement") ?? options.placement;
3039
3297
  const placement = value === "top-left" || value === "top-right" ? value : "inline";
3040
3298
  const wasFloating = this.placement && this.placement !== "inline";
3041
3299
  this.placement = placement;
3042
3300
  this.dataset.acPlacement = placement;
3043
- const toggle = this.shadowRoot.querySelector(".acw-remote-toggle");
3301
+ const toggle = this.refs.remoteToggle;
3044
3302
  const focusRemote = placement === "inline" && this.shadowRoot.activeElement === toggle;
3045
3303
  toggle.hidden = placement === "inline";
3046
3304
  if (placement === "inline" || !wasFloating) this.setRemoteOpen(placement === "inline");
3047
- if (focusRemote) this.shadowRoot.querySelector(".acw-button-power")?.focus();
3305
+ if (focusRemote) this.refs.powerButton.focus();
3048
3306
  }
3049
3307
  setRemoteOpen(open) {
3050
- const panel = this.shadowRoot?.querySelector(".acw-remote-panel");
3051
- const toggle = this.shadowRoot?.querySelector(".acw-remote-toggle");
3052
- if (!panel || !toggle) return;
3308
+ if (!this.refs) return;
3309
+ const { remotePanel: panel, remoteToggle: toggle, remoteToggleLabel: label } = this.refs;
3053
3310
  if (!open && this.shadowRoot?.activeElement && panel.contains(this.shadowRoot.activeElement)) toggle.focus();
3054
3311
  panel.hidden = !open;
3055
3312
  toggle.setAttribute("aria-expanded", String(open));
3056
- const label = toggle.querySelector(".acw-toggle-label");
3057
3313
  if (label) label.textContent = open ? "收起遥控器" : "打开遥控器";
3058
3314
  }
3059
3315
  onKeyDown = (event) => {
3060
3316
  const keyboardEvent = event;
3061
3317
  if (keyboardEvent.key !== "Escape" || this.placement === "inline") return;
3062
- const panel = this.shadowRoot?.querySelector(".acw-remote-panel");
3318
+ const panel = this.refs?.remotePanel;
3063
3319
  if (!panel || panel.hidden) return;
3064
3320
  keyboardEvent.preventDefault();
3065
3321
  keyboardEvent.stopPropagation();
3066
3322
  this.setRemoteOpen(false);
3067
- this.shadowRoot?.querySelector(".acw-remote-toggle")?.focus();
3323
+ this.refs?.remoteToggle.focus();
3068
3324
  };
3069
3325
  /**
3070
- * 同步声音模式后播放按键「嘀」声;开关状态翻转时播放启动 / 关闭音效(与 Vue 版 useAcAudio 一致)。
3326
+ * 有 `<audio>` 时创建控制器并开始解码。重复调用沿用已创建的那一个。
3071
3327
  */
3072
- playAudio(event) {
3328
+ ensureAudio(soundMode, fanSpeed) {
3073
3329
  const root = this.shadowRoot;
3074
- if (!root?.querySelector("audio")) return;
3330
+ if (!root?.querySelector("audio")) return void 0;
3075
3331
  this.audio ||= createAcAudioController({
3076
3332
  beep: root.querySelector("[data-audio=\"beep\"]"),
3077
3333
  start: root.querySelector("[data-audio=\"start\"]"),
3078
3334
  work: root.querySelector("[data-audio=\"work\"]")
3079
3335
  }, {
3080
- soundMode: event.state.sound,
3081
- fanSpeed: event.state.fan ?? "auto"
3336
+ soundMode,
3337
+ fanSpeed
3082
3338
  });
3083
- if (event.previousState.sound !== event.state.sound) this.audio.setSoundMode(event.state.sound);
3084
- if (event.previousState.fan !== event.state.fan) this.audio.setFanSpeed(event.state.fan ?? "auto");
3085
- this.audio.beep();
3086
- if (event.previousState.status !== event.state.status) this.audio.toggleStatusAudio(event.previousState.status);
3339
+ return this.audio;
3340
+ }
3341
+ /**
3342
+ * 同步声音模式后播放按键「嘀」声;开关状态翻转时播放启动 / 关闭音效(与 Vue 版 useAcAudio 一致)。
3343
+ */
3344
+ playAudio(event) {
3345
+ const audio = this.ensureAudio(event.state.sound, event.state.fan ?? "auto");
3346
+ if (!audio) return;
3347
+ if (event.previousState.sound !== event.state.sound) audio.setSoundMode(event.state.sound);
3348
+ if (event.previousState.fan !== event.state.fan) audio.setFanSpeed(event.state.fan ?? "auto");
3349
+ audio.beep();
3350
+ if (event.previousState.status !== event.state.status) {
3351
+ this.audioRunning = event.state.status;
3352
+ audio.toggleStatusAudio(event.previousState.status);
3353
+ }
3087
3354
  }
3088
3355
  render() {
3089
3356
  const state = this.store?.getState() ?? defaultAcState;
3090
- if (this.shadowRoot) updateWidget(this.shadowRoot, state, this.renderedState);
3357
+ if (this.refs) updateWidget(this.refs, state, this.renderedState);
3091
3358
  this.renderedState = state;
3092
3359
  }
3093
3360
  }