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