@yunlefun-home/air-conditioner-core 0.2.0 → 0.4.0

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
@@ -21,17 +21,129 @@ const acAudioFileNames = {
21
21
  };
22
22
  const minTemperature = 16;
23
23
  const maxTemperature = 31;
24
+ const defaultAcLimits = {
25
+ min: 16,
26
+ max: 31,
27
+ step: 1
28
+ };
24
29
  const recommendedColdTemperature = 26;
25
30
  const recommendedHotTemperature = 20;
26
31
  const defaultAcState = {
27
32
  mode: "cold",
28
33
  status: false,
29
- temperature: 26
34
+ temperature: 26,
35
+ temperatures: {
36
+ cold: 26,
37
+ hot: 26
38
+ },
39
+ sound: "normal",
40
+ swing: false,
41
+ fan: "auto"
42
+ };
43
+ /**
44
+ * 遥控器「声音」键依次切换的顺序。
45
+ */
46
+ const acSoundModes = [
47
+ "normal",
48
+ "sleep",
49
+ "mute"
50
+ ];
51
+ /**
52
+ * 各模式的中文名称(遥控器小屏与按键提示共用)。
53
+ */
54
+ const acModeLabels = {
55
+ cold: "制冷",
56
+ hot: "制热"
57
+ };
58
+ const acSoundModeLabels = {
59
+ normal: "标准",
60
+ sleep: "睡眠",
61
+ mute: "静音"
62
+ };
63
+ /**
64
+ * 各声音模式的总音量(0–1)。
65
+ */
66
+ const acSoundVolumes = {
67
+ normal: 1,
68
+ sleep: .3,
69
+ mute: 0
30
70
  };
71
+ /**
72
+ * 遥控器「风速」键依次切换的顺序。
73
+ */
74
+ const acFanSpeeds = [
75
+ "auto",
76
+ "low",
77
+ "medium",
78
+ "high"
79
+ ];
80
+ const acFanSpeedLabels = {
81
+ auto: "自动",
82
+ low: "低风",
83
+ medium: "中风",
84
+ high: "高风"
85
+ };
86
+ /**
87
+ * 小屏上点亮的风速格数(1–3)。自动风速由空调自己决定,显示为 0 并另加「自动」标记。
88
+ */
89
+ const acFanBars = {
90
+ auto: 0,
91
+ low: 1,
92
+ medium: 2,
93
+ high: 3
94
+ };
95
+ /**
96
+ * 固定风速下风声的相对音量(0–1);自动风速沿用开机后的「达标 / 发力」循环。
97
+ */
98
+ const acFanSoundLevels = {
99
+ low: .45,
100
+ medium: .7,
101
+ high: 1
102
+ };
103
+ function isAcFanSpeed(value) {
104
+ return acFanSpeeds.includes(value);
105
+ }
106
+ /**
107
+ * 风速键的下一档:自动 → 低 → 中 → 高 → 自动。
108
+ */
109
+ function nextAcFanSpeed(fan) {
110
+ const index = Math.max(acFanSpeeds.indexOf(fan), 0);
111
+ return acFanSpeeds[(index + 1) % acFanSpeeds.length];
112
+ }
113
+ function isAcSoundMode(value) {
114
+ return acSoundModes.includes(value);
115
+ }
116
+ /**
117
+ * 声音键的下一个模式:标准 → 睡眠 → 静音 → 标准。
118
+ */
119
+ function nextAcSoundMode(mode) {
120
+ const index = Math.max(acSoundModes.indexOf(mode), 0);
121
+ return acSoundModes[(index + 1) % acSoundModes.length];
122
+ }
123
+ /**
124
+ * 音效时序。时长单位为毫秒,`*Level` 是风声相对音量(0–1)。
125
+ */
31
126
  const soundTimings = {
127
+ /** 开机后多久接上持续的风声(启动声约 9 秒) */
32
128
  startDelayMs: 8e3,
33
- noiseStartTime: 2,
34
- noiseDuration: 56
129
+ /** 风声循环首尾的交叉淡化时长 */
130
+ loopCrossfadeMs: 1500,
131
+ /** 关机时声音淡出时长 */
132
+ stopFadeMs: 600,
133
+ /** 开机运行多久后室温达标、风声降下来 */
134
+ settleAfterMs: 9e4,
135
+ /** 风声降下来的渐变时长 */
136
+ settleRampMs: 2e4,
137
+ /** 达标后的安静风声 */
138
+ settleLevel: .5,
139
+ /** 室温回升、压缩机重新发力时的风声 */
140
+ surgeLevel: .85,
141
+ /** 两次发力之间安静运行的时长范围 */
142
+ quietDurationMs: [18e4, 36e4],
143
+ /** 每次发力持续的时长范围 */
144
+ surgeDurationMs: [6e4, 12e4],
145
+ /** 发力 / 回落的渐变时长 */
146
+ surgeRampMs: 1e4
35
147
  };
36
148
  /**
37
149
  * 根据基础路径解析出三个音频文件的完整 URL。
@@ -51,79 +163,789 @@ function resolveAcAudioAssets(baseUrl = "/assets/audio", ext = "m4a") {
51
163
  }
52
164
  //#endregion
53
165
  //#region src/audio.ts
54
- function createAcAudioController(elements) {
55
- let playStartSoundTimeoutId;
56
- let playWorkSoundTimeoutId;
57
- let playWorkSoundIntervalId;
58
- function clearWorkTimers() {
59
- if (playStartSoundTimeoutId) clearTimeout(playStartSoundTimeoutId);
60
- if (playWorkSoundTimeoutId) clearTimeout(playWorkSoundTimeoutId);
61
- if (playWorkSoundIntervalId) clearInterval(playWorkSoundIntervalId);
62
- playStartSoundTimeoutId = void 0;
63
- playWorkSoundTimeoutId = void 0;
64
- playWorkSoundIntervalId = void 0;
65
- }
66
- function play(audio) {
67
- if (!audio) return;
68
- audio.load();
69
- audio.play();
70
- }
71
- function playWorkSound() {
72
- if (!elements.work) return;
73
- play(elements.work);
74
- playWorkSoundTimeoutId = setTimeout(() => {
75
- playWorkSoundIntervalId = setInterval(() => {
76
- if (elements.work) elements.work.currentTime = soundTimings.noiseStartTime;
77
- }, soundTimings.noiseDuration * 1e3);
78
- }, soundTimings.noiseStartTime * 1e3);
79
- }
80
- function playStartSound() {
81
- play(elements.start);
82
- playStartSoundTimeoutId = setTimeout(() => {
83
- playWorkSound();
166
+ /** Web Audio 资源迟迟没加载好时,本次开机先用 `<audio>` 播放 */
167
+ const readyTimeoutMs = 1500;
168
+ const fallbackTweenStepMs = 100;
169
+ const curveLength = 64;
170
+ function sourceUrl(element) {
171
+ return element?.currentSrc || element?.src || "";
172
+ }
173
+ async function fetchAudioData(url) {
174
+ const response = await fetch(url);
175
+ if (!response.ok) throw new Error(`Failed to load ${url}: ${response.status}`);
176
+ return response.arrayBuffer();
177
+ }
178
+ function createDefaultAudioContext() {
179
+ const scope = globalThis;
180
+ const AudioContextConstructor = scope.AudioContext ?? scope.webkitAudioContext;
181
+ return AudioContextConstructor ? new AudioContextConstructor() : null;
182
+ }
183
+ /**
184
+ * 合成一声很轻的「嗒」:音高快速下滑的正弦波,短促起音、指数衰减,像水珠落在窗台上。
185
+ */
186
+ function playDrip(context, output) {
187
+ const start = context.currentTime;
188
+ const oscillator = context.createOscillator();
189
+ const gain = context.createGain();
190
+ oscillator.type = "sine";
191
+ oscillator.frequency.setValueAtTime(1500, start);
192
+ oscillator.frequency.exponentialRampToValueAtTime(520, start + .07);
193
+ gain.gain.setValueAtTime(1e-4, start);
194
+ gain.gain.exponentialRampToValueAtTime(.12, start + .004);
195
+ gain.gain.exponentialRampToValueAtTime(1e-4, start + .16);
196
+ oscillator.connect(gain);
197
+ gain.connect(output);
198
+ oscillator.start(start);
199
+ oscillator.stop(start + .18);
200
+ oscillator.onended = () => gain.disconnect();
201
+ }
202
+ /**
203
+ * 等功率淡入 / 淡出曲线,噪声类声音交叉淡化时中段不会变小。
204
+ */
205
+ function fadeCurve(direction) {
206
+ const curve = new Float32Array(curveLength);
207
+ for (let i = 0; i < curveLength; i++) {
208
+ const phase = i / 63 * Math.PI / 2;
209
+ curve[i] = direction === "in" ? Math.sin(phase) : Math.cos(phase);
210
+ }
211
+ return curve;
212
+ }
213
+ function randomBetween(range, random) {
214
+ return range[0] + (range[1] - range[0]) * random();
215
+ }
216
+ function playElement(element) {
217
+ if (!element) return;
218
+ element.load();
219
+ Promise.resolve(element.play()).catch(() => {});
220
+ }
221
+ function stopElement(element) {
222
+ if (!element) return;
223
+ if (element.pause) element.pause();
224
+ else element.load();
225
+ }
226
+ /**
227
+ * 空调音效:按键「嘀」声、开机启动声与持续的风声。
228
+ *
229
+ * 默认通过 Web Audio API 播放:风声无缝循环,开关机淡入淡出,运行一段时间后
230
+ * 风声变小、并不定时随压缩机发力起伏。环境不支持或音频无法获取时退回
231
+ * `<audio>` 元素。
232
+ *
233
+ * 需在用户交互(点击遥控器)里首次调用,浏览器才允许发声。
234
+ *
235
+ * @param elements 三个音频元素;Web Audio 会从它们的 `src` 获取音频
236
+ * @param options 声音模式与可替换的环境依赖
237
+ */
238
+ function createAcAudioController(elements, options = {}) {
239
+ const random = options.random ?? Math.random;
240
+ let soundMode = options.soundMode ?? "normal";
241
+ let fanSpeed = options.fanSpeed ?? "auto";
242
+ /** 开机后风声循环已经接上(启动声结束) */
243
+ let fanRunning = false;
244
+ /** 每次重启「达标 / 发力」循环自增,丢弃旧循环的回调 */
245
+ let fanCycle = 0;
246
+ /** undefined:尚未尝试;null:不可用 */
247
+ let engine;
248
+ let run;
249
+ /** 每次开关机自增,丢弃过期的异步回调 */
250
+ let session = 0;
251
+ const timers = /* @__PURE__ */ new Set();
252
+ /** `<audio>` 播放时的风声相对音量 */
253
+ let fallbackFanLevel = 1;
254
+ let fallbackTween;
255
+ function later(callback, delayMs) {
256
+ const timer = setTimeout(() => {
257
+ timers.delete(timer);
258
+ callback();
259
+ }, delayMs);
260
+ timers.add(timer);
261
+ }
262
+ function clearTimers() {
263
+ timers.forEach((timer) => clearTimeout(timer));
264
+ timers.clear();
265
+ }
266
+ function volume() {
267
+ return acSoundVolumes[soundMode];
268
+ }
269
+ function applyElementVolume(element, level = 1) {
270
+ if (!element) return;
271
+ if (element.volume !== void 0) element.volume = Math.min(1, Math.max(0, volume() * level));
272
+ if (element.muted !== void 0) element.muted = soundMode === "mute";
273
+ }
274
+ function cancelFallbackTween() {
275
+ if (fallbackTween) clearInterval(fallbackTween);
276
+ fallbackTween = void 0;
277
+ }
278
+ function tweenFallbackFan(target, durationMs, onDone) {
279
+ cancelFallbackTween();
280
+ const from = fallbackFanLevel;
281
+ const steps = Math.max(1, Math.round(durationMs / fallbackTweenStepMs));
282
+ let step = 0;
283
+ fallbackTween = setInterval(() => {
284
+ step++;
285
+ fallbackFanLevel = from + (target - from) * (step / steps);
286
+ applyElementVolume(elements.work, fallbackFanLevel);
287
+ if (step >= steps) {
288
+ cancelFallbackTween();
289
+ onDone?.();
290
+ }
291
+ }, fallbackTweenStepMs);
292
+ }
293
+ function ensureEngine() {
294
+ if (engine !== void 0) return engine;
295
+ engine = createEngine();
296
+ return engine;
297
+ }
298
+ function createEngine() {
299
+ if (options.webAudio === false) return null;
300
+ let context;
301
+ try {
302
+ context = (options.createAudioContext ?? createDefaultAudioContext)();
303
+ } catch {
304
+ return null;
305
+ }
306
+ if (!context) return null;
307
+ const master = context.createGain();
308
+ master.gain.value = volume();
309
+ master.connect(context.destination);
310
+ const buffers = {};
311
+ const load = options.loadAudioData ?? fetchAudioData;
312
+ const decode = async (name) => {
313
+ const url = sourceUrl(elements[name]);
314
+ if (!url) return;
315
+ try {
316
+ buffers[name] = await context.decodeAudioData(await load(url));
317
+ } catch {}
318
+ };
319
+ const ready = Promise.all([
320
+ "beep",
321
+ "start",
322
+ "work"
323
+ ].map(decode)).then(() => Boolean(buffers.start && buffers.work));
324
+ return {
325
+ context,
326
+ master,
327
+ buffers,
328
+ ready
329
+ };
330
+ }
331
+ function resume(web) {
332
+ if (web.context.state === "suspended") Promise.resolve(web.context.resume()).catch(() => {});
333
+ }
334
+ function waitReady(web) {
335
+ return Promise.race([web.ready, new Promise((resolve) => setTimeout(resolve, readyTimeoutMs, false))]);
336
+ }
337
+ function playBuffer(web, buffer, destination, when) {
338
+ const source = web.context.createBufferSource();
339
+ source.buffer = buffer;
340
+ source.connect(destination);
341
+ source.start(when);
342
+ return source;
343
+ }
344
+ function track(target, source, cleanup) {
345
+ target.sources.add(source);
346
+ source.onended = () => {
347
+ target.sources.delete(source);
348
+ source.disconnect();
349
+ cleanup?.();
350
+ };
351
+ }
352
+ /**
353
+ * 排一段风声,并在它结束前交叉淡化接上下一段。
354
+ */
355
+ function loopFan(web, target, when) {
356
+ const buffer = web.buffers.work;
357
+ const crossfade = Math.min(soundTimings.loopCrossfadeMs / 1e3, buffer.duration / 2);
358
+ const gain = web.context.createGain();
359
+ gain.gain.value = 0;
360
+ gain.gain.setValueCurveAtTime(fadeCurve("in"), when, crossfade);
361
+ gain.gain.setValueCurveAtTime(fadeCurve("out"), when + buffer.duration - crossfade, crossfade);
362
+ gain.connect(target.fan);
363
+ const source = playBuffer(web, buffer, gain, when);
364
+ source.stop(when + buffer.duration);
365
+ track(target, source, () => gain.disconnect());
366
+ const next = when + buffer.duration - crossfade;
367
+ later(() => {
368
+ if (run === target) loopFan(web, target, next);
369
+ }, Math.max(0, (next - web.context.currentTime - 1) * 1e3));
370
+ }
371
+ function setFanLevel(level, rampMs) {
372
+ if (run && engine) {
373
+ const gain = run.fan.gain;
374
+ const now = engine.context.currentTime;
375
+ gain.cancelScheduledValues(now);
376
+ gain.setValueAtTime(gain.value, now);
377
+ gain.linearRampToValueAtTime(level, now + rampMs / 1e3);
378
+ } else tweenFallbackFan(level, rampMs);
379
+ }
380
+ /** 风声循环刚接上时的音量:自动风速从满音量开始,固定风速保持各自的音量。 */
381
+ function initialFanLevel() {
382
+ return fanSpeed === "auto" ? 1 : acFanSoundLevels[fanSpeed];
383
+ }
384
+ /**
385
+ * 自动风速:室温达标后风声变小;之后不定时随压缩机发力变大,再回落。
386
+ * 固定风速不走这个循环。
387
+ */
388
+ function startFanCycle() {
389
+ fanRunning = true;
390
+ const cycle = ++fanCycle;
391
+ if (fanSpeed !== "auto") return;
392
+ const current = () => cycle === fanCycle && fanSpeed === "auto";
393
+ const quiet = () => {
394
+ later(() => {
395
+ if (!current()) return;
396
+ setFanLevel(soundTimings.surgeLevel, soundTimings.surgeRampMs);
397
+ later(() => {
398
+ if (!current()) return;
399
+ setFanLevel(soundTimings.settleLevel, soundTimings.surgeRampMs);
400
+ quiet();
401
+ }, randomBetween(soundTimings.surgeDurationMs, random));
402
+ }, randomBetween(soundTimings.quietDurationMs, random));
403
+ };
404
+ later(() => {
405
+ if (!current()) return;
406
+ setFanLevel(soundTimings.settleLevel, soundTimings.settleRampMs);
407
+ quiet();
408
+ }, soundTimings.settleAfterMs);
409
+ }
410
+ function startWeb(web) {
411
+ const output = web.context.createGain();
412
+ output.connect(web.master);
413
+ const fan = web.context.createGain();
414
+ fan.gain.value = initialFanLevel();
415
+ fan.connect(output);
416
+ const target = {
417
+ output,
418
+ fan,
419
+ sources: /* @__PURE__ */ new Set()
420
+ };
421
+ run = target;
422
+ const now = web.context.currentTime;
423
+ track(target, playBuffer(web, web.buffers.start, output, now));
424
+ loopFan(web, target, now + soundTimings.startDelayMs / 1e3);
425
+ later(startFanCycle, soundTimings.startDelayMs);
426
+ }
427
+ function stopWeb(fadeMs) {
428
+ const target = run;
429
+ run = void 0;
430
+ if (!target || !engine) return;
431
+ const now = engine.context.currentTime;
432
+ const end = now + fadeMs / 1e3;
433
+ const gain = target.output.gain;
434
+ gain.cancelScheduledValues(now);
435
+ gain.setValueAtTime(gain.value, now);
436
+ gain.linearRampToValueAtTime(0, end);
437
+ target.sources.forEach((source) => {
438
+ try {
439
+ source.stop(end);
440
+ } catch {}
441
+ });
442
+ setTimeout(() => target.output.disconnect(), fadeMs + 100);
443
+ }
444
+ function startFallback() {
445
+ const { start, work } = elements;
446
+ stopElement(work);
447
+ applyElementVolume(start);
448
+ playElement(start);
449
+ later(() => {
450
+ if (!work) return;
451
+ fallbackFanLevel = 0;
452
+ applyElementVolume(work, 0);
453
+ if (work.loop !== void 0) work.loop = true;
454
+ playElement(work);
455
+ tweenFallbackFan(initialFanLevel(), soundTimings.loopCrossfadeMs);
456
+ startFanCycle();
84
457
  }, soundTimings.startDelayMs);
85
458
  }
459
+ function stopFallback(fadeMs) {
460
+ stopElement(elements.start);
461
+ if (fadeMs > 0) tweenFallbackFan(0, fadeMs, () => stopElement(elements.work));
462
+ else stopElement(elements.work);
463
+ }
464
+ function powerOn() {
465
+ const id = ++session;
466
+ fanRunning = false;
467
+ fanCycle++;
468
+ clearTimers();
469
+ cancelFallbackTween();
470
+ stopWeb(0);
471
+ stopFallback(0);
472
+ const web = ensureEngine();
473
+ if (!web) {
474
+ startFallback();
475
+ return;
476
+ }
477
+ resume(web);
478
+ waitReady(web).then((ok) => {
479
+ if (id !== session) return;
480
+ if (ok) startWeb(web);
481
+ else startFallback();
482
+ });
483
+ }
484
+ function powerOff() {
485
+ session++;
486
+ fanRunning = false;
487
+ fanCycle++;
488
+ clearTimers();
489
+ stopWeb(soundTimings.stopFadeMs);
490
+ stopFallback(soundTimings.stopFadeMs);
491
+ }
86
492
  return {
87
493
  beep() {
88
- play(elements.beep);
494
+ if (soundMode === "mute") return;
495
+ const web = ensureEngine();
496
+ if (web) {
497
+ resume(web);
498
+ if (web.buffers.beep) {
499
+ playBuffer(web, web.buffers.beep, web.master, web.context.currentTime);
500
+ return;
501
+ }
502
+ }
503
+ applyElementVolume(elements.beep);
504
+ playElement(elements.beep);
505
+ },
506
+ drip() {
507
+ if (soundMode !== "normal") return;
508
+ const web = ensureEngine();
509
+ if (!web || typeof web.context.createOscillator !== "function") return;
510
+ resume(web);
511
+ playDrip(web.context, web.master);
89
512
  },
90
513
  toggleStatusAudio(previousStatus) {
91
- if (previousStatus) {
92
- clearWorkTimers();
93
- if (elements.start) elements.start.load();
94
- if (elements.work) elements.work.currentTime = soundTimings.noiseStartTime + soundTimings.noiseDuration;
514
+ if (previousStatus) powerOff();
515
+ else powerOn();
516
+ },
517
+ setSoundMode(mode) {
518
+ soundMode = mode;
519
+ if (engine) engine.master.gain.setTargetAtTime(volume(), engine.context.currentTime, .08);
520
+ applyElementVolume(elements.beep);
521
+ applyElementVolume(elements.start);
522
+ applyElementVolume(elements.work, fallbackFanLevel);
523
+ },
524
+ setFanSpeed(fan) {
525
+ if (fan === fanSpeed) return;
526
+ fanSpeed = fan;
527
+ if (!fanRunning) {
528
+ if (run) run.fan.gain.value = initialFanLevel();
529
+ return;
530
+ }
531
+ if (fan === "auto") {
532
+ setFanLevel(1, soundTimings.loopCrossfadeMs);
533
+ startFanCycle();
95
534
  } else {
96
- clearWorkTimers();
97
- playStartSound();
535
+ fanCycle++;
536
+ setFanLevel(acFanSoundLevels[fan], soundTimings.loopCrossfadeMs);
98
537
  }
99
538
  },
100
539
  dispose() {
101
- clearWorkTimers();
540
+ session++;
541
+ clearTimers();
542
+ cancelFallbackTween();
543
+ stopWeb(0);
544
+ stopFallback(0);
545
+ if (engine && !options.createAudioContext) Promise.resolve(engine.context.close()).catch(() => {});
546
+ engine = null;
547
+ }
548
+ };
549
+ }
550
+ //#endregion
551
+ //#region src/condensation.ts
552
+ /** 风速越大,雾气越浓、冷凝水越快 */
553
+ const fanFactor = {
554
+ auto: .8,
555
+ low: .55,
556
+ medium: .8,
557
+ high: 1
558
+ };
559
+ /** 高于这个设定温度不滴水:冷凝水不该常见,只在开得很冷时偶尔出现 */
560
+ const acDripMaxTemperature = 22;
561
+ /** 最冷(16 °C)与 {@link acDripMaxTemperature} 时,两滴水之间的间隔(ms) */
562
+ const acDripIntervalRange = [9e3, 18e3];
563
+ /**
564
+ * 出风口雾气的浓度(#70),0–1:只在制冷开机时出现,设定温度越低、风越大越浓。
565
+ *
566
+ * 视图把它写进 CSS 变量 `--acw-mist`,3D 等其他渲染器也可以按它控制粒子数量。
567
+ */
568
+ function getAcMist(state) {
569
+ if (!state.status || state.mode !== "cold") return 0;
570
+ const cold = .2 + .8 * (31 - state.temperature) / 15;
571
+ const mist = Math.min(1, Math.max(.2, cold)) * fanFactor[state.fan ?? "auto"];
572
+ return Math.round(mist * 100) / 100;
573
+ }
574
+ /**
575
+ * 冷凝水滴落的间隔(#21,ms):只在制冷开机、设定温度不高于 {@link acDripMaxTemperature} 时滴水,
576
+ * 越冷越频繁,高风再快一些;不滴水时返回 `undefined`。
577
+ *
578
+ * 视图把它写进 CSS 变量 `--acw-drip-cycle`,水珠在出风口边缘慢慢聚起再落下,开机后要等一整个间隔才滴第一滴。
579
+ */
580
+ function getAcDripInterval(state) {
581
+ if (!state.status || state.mode !== "cold" || state.temperature > 22) return void 0;
582
+ const [fastest, slowest] = acDripIntervalRange;
583
+ const progress = (state.temperature - 16) / 6;
584
+ const interval = fastest + (slowest - fastest) * Math.min(1, Math.max(0, progress));
585
+ return Math.round(interval * (state.fan === "high" ? .8 : 1));
586
+ }
587
+ /**
588
+ * 视图要写到空调根元素上的雾气 / 滴水样式变量与属性。
589
+ */
590
+ function getAcCondensationStyle(state) {
591
+ const interval = getAcDripInterval(state);
592
+ return {
593
+ mist: getAcMist(state),
594
+ dripCycle: interval === void 0 ? void 0 : `${interval}ms`,
595
+ drip: interval === void 0 ? "off" : "on"
596
+ };
597
+ }
598
+ //#endregion
599
+ //#region src/motion.ts
600
+ /**
601
+ * 动效 token:各框架视图层共用的时长与缓动曲线。
602
+ *
603
+ * 样式里统一通过 CSS 变量(`--acw-motion-*`)引用,
604
+ * 需要在 JS 里计时的地方(如 React 过渡组件)直接读取 `acMotion`。
605
+ */
606
+ const acMotion = {
607
+ duration: {
608
+ /** 按下反馈 */
609
+ instant: 90,
610
+ /** 悬停、指示灯、图标 */
611
+ fast: 160,
612
+ /** 显示屏、数字切换、提示 */
613
+ base: 240,
614
+ /** 导风板、出风淡入淡出 */
615
+ slow: 420,
616
+ /** 出风气流单次循环 */
617
+ flow: 1800,
618
+ /** 扫风:左右摆动一个来回 */
619
+ swing: 5200
620
+ },
621
+ easing: {
622
+ /** 常规状态切换 */
623
+ standard: "cubic-bezier(0.2, 0, 0, 1)",
624
+ /** 进入:快起慢停 */
625
+ enter: "cubic-bezier(0, 0, 0, 1)",
626
+ /** 退出:慢起快走 */
627
+ exit: "cubic-bezier(0.3, 0, 1, 1)",
628
+ /** 轻微回弹(按钮松开、图标弹出) */
629
+ spring: "cubic-bezier(0.34, 1.56, 0.64, 1)"
630
+ }
631
+ };
632
+ /**
633
+ * `prefers-reduced-motion: reduce` 时使用的时长:
634
+ * 保留短促的淡入淡出(不涉及位移),去掉较长的过渡;循环动画由各样式表自行关闭。
635
+ */
636
+ const acReducedMotionDuration = {
637
+ instant: 0,
638
+ fast: 80,
639
+ base: 120,
640
+ slow: 120,
641
+ flow: 0,
642
+ swing: 0
643
+ };
644
+ const acReducedMotionQuery = "(prefers-reduced-motion: reduce)";
645
+ /**
646
+ * 当前环境是否要求减少动效(SSR / 无 matchMedia 时返回 `false`)。
647
+ */
648
+ function prefersReducedMotion() {
649
+ return typeof globalThis.matchMedia === "function" && globalThis.matchMedia("(prefers-reduced-motion: reduce)").matches;
650
+ }
651
+ function declarations(durations, withEasing, indent) {
652
+ const lines = Object.keys(durations).map((key) => `${indent}--acw-motion-duration-${key}: ${durations[key]}ms;`);
653
+ if (withEasing) for (const key of Object.keys(acMotion.easing)) lines.push(`${indent}--acw-motion-ease-${key}: ${acMotion.easing[key]};`);
654
+ return lines.join("\n");
655
+ }
656
+ /**
657
+ * 生成动效 CSS 变量声明(含 reduced-motion 覆盖),供 Shadow DOM 注入或样式表同步使用。
658
+ *
659
+ * @param selector 变量挂载的选择器,如 `:root`、`:host`
660
+ */
661
+ function renderAcMotionCssVars(selector = ":root") {
662
+ return [
663
+ `${selector} {`,
664
+ declarations(acMotion.duration, true, " "),
665
+ "}",
666
+ "",
667
+ `@media ${acReducedMotionQuery} {`,
668
+ ` ${selector} {`,
669
+ declarations(acReducedMotionDuration, false, " "),
670
+ " }",
671
+ "}"
672
+ ].join("\n");
673
+ }
674
+ //#endregion
675
+ //#region src/layout.ts
676
+ /**
677
+ * 机身的设计尺寸(px),约 3:1,接近真实壁挂机(如 800–900mm × 280–300mm)的比例。
678
+ * 窄容器下按比例整体缩放,保持「长款」外观不被压扁。
679
+ *
680
+ * - `compact`:Vue / React 组件库 / Web Component 使用的 360 × 128 机身
681
+ * - `wide`:React 主站使用的 600 × 200 机身
682
+ */
683
+ const acShellSize = {
684
+ compact: {
685
+ width: 360,
686
+ height: 128
687
+ },
688
+ wide: {
689
+ width: 600,
690
+ height: 200
691
+ }
692
+ };
693
+ /**
694
+ * 根据可用宽度计算机身缩放比例:只缩小、不放大。
695
+ */
696
+ function getAcScale(availableWidth, designWidth) {
697
+ if (!(availableWidth > 0) || !(designWidth > 0)) return 1;
698
+ return Math.min(1, availableWidth / designWidth);
699
+ }
700
+ /**
701
+ * 监听容器宽度变化并回调缩放比例。
702
+ *
703
+ * 不支持 `ResizeObserver` 的环境(如 SSR)直接返回空的清理函数,保持 1 倍显示。
704
+ *
705
+ * @param target 被测量宽度的容器(不要传被缩放的元素本身)
706
+ * @param designWidth 机身的设计宽度
707
+ * @param onScale 比例变化时的回调
708
+ * @returns 停止监听的清理函数
709
+ */
710
+ function observeAcScale(target, designWidth, onScale) {
711
+ if (typeof ResizeObserver === "undefined") return () => {};
712
+ let current;
713
+ const update = (width) => {
714
+ const scale = getAcScale(width, designWidth);
715
+ if (scale !== current) {
716
+ current = scale;
717
+ onScale(scale);
102
718
  }
103
719
  };
720
+ update(target.getBoundingClientRect().width);
721
+ const observer = new ResizeObserver((entries) => {
722
+ for (const entry of entries) update(entry.contentRect.width);
723
+ });
724
+ observer.observe(target);
725
+ return () => observer.disconnect();
726
+ }
727
+ /** 指针跟随倾斜的最大角度(deg) */
728
+ const acMaxTilt = 4;
729
+ const finePointerQuery = "(hover: hover) and (pointer: fine)";
730
+ /**
731
+ * 指针在元素上移动时回调轻微的 3D 倾斜角度(`rotateX` / `rotateY`,单位 deg),离开时回到 0。
732
+ *
733
+ * 仅在有悬停能力的精细指针(鼠标 / 触控板)上启用;`prefers-reduced-motion: reduce`、
734
+ * 触屏或 SSR 下直接返回空的清理函数。
735
+ *
736
+ * @returns 停止监听的清理函数
737
+ */
738
+ function observeAcTilt(target, onTilt, maxTilt = 4) {
739
+ const matchMedia = globalThis.matchMedia;
740
+ if (typeof matchMedia !== "function" || !matchMedia(finePointerQuery).matches || matchMedia("(prefers-reduced-motion: reduce)").matches) return () => {};
741
+ let frame = 0;
742
+ const schedule = (rotateX, rotateY) => {
743
+ cancelAnimationFrame(frame);
744
+ frame = requestAnimationFrame(() => onTilt(rotateX, rotateY));
745
+ };
746
+ const onMove = (event) => {
747
+ const rect = target.getBoundingClientRect();
748
+ if (!rect.width || !rect.height) return;
749
+ const x = (event.clientX - rect.left) / rect.width - .5;
750
+ const y = (event.clientY - rect.top) / rect.height - .5;
751
+ const round = (value) => Math.round(value * 100) / 100;
752
+ schedule(round(-y * 2 * maxTilt), round(x * 2 * maxTilt));
753
+ };
754
+ const onLeave = () => schedule(0, 0);
755
+ target.addEventListener("pointermove", onMove);
756
+ target.addEventListener("pointerleave", onLeave);
757
+ return () => {
758
+ cancelAnimationFrame(frame);
759
+ target.removeEventListener("pointermove", onMove);
760
+ target.removeEventListener("pointerleave", onLeave);
761
+ };
762
+ }
763
+ //#endregion
764
+ //#region src/model.ts
765
+ const acForms = ["wall", "tower"];
766
+ const acFormLabels = {
767
+ wall: "挂机",
768
+ tower: "柜机"
769
+ };
770
+ /** 网页用的模型文件名(站点的 `public/models/` 下) */
771
+ const acModelFiles = {
772
+ wall: "CuteAC.glb",
773
+ tower: "CuteACTower.glb"
774
+ };
775
+ /** 渲染器要控制的命名节点,两种形态相同 */
776
+ const acModelParts = {
777
+ /** 导风板:挂机是一整块,柜机是一组百叶(子节点) */
778
+ louver: "Louver",
779
+ /** 0.25 × 0.1、UV 为 0–1 的平面,贴温度画面 */
780
+ display: "Display",
781
+ /** 指示灯 */
782
+ led: "Led"
783
+ };
784
+ const acLouverMotion = {
785
+ wall: {
786
+ pivot: "node",
787
+ openAngle: 40
788
+ },
789
+ tower: {
790
+ pivot: "children",
791
+ openAngle: 30
792
+ }
793
+ };
794
+ const acAirflowAnchors = {
795
+ wall: {
796
+ offset: [
797
+ 0,
798
+ -.1,
799
+ .05
800
+ ],
801
+ extent: 1.5,
802
+ direction: "down"
803
+ },
804
+ tower: {
805
+ offset: [
806
+ .24,
807
+ 0,
808
+ .08
809
+ ],
810
+ extent: .5,
811
+ direction: "side"
812
+ }
813
+ };
814
+ /** 指示灯与显示窗的颜色:开机时是模式色,关机是灰色(与 `ACPalette` 一致) */
815
+ const acModelColors = {
816
+ cold: "#5aa9ff",
817
+ hot: "#ff9f5a",
818
+ off: "#8e97aa"
819
+ };
820
+ function getAcLedColor(state) {
821
+ return state.status ? acModelColors[state.mode] : acModelColors.off;
822
+ }
823
+ function isAcForm(value) {
824
+ return value === "wall" || value === "tower";
825
+ }
826
+ //#endregion
827
+ //#region src/press.ts
828
+ /**
829
+ * 让按键支持长按连续触发,和真的遥控器一样:按下立即触发一次,按住一会儿后连续触发并逐渐加速,
830
+ * 松开、移出或取消时停止。键盘的 Enter / 空格仍走 `click`,每按一次触发一次。
831
+ *
832
+ * @param element 按键
833
+ * @param fire 每次触发时调用
834
+ * @param options 节奏与停止条件
835
+ * @returns 解除绑定的清理函数
836
+ */
837
+ function bindAcPressRepeat(element, fire, options = {}) {
838
+ const { delay = 500, interval = 200, minInterval = 100, value } = options;
839
+ let timer;
840
+ let wait = interval;
841
+ let last;
842
+ const stop = () => {
843
+ clearTimeout(timer);
844
+ timer = void 0;
845
+ };
846
+ const tick = () => {
847
+ if (value && value() === last) return stop();
848
+ last = value?.();
849
+ fire();
850
+ wait = Math.max(minInterval, wait * .85);
851
+ timer = setTimeout(tick, wait);
852
+ };
853
+ const onPointerDown = (event) => {
854
+ if (event.button !== 0) return;
855
+ stop();
856
+ last = value?.();
857
+ fire();
858
+ wait = interval;
859
+ timer = setTimeout(tick, delay);
860
+ };
861
+ const onClick = (event) => {
862
+ if (event.detail === 0) fire();
863
+ };
864
+ const onContextMenu = (event) => event.preventDefault();
865
+ element.addEventListener("pointerdown", onPointerDown);
866
+ element.addEventListener("pointerup", stop);
867
+ element.addEventListener("pointerleave", stop);
868
+ element.addEventListener("pointercancel", stop);
869
+ element.addEventListener("click", onClick);
870
+ element.addEventListener("contextmenu", onContextMenu);
871
+ return () => {
872
+ stop();
873
+ element.removeEventListener("pointerdown", onPointerDown);
874
+ element.removeEventListener("pointerup", stop);
875
+ element.removeEventListener("pointerleave", stop);
876
+ element.removeEventListener("pointercancel", stop);
877
+ element.removeEventListener("click", onClick);
878
+ element.removeEventListener("contextmenu", onContextMenu);
879
+ };
104
880
  }
105
881
  //#endregion
106
882
  //#region src/reducer.ts
107
- function normalizeAcState(state) {
883
+ /**
884
+ * Merge a partial state over the defaults and clamp its temperature.
885
+ *
886
+ * @param state - Partial or stored state
887
+ * @param limits - Device limits; omit to keep the default 16–31 °C range
888
+ */
889
+ function normalizeAcState(state, limits) {
890
+ const mode = state?.mode === "hot" ? "hot" : "cold";
891
+ const temperature = clampTemperature(state?.temperature ?? defaultAcState.temperature, limits);
892
+ const remembered = (other) => {
893
+ const value = state?.temperatures?.[other];
894
+ return typeof value === "number" && Number.isFinite(value) ? clampTemperature(value, limits) : temperature;
895
+ };
108
896
  return {
109
897
  ...defaultAcState,
110
898
  ...state,
111
- temperature: clampTemperature(state?.temperature ?? defaultAcState.temperature)
899
+ mode,
900
+ temperature,
901
+ temperatures: {
902
+ cold: mode === "cold" ? temperature : remembered("cold"),
903
+ hot: mode === "hot" ? temperature : remembered("hot")
904
+ },
905
+ sound: isAcSoundMode(state?.sound) ? state.sound : defaultAcState.sound,
906
+ swing: typeof state?.swing === "boolean" ? state.swing : defaultAcState.swing,
907
+ fan: isAcFanSpeed(state?.fan) ? state.fan : "auto"
112
908
  };
113
909
  }
114
- function clampTemperature(temperature) {
115
- return Math.min(31, Math.max(16, temperature));
910
+ /** Set the current mode's temperature, keeping `temperatures` in step. */
911
+ function withTemperature(state, temperature) {
912
+ const temperatures = {
913
+ cold: temperature,
914
+ hot: temperature,
915
+ ...state.temperatures
916
+ };
917
+ temperatures[state.mode] = temperature;
918
+ return {
919
+ ...state,
920
+ temperature,
921
+ temperatures
922
+ };
923
+ }
924
+ /**
925
+ * Clamp a temperature into range. When `limits` are given the value also
926
+ * snaps to the device step, measured from `limits.min`.
927
+ *
928
+ * @param temperature - Requested temperature in Celsius
929
+ * @param limits - Device limits; omit to clamp to 16–31 °C without snapping
930
+ */
931
+ function clampTemperature(temperature, limits) {
932
+ if (!limits) return Math.min(31, Math.max(16, temperature));
933
+ const { min, max, step } = limits;
934
+ const snapped = step > 0 ? Math.round((temperature - min) / step) * step + min : temperature;
935
+ return Number(Math.min(max, Math.max(min, snapped)).toFixed(4));
116
936
  }
117
- function acReducer(state, action) {
937
+ /**
938
+ * Apply an action to the state.
939
+ *
940
+ * @param state - Current state
941
+ * @param action - Action to apply
942
+ * @param limits - Device limits; increments use `limits.step`
943
+ */
944
+ function acReducer(state, action, limits) {
945
+ const step = limits?.step ?? defaultAcLimits.step;
118
946
  switch (action.type) {
119
- case "increment": return {
120
- ...state,
121
- temperature: clampTemperature(state.temperature + 1)
122
- };
123
- case "decrement": return {
124
- ...state,
125
- temperature: clampTemperature(state.temperature - 1)
126
- };
947
+ case "increment": return withTemperature(state, clampTemperature(state.temperature + step, limits));
948
+ case "decrement": return withTemperature(state, clampTemperature(state.temperature - step, limits));
127
949
  case "toggleStatus": return {
128
950
  ...state,
129
951
  status: !state.status
@@ -132,36 +954,143 @@ function acReducer(state, action) {
132
954
  ...state,
133
955
  status: action.status
134
956
  };
135
- case "mode": return {
957
+ case "mode": {
958
+ const status = state.status || action.powerOn === true;
959
+ if (action.mode === state.mode) return status === state.status ? state : {
960
+ ...state,
961
+ status
962
+ };
963
+ const temperatures = {
964
+ cold: state.temperature,
965
+ hot: state.temperature,
966
+ ...state.temperatures,
967
+ [state.mode]: state.temperature
968
+ };
969
+ return {
970
+ ...state,
971
+ status,
972
+ mode: action.mode,
973
+ temperature: clampTemperature(temperatures[action.mode] ?? state.temperature, limits),
974
+ temperatures
975
+ };
976
+ }
977
+ case "sound": return {
978
+ ...state,
979
+ sound: isAcSoundMode(action.sound) ? action.sound : state.sound
980
+ };
981
+ case "cycleSound": return {
982
+ ...state,
983
+ sound: nextAcSoundMode(state.sound)
984
+ };
985
+ case "toggleSwing": return {
986
+ ...state,
987
+ swing: !state.swing
988
+ };
989
+ case "swing": return {
990
+ ...state,
991
+ swing: action.swing === true
992
+ };
993
+ case "fan": return {
136
994
  ...state,
137
- mode: action.mode
995
+ fan: isAcFanSpeed(action.fan) ? action.fan : state.fan
996
+ };
997
+ case "cycleFan": return {
998
+ ...state,
999
+ fan: nextAcFanSpeed(state.fan)
138
1000
  };
139
1001
  case "update": return normalizeAcState({
140
1002
  ...state,
141
1003
  ...action.payload
142
- });
1004
+ }, limits);
143
1005
  default: throw new Error("Unexpected Ac Action");
144
1006
  }
145
1007
  }
1008
+ /**
1009
+ * 节能建议的短文案(显示在小纸条上)与补充说明。
1010
+ */
1011
+ function getEnergyTip(mode, temperature) {
1012
+ return mode === "cold" ? {
1013
+ message: `制冷调到 ${temperature}°C 以上更省电`,
1014
+ detail: "少开一度,为节能减排出一份力"
1015
+ } : {
1016
+ message: `制热调到 ${temperature}°C 以下更省电`,
1017
+ detail: "少开一度,为节能减排出一份力"
1018
+ };
1019
+ }
1020
+ /**
1021
+ * 创建一个提示「呈现器」:每个视图实例一个,记住提示过的节能建议,避免重复打扰。
1022
+ */
1023
+ function createAcNotificationPresenter() {
1024
+ let lastTip;
1025
+ return (notification, state) => {
1026
+ if (notification.kind === "limit") return "shake";
1027
+ if (notification.kind === "setting") return "announce";
1028
+ const key = `${state.mode}:${state.temperature}`;
1029
+ if (key === lastTip) return "skip";
1030
+ lastTip = key;
1031
+ return "note";
1032
+ };
1033
+ }
146
1034
  function getRecommendedTemperatureMessage(mode, temperature) {
147
1035
  return `建议将空调的制${mode === "cold" ? "冷" : "热"}温度调至 ${temperature} 度以${mode === "cold" ? "上" : "下"},为节能减排贡献一份力量!`;
148
1036
  }
149
- function getAcActionNotification(previousState, nextState, action) {
150
- if (action.type === "increment" && previousState.temperature >= 31) return {
1037
+ function getSoundModeMessage(sound) {
1038
+ return `${acSoundModeLabels[sound]}模式:${{
1039
+ normal: "风声和按键音恢复正常",
1040
+ sleep: "风声和按键音都调小了,晚安",
1041
+ mute: "空调不再发出任何声音"
1042
+ }[sound]}`;
1043
+ }
1044
+ function getFanSpeedMessage(fan) {
1045
+ return fan === "auto" ? "风速:自动,由空调根据室温调节" : `风速:${acFanSpeedLabels[fan]}`;
1046
+ }
1047
+ function getSwingMessage(swing) {
1048
+ return swing ? "扫风已开启:导风板上下摆动,出风左右扫" : "扫风已关闭:导风板停在当前位置";
1049
+ }
1050
+ /**
1051
+ * Visual tone for a state: `idle` when off, otherwise `cool` or `heat`.
1052
+ *
1053
+ * @param state - Current state
1054
+ */
1055
+ function acTone(state) {
1056
+ if (!state.status) return "idle";
1057
+ return state.mode === "hot" ? "heat" : "cool";
1058
+ }
1059
+ function getAcActionNotification(previousState, nextState, action, limits = defaultAcLimits) {
1060
+ if (action.type === "increment" && previousState.temperature >= limits.max) return {
151
1061
  message: "已经是最大温度啦!",
152
- severity: "error"
1062
+ severity: "error",
1063
+ kind: "limit"
153
1064
  };
154
- if (action.type === "decrement" && previousState.temperature <= 16) return {
1065
+ if (action.type === "decrement" && previousState.temperature <= limits.min) return {
155
1066
  message: "已经是最小温度啦!",
156
- severity: "error"
1067
+ severity: "error",
1068
+ kind: "limit"
1069
+ };
1070
+ if ((action.type === "sound" || action.type === "cycleSound") && nextState.sound !== previousState.sound) return {
1071
+ message: getSoundModeMessage(nextState.sound),
1072
+ severity: "info",
1073
+ kind: "setting"
1074
+ };
1075
+ if ((action.type === "fan" || action.type === "cycleFan") && nextState.fan && nextState.fan !== previousState.fan) return {
1076
+ message: getFanSpeedMessage(nextState.fan),
1077
+ severity: "info",
1078
+ kind: "setting"
157
1079
  };
158
- if (action.type === "mode" && nextState.mode === "cold" && previousState.temperature < 26) return {
159
- message: getRecommendedTemperatureMessage("cold", 26),
160
- severity: "success"
1080
+ if ((action.type === "swing" || action.type === "toggleSwing") && nextState.swing !== previousState.swing) return {
1081
+ message: getSwingMessage(nextState.swing),
1082
+ severity: "info",
1083
+ kind: "setting"
161
1084
  };
162
- if (action.type === "mode" && nextState.mode === "hot" && previousState.temperature > 20) return {
163
- message: getRecommendedTemperatureMessage("hot", 20),
164
- severity: "success"
1085
+ if (action.type === "mode" && nextState.mode === "cold" && nextState.temperature < 26) return {
1086
+ ...getEnergyTip("cold", 26),
1087
+ severity: "success",
1088
+ kind: "tip"
1089
+ };
1090
+ if (action.type === "mode" && nextState.mode === "hot" && nextState.temperature > 20) return {
1091
+ ...getEnergyTip("hot", 20),
1092
+ severity: "success",
1093
+ kind: "tip"
165
1094
  };
166
1095
  }
167
1096
  //#endregion
@@ -210,11 +1139,12 @@ function createAirConditionerStore(options = {}) {
210
1139
  const storageKey = options.storageKey ?? "ac:state";
211
1140
  const storage = options.storage === void 0 ? getBrowserStorage() : options.storage;
212
1141
  const persistedState = readAcState(storage, storageKey);
1142
+ const limits = options.limits;
213
1143
  let state = normalizeAcState({
214
1144
  ...defaultAcState,
215
1145
  ...persistedState,
216
1146
  ...options.initialState
217
- });
1147
+ }, limits);
218
1148
  const listeners = /* @__PURE__ */ new Set();
219
1149
  return {
220
1150
  getState() {
@@ -222,8 +1152,8 @@ function createAirConditionerStore(options = {}) {
222
1152
  },
223
1153
  dispatch(action) {
224
1154
  const previousState = state;
225
- const nextState = acReducer(state, action);
226
- const notification = getAcActionNotification(previousState, nextState, action);
1155
+ const nextState = acReducer(state, action, limits);
1156
+ const notification = getAcActionNotification(previousState, nextState, action, limits);
227
1157
  const event = {
228
1158
  action,
229
1159
  previousState,
@@ -245,4 +1175,283 @@ function createAirConditionerStore(options = {}) {
245
1175
  };
246
1176
  }
247
1177
  //#endregion
248
- export { acAudioFileNames, acModeIcons, acReducer, acStorageKey, clampTemperature, createAcAudioController, createAirConditionerStore, createMemoryStorage, defaultAcState, getAcActionNotification, getBrowserStorage, getRecommendedTemperatureMessage, maxTemperature, minTemperature, normalizeAcState, readAcState, recommendedColdTemperature, recommendedHotTemperature, resolveAcAudioAssets, soundTimings, writeAcState };
1178
+ //#region src/thermal/levels.ts
1179
+ const heatLevels = [
1180
+ "nominal",
1181
+ "fair",
1182
+ "serious",
1183
+ "critical"
1184
+ ];
1185
+ /** Default Celsius thresholds for fair, serious and critical. */
1186
+ const defaultHeatThresholds = [
1187
+ 60,
1188
+ 75,
1189
+ 90
1190
+ ];
1191
+ /**
1192
+ * @param level - A heat level
1193
+ * @returns Its rank from 0 (nominal) to 3 (critical)
1194
+ */
1195
+ function heatLevelRank(level) {
1196
+ return heatLevels.indexOf(level);
1197
+ }
1198
+ function isHeatLevel(value) {
1199
+ return heatLevels.includes(value);
1200
+ }
1201
+ /**
1202
+ * Convert a temperature to a heat level. With a previous level, the value
1203
+ * must fall `hysteresis` degrees below a threshold before dropping a level,
1204
+ * which keeps readings near a threshold from flickering.
1205
+ *
1206
+ * @param celsius - Measured temperature
1207
+ * @param thresholds - Lower bounds for fair, serious and critical
1208
+ * @param previous - Level from the previous reading
1209
+ * @param hysteresis - Degrees required below a threshold to step down
1210
+ */
1211
+ function celsiusToHeatLevel(celsius, thresholds = defaultHeatThresholds, previous, hysteresis = 5) {
1212
+ const raw = thresholds.filter((threshold) => celsius >= threshold).length;
1213
+ if (previous === void 0) return heatLevels[raw];
1214
+ const held = thresholds.filter((threshold) => celsius >= threshold - hysteresis).length;
1215
+ return heatLevels[Math.max(raw, Math.min(heatLevelRank(previous), held))];
1216
+ }
1217
+ /**
1218
+ * Create a filter that raises the level immediately but only lowers it after
1219
+ * lower readings persist for `dwellMs`, measured with `reading.at`.
1220
+ *
1221
+ * @param options - Governor options
1222
+ * @param options.dwellMs - Time a lower level must persist; defaults to 30 seconds
1223
+ * @returns A function that maps each reading to the settled level
1224
+ */
1225
+ function createHeatGovernor(options = {}) {
1226
+ const dwellMs = options.dwellMs ?? 3e4;
1227
+ let current;
1228
+ let lowerSince;
1229
+ return (reading) => {
1230
+ if (current === void 0 || heatLevelRank(reading.level) >= heatLevelRank(current)) {
1231
+ current = reading.level;
1232
+ lowerSince = void 0;
1233
+ return current;
1234
+ }
1235
+ lowerSince ??= reading.at;
1236
+ if (reading.at - lowerSince >= dwellMs) {
1237
+ current = reading.level;
1238
+ lowerSince = void 0;
1239
+ }
1240
+ return current;
1241
+ };
1242
+ }
1243
+ //#endregion
1244
+ //#region src/thermal/plan.ts
1245
+ const coolingByLevel = {
1246
+ fair: {
1247
+ temperature: 26,
1248
+ airflow: .4
1249
+ },
1250
+ serious: {
1251
+ temperature: 24,
1252
+ airflow: .7
1253
+ },
1254
+ critical: {
1255
+ temperature: 22,
1256
+ airflow: 1
1257
+ }
1258
+ };
1259
+ /**
1260
+ * Decide how the virtual air conditioner should respond to a heat level.
1261
+ *
1262
+ * @param level - Settled heat level
1263
+ * @param limits - Device limits used to clamp the target temperature
1264
+ * @returns A cooling plan, or `null` at `nominal` so the user keeps control
1265
+ */
1266
+ function planCooling(level, limits) {
1267
+ if (level === "nominal") return null;
1268
+ const { temperature, airflow } = coolingByLevel[level];
1269
+ return {
1270
+ status: true,
1271
+ mode: "cold",
1272
+ temperature: clampTemperature(temperature, limits),
1273
+ airflow
1274
+ };
1275
+ }
1276
+ //#endregion
1277
+ //#region src/thermal/pressure.ts
1278
+ function getPressureObserver() {
1279
+ return globalThis.PressureObserver;
1280
+ }
1281
+ /**
1282
+ * Heat source backed by the browser Compute Pressure API. It reports CPU
1283
+ * load levels, not temperatures; browsers expose no CPU temperature.
1284
+ *
1285
+ * Supported in Chromium-based browsers on secure origins. The API is only
1286
+ * touched when the source is started.
1287
+ *
1288
+ * @param options - Sampling and error handling options
1289
+ */
1290
+ function createComputePressureSource(options = {}) {
1291
+ return {
1292
+ id: "compute-pressure",
1293
+ isSupported: () => typeof getPressureObserver() === "function",
1294
+ start(listener) {
1295
+ const Observer = getPressureObserver();
1296
+ if (!Observer) return () => {};
1297
+ let stopped = false;
1298
+ const observer = new Observer((records) => {
1299
+ const record = records.at(-1);
1300
+ if (stopped || !record || !isHeatLevel(record.state)) return;
1301
+ listener({
1302
+ level: record.state,
1303
+ source: "compute-pressure",
1304
+ at: Date.now()
1305
+ });
1306
+ });
1307
+ observer.observe("cpu", { sampleInterval: options.sampleIntervalMs ?? 2e3 }).catch((error) => {
1308
+ if (!stopped) options.onError?.(error);
1309
+ });
1310
+ return () => {
1311
+ stopped = true;
1312
+ observer.disconnect();
1313
+ };
1314
+ }
1315
+ };
1316
+ }
1317
+ //#endregion
1318
+ //#region src/icons.ts
1319
+ /**
1320
+ * 遥控器按钮与提示图标(24 × 24 viewBox 的 SVG path),全部来自 Material Design
1321
+ * Icons,和站点通过 UnoCSS presetIcons 使用的 i-mdi-* 是同一套。
1322
+ */
1323
+ const acIconPaths = {
1324
+ /** mdi:snowflake */
1325
+ cold: "m20.79 13.95l-2.33.62l-2-1.13v-2.88l2-1.13l2.33.62l.52-1.93l-1.77-.47l.46-1.77l-1.93-.52l-.62 2.33l-2 1.13L13 7.38V5.12l1.71-1.71L13.29 2L12 3.29L10.71 2L9.29 3.41L11 5.12v2.26L8.5 8.82l-2-1.13l-.58-2.33L4 5.88l.47 1.77l-1.77.47l.52 1.93l2.33-.62l2 1.13v2.89l-2 1.13l-2.33-.62l-.52 1.93l1.77.47L4 18.12l1.93.52l.62-2.33l2-1.13L11 16.62v2.26l-1.71 1.71L10.71 22L12 20.71L13.29 22l1.41-1.41l-1.7-1.71v-2.26l2.5-1.45l2 1.13l.62 2.33l1.88-.51l-.47-1.77l1.77-.47zM9.5 10.56L12 9.11l2.5 1.45v2.88L12 14.89l-2.5-1.45z",
1326
+ /** mdi:white-balance-sunny */
1327
+ hot: "m3.55 19.09l1.41 1.41l1.8-1.79l-1.42-1.42M12 6c-3.31 0-6 2.69-6 6s2.69 6 6 6s6-2.69 6-6c0-3.32-2.69-6-6-6m8 7h3v-2h-3m-2.76 7.71l1.8 1.79l1.41-1.41l-1.79-1.8M20.45 5l-1.41-1.4l-1.8 1.79l1.42 1.42M13 1h-2v3h2M6.76 5.39L4.96 3.6L3.55 5l1.79 1.81zM1 13h3v-2H1m12 9h-2v3h2",
1328
+ /** mdi:power */
1329
+ power: "m16.56 5.44l-1.45 1.45A5.97 5.97 0 0 1 18 12a6 6 0 0 1-6 6a6 6 0 0 1-6-6c0-2.17 1.16-4.06 2.88-5.12L7.44 5.44A7.96 7.96 0 0 0 4 12a8 8 0 0 0 8 8a8 8 0 0 0 8-8c0-2.72-1.36-5.12-3.44-6.56M13 3h-2v10h2",
1330
+ /** mdi:plus */
1331
+ plus: "M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z",
1332
+ /** mdi:minus */
1333
+ minus: "M19 13H5v-2h14z",
1334
+ /** mdi:menu-up */
1335
+ increase: "m7 15l5-5l5 5z",
1336
+ /** mdi:menu-down */
1337
+ decrease: "m7 10l5 5l5-5z",
1338
+ /** mdi:fan */
1339
+ fan: "M12 11a1 1 0 0 0-1 1a1 1 0 0 0 1 1a1 1 0 0 0 1-1a1 1 0 0 0-1-1m.5-9c4.5 0 4.61 3.57 2.25 4.75c-.99.49-1.43 1.54-1.62 2.47c.48.2.9.51 1.22.91c3.7-2 7.68-1.21 7.68 2.37c0 4.5-3.57 4.6-4.75 2.23c-.5-.99-1.56-1.43-2.49-1.62c-.2.48-.51.89-.91 1.23c1.99 3.69 1.2 7.66-2.38 7.66c-4.5 0-4.59-3.58-2.23-4.76c.98-.49 1.42-1.53 1.62-2.45c-.49-.2-.92-.52-1.24-.92C5.96 15.85 2 15.07 2 11.5C2 7 5.56 6.89 6.74 9.26c.5.99 1.55 1.42 2.48 1.61c.19-.48.51-.9.92-1.22C8.15 5.96 8.94 2 12.5 2",
1340
+ /** mdi:arrow-oscillating */
1341
+ swing: "M6 14h3l-4 4l-4-4h3c0-2.7 1.7-7.4 7-7.9v2c-3.4.5-5 3.8-5 5.9m14 0c0-2.7-1.7-7.4-7-7.9v2c3.4.6 5 3.8 5 5.9h-3l4 4l4-4z",
1342
+ /** mdi:volume-high */
1343
+ soundNormal: "M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.84-5 6.7v2.07c4-.91 7-4.49 7-8.77s-3-7.86-7-8.77M16.5 12c0-1.77-1-3.29-2.5-4.03V16c1.5-.71 2.5-2.24 2.5-4M3 9v6h4l5 5V4L7 9z",
1344
+ /** mdi:weather-night */
1345
+ soundSleep: "m17.75 4.09l-2.53 1.94l.91 3.06l-2.63-1.81l-2.63 1.81l.91-3.06l-2.53-1.94L12.44 4l1.06-3l1.06 3zm3.5 6.91l-1.64 1.25l.59 1.98l-1.7-1.17l-1.7 1.17l.59-1.98L15.75 11l2.06-.05L18.5 9l.69 1.95zm-2.28 4.95c.83-.08 1.72 1.1 1.19 1.85c-.32.45-.66.87-1.08 1.27C15.17 23 8.84 23 4.94 19.07c-3.91-3.9-3.91-10.24 0-14.14c.4-.4.82-.76 1.27-1.08c.75-.53 1.93.36 1.85 1.19c-.27 2.86.69 5.83 2.89 8.02a9.96 9.96 0 0 0 8.02 2.89m-1.64 2.02a12.08 12.08 0 0 1-7.8-3.47c-2.17-2.19-3.33-5-3.49-7.82c-2.81 3.14-2.7 7.96.31 10.98c3.02 3.01 7.84 3.12 10.98.31",
1346
+ /** mdi:volume-off */
1347
+ soundMute: "M12 4L9.91 6.09L12 8.18M4.27 3L3 4.27L7.73 9H3v6h4l5 5v-6.73l4.25 4.26c-.67.51-1.42.93-2.25 1.17v2.07c1.38-.32 2.63-.95 3.68-1.81L19.73 21L21 19.73l-9-9M19 12c0 .94-.2 1.82-.54 2.64l1.51 1.51A8.9 8.9 0 0 0 21 12c0-4.28-3-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71m-2.5 0c0-1.77-1-3.29-2.5-4.03v2.21l2.45 2.45c.05-.2.05-.42.05-.63",
1348
+ /** mdi:leaf */
1349
+ leaf: "M17 8C8 10 5.9 16.17 3.82 21.34l1.89.66l.95-2.3c.48.17.98.3 1.34.3C19 20 22 3 22 3c-1 2-8 2.25-13 3.25S2 11.5 2 13.5s1.75 3.75 1.75 3.75C7 8 17 8 17 8"
1350
+ };
1351
+ //#endregion
1352
+ //#region src/ui.ts
1353
+ /**
1354
+ * 声音键在各声音模式下显示的图标。
1355
+ */
1356
+ const acSoundIcons = {
1357
+ normal: "soundNormal",
1358
+ sleep: "soundSleep",
1359
+ mute: "soundMute"
1360
+ };
1361
+ /**
1362
+ * 遥控器小屏的读屏文字与各按键的悬停提示,保证各框架文案一致。
1363
+ */
1364
+ function getAcRemoteText(state) {
1365
+ const swing = `扫风:${state.swing ? "开" : "关"}`;
1366
+ const sound = `声音:${acSoundModeLabels[state.sound]}`;
1367
+ const fan = `风速:${acFanSpeedLabels[state.fan ?? "auto"]}`;
1368
+ return {
1369
+ display: `${state.status ? "运行" : "待机"},${acModeLabels[state.mode]} ${state.temperature}°C,${fan},${swing},${sound}`,
1370
+ power: `电源:${state.status ? "开" : "关"}`,
1371
+ mode: acModeLabels,
1372
+ fan,
1373
+ swing,
1374
+ sound
1375
+ };
1376
+ }
1377
+ /**
1378
+ * 能效标签的点阵与等级条布局:蓝白背景的「中国能效标识」,带能效信息码
1379
+ * (二维码),样式依据《房间空气调节器能源效率标识实施规则》(CEL 010—2019)。
1380
+ *
1381
+ * 等级按现行 GB 21455-2019 分 5 级,1 级最高。GB 21455 的修订版征求意见稿
1382
+ * (2026 年 5 月)拟改为 3 级、以全年动态能源消耗效率(DAPF)分级;正式发布并
1383
+ * 实施后,再更新 `grades`、`standard` 与 `levels`。
1384
+ *
1385
+ * - `top`:标识名称(白点),右侧是能效信息码
1386
+ * - 等级区:首行是 1 级绿色条和指示箭头,`levels` 是 2–5 级
1387
+ * - `detail`:生产者、型号、APF 等参数(黑点)
1388
+ * - `footer`:依据的国家标准编号(白点)
1389
+ */
1390
+ const acEnergyLabel = {
1391
+ grade: 1,
1392
+ grades: 5,
1393
+ standard: "GB 21455-2019",
1394
+ top: [{
1395
+ num: 4,
1396
+ size: 4,
1397
+ mx: 1.5,
1398
+ my: 0,
1399
+ color: "white"
1400
+ }],
1401
+ detail: [
1402
+ {
1403
+ num: 11,
1404
+ size: 2,
1405
+ mx: .8,
1406
+ my: 2,
1407
+ color: "black"
1408
+ },
1409
+ {
1410
+ num: 9,
1411
+ size: 1.5,
1412
+ mx: .8,
1413
+ my: 2,
1414
+ color: "black"
1415
+ },
1416
+ {
1417
+ num: 10,
1418
+ size: 1.2,
1419
+ mx: .8,
1420
+ my: 0,
1421
+ color: "black"
1422
+ }
1423
+ ],
1424
+ footer: {
1425
+ num: 8,
1426
+ size: 2,
1427
+ mx: .8,
1428
+ my: 0,
1429
+ color: "white"
1430
+ },
1431
+ levels: [
1432
+ {
1433
+ background: "lightgreen",
1434
+ width: "50%"
1435
+ },
1436
+ {
1437
+ background: "#fdd835",
1438
+ width: "60%"
1439
+ },
1440
+ {
1441
+ background: "orange",
1442
+ width: "70%"
1443
+ },
1444
+ {
1445
+ background: "red",
1446
+ width: "80%"
1447
+ }
1448
+ ]
1449
+ };
1450
+ /**
1451
+ * 能效标签的读屏文字。
1452
+ */
1453
+ function getAcEnergyLabelText() {
1454
+ return `中国能效标识:能效等级 ${acEnergyLabel.grade} 级(共 ${acEnergyLabel.grades} 级),依据 ${acEnergyLabel.standard}`;
1455
+ }
1456
+ //#endregion
1457
+ export { acAirflowAnchors, acAudioFileNames, acDripIntervalRange, acDripMaxTemperature, acEnergyLabel, acFanBars, acFanSoundLevels, acFanSpeedLabels, acFanSpeeds, acFormLabels, acForms, acIconPaths, acLouverMotion, acMaxTilt, acModeIcons, acModeLabels, acModelColors, acModelFiles, acModelParts, acMotion, acReducedMotionDuration, acReducedMotionQuery, acReducer, acShellSize, acSoundIcons, acSoundModeLabels, acSoundModes, acSoundVolumes, acStorageKey, acTone, bindAcPressRepeat, celsiusToHeatLevel, clampTemperature, createAcAudioController, createAcNotificationPresenter, createAirConditionerStore, createComputePressureSource, createHeatGovernor, createMemoryStorage, defaultAcLimits, defaultAcState, defaultHeatThresholds, getAcActionNotification, getAcCondensationStyle, getAcDripInterval, getAcEnergyLabelText, getAcLedColor, getAcMist, getAcRemoteText, getAcScale, getBrowserStorage, getEnergyTip, getFanSpeedMessage, getRecommendedTemperatureMessage, getSoundModeMessage, getSwingMessage, heatLevelRank, heatLevels, isAcFanSpeed, isAcForm, isAcSoundMode, isHeatLevel, maxTemperature, minTemperature, nextAcFanSpeed, nextAcSoundMode, normalizeAcState, observeAcScale, observeAcTilt, planCooling, prefersReducedMotion, readAcState, recommendedColdTemperature, recommendedHotTemperature, renderAcMotionCssVars, resolveAcAudioAssets, soundTimings, writeAcState };