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