@yunlefun-home/air-conditioner-core 0.2.0 → 0.3.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,74 @@ 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
+ sound: "normal"
36
+ };
37
+ /**
38
+ * 遥控器「声音」键依次切换的顺序。
39
+ */
40
+ const acSoundModes = [
41
+ "normal",
42
+ "sleep",
43
+ "mute"
44
+ ];
45
+ const acSoundModeLabels = {
46
+ normal: "标准",
47
+ sleep: "睡眠",
48
+ mute: "静音"
49
+ };
50
+ /**
51
+ * 各声音模式的总音量(0–1)。
52
+ */
53
+ const acSoundVolumes = {
54
+ normal: 1,
55
+ sleep: .3,
56
+ mute: 0
30
57
  };
58
+ function isAcSoundMode(value) {
59
+ return acSoundModes.includes(value);
60
+ }
61
+ /**
62
+ * 声音键的下一个模式:标准 → 睡眠 → 静音 → 标准。
63
+ */
64
+ function nextAcSoundMode(mode) {
65
+ const index = Math.max(acSoundModes.indexOf(mode), 0);
66
+ return acSoundModes[(index + 1) % acSoundModes.length];
67
+ }
68
+ /**
69
+ * 音效时序。时长单位为毫秒,`*Level` 是风声相对音量(0–1)。
70
+ */
31
71
  const soundTimings = {
72
+ /** 开机后多久接上持续的风声(启动声约 9 秒) */
32
73
  startDelayMs: 8e3,
33
- noiseStartTime: 2,
34
- noiseDuration: 56
74
+ /** 风声循环首尾的交叉淡化时长 */
75
+ loopCrossfadeMs: 1500,
76
+ /** 关机时声音淡出时长 */
77
+ stopFadeMs: 600,
78
+ /** 开机运行多久后室温达标、风声降下来 */
79
+ settleAfterMs: 9e4,
80
+ /** 风声降下来的渐变时长 */
81
+ settleRampMs: 2e4,
82
+ /** 达标后的安静风声 */
83
+ settleLevel: .5,
84
+ /** 室温回升、压缩机重新发力时的风声 */
85
+ surgeLevel: .85,
86
+ /** 两次发力之间安静运行的时长范围 */
87
+ quietDurationMs: [18e4, 36e4],
88
+ /** 每次发力持续的时长范围 */
89
+ surgeDurationMs: [6e4, 12e4],
90
+ /** 发力 / 回落的渐变时长 */
91
+ surgeRampMs: 1e4
35
92
  };
36
93
  /**
37
94
  * 根据基础路径解析出三个音频文件的完整 URL。
@@ -51,78 +108,535 @@ function resolveAcAudioAssets(baseUrl = "/assets/audio", ext = "m4a") {
51
108
  }
52
109
  //#endregion
53
110
  //#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();
111
+ /** Web Audio 资源迟迟没加载好时,本次开机先用 `<audio>` 播放 */
112
+ const readyTimeoutMs = 1500;
113
+ const fallbackTweenStepMs = 100;
114
+ const curveLength = 64;
115
+ function sourceUrl(element) {
116
+ return element?.currentSrc || element?.src || "";
117
+ }
118
+ async function fetchAudioData(url) {
119
+ const response = await fetch(url);
120
+ if (!response.ok) throw new Error(`Failed to load ${url}: ${response.status}`);
121
+ return response.arrayBuffer();
122
+ }
123
+ function createDefaultAudioContext() {
124
+ const scope = globalThis;
125
+ const AudioContextConstructor = scope.AudioContext ?? scope.webkitAudioContext;
126
+ return AudioContextConstructor ? new AudioContextConstructor() : null;
127
+ }
128
+ /**
129
+ * 等功率淡入 / 淡出曲线,噪声类声音交叉淡化时中段不会变小。
130
+ */
131
+ function fadeCurve(direction) {
132
+ const curve = new Float32Array(curveLength);
133
+ for (let i = 0; i < curveLength; i++) {
134
+ const phase = i / 63 * Math.PI / 2;
135
+ curve[i] = direction === "in" ? Math.sin(phase) : Math.cos(phase);
136
+ }
137
+ return curve;
138
+ }
139
+ function randomBetween(range, random) {
140
+ return range[0] + (range[1] - range[0]) * random();
141
+ }
142
+ function playElement(element) {
143
+ if (!element) return;
144
+ element.load();
145
+ Promise.resolve(element.play()).catch(() => {});
146
+ }
147
+ function stopElement(element) {
148
+ if (!element) return;
149
+ if (element.pause) element.pause();
150
+ else element.load();
151
+ }
152
+ /**
153
+ * 空调音效:按键「嘀」声、开机启动声与持续的风声。
154
+ *
155
+ * 默认通过 Web Audio API 播放:风声无缝循环,开关机淡入淡出,运行一段时间后
156
+ * 风声变小、并不定时随压缩机发力起伏。环境不支持或音频无法获取时退回
157
+ * `<audio>` 元素。
158
+ *
159
+ * 需在用户交互(点击遥控器)里首次调用,浏览器才允许发声。
160
+ *
161
+ * @param elements 三个音频元素;Web Audio 会从它们的 `src` 获取音频
162
+ * @param options 声音模式与可替换的环境依赖
163
+ */
164
+ function createAcAudioController(elements, options = {}) {
165
+ const random = options.random ?? Math.random;
166
+ let soundMode = options.soundMode ?? "normal";
167
+ /** undefined:尚未尝试;null:不可用 */
168
+ let engine;
169
+ let run;
170
+ /** 每次开关机自增,丢弃过期的异步回调 */
171
+ let session = 0;
172
+ const timers = /* @__PURE__ */ new Set();
173
+ /** `<audio>` 播放时的风声相对音量 */
174
+ let fallbackFanLevel = 1;
175
+ let fallbackTween;
176
+ function later(callback, delayMs) {
177
+ const timer = setTimeout(() => {
178
+ timers.delete(timer);
179
+ callback();
180
+ }, delayMs);
181
+ timers.add(timer);
182
+ }
183
+ function clearTimers() {
184
+ timers.forEach((timer) => clearTimeout(timer));
185
+ timers.clear();
186
+ }
187
+ function volume() {
188
+ return acSoundVolumes[soundMode];
189
+ }
190
+ function applyElementVolume(element, level = 1) {
191
+ if (!element) return;
192
+ if (element.volume !== void 0) element.volume = Math.min(1, Math.max(0, volume() * level));
193
+ if (element.muted !== void 0) element.muted = soundMode === "mute";
194
+ }
195
+ function cancelFallbackTween() {
196
+ if (fallbackTween) clearInterval(fallbackTween);
197
+ fallbackTween = void 0;
198
+ }
199
+ function tweenFallbackFan(target, durationMs, onDone) {
200
+ cancelFallbackTween();
201
+ const from = fallbackFanLevel;
202
+ const steps = Math.max(1, Math.round(durationMs / fallbackTweenStepMs));
203
+ let step = 0;
204
+ fallbackTween = setInterval(() => {
205
+ step++;
206
+ fallbackFanLevel = from + (target - from) * (step / steps);
207
+ applyElementVolume(elements.work, fallbackFanLevel);
208
+ if (step >= steps) {
209
+ cancelFallbackTween();
210
+ onDone?.();
211
+ }
212
+ }, fallbackTweenStepMs);
213
+ }
214
+ function ensureEngine() {
215
+ if (engine !== void 0) return engine;
216
+ engine = createEngine();
217
+ return engine;
218
+ }
219
+ function createEngine() {
220
+ if (options.webAudio === false) return null;
221
+ let context;
222
+ try {
223
+ context = (options.createAudioContext ?? createDefaultAudioContext)();
224
+ } catch {
225
+ return null;
226
+ }
227
+ if (!context) return null;
228
+ const master = context.createGain();
229
+ master.gain.value = volume();
230
+ master.connect(context.destination);
231
+ const buffers = {};
232
+ const load = options.loadAudioData ?? fetchAudioData;
233
+ const decode = async (name) => {
234
+ const url = sourceUrl(elements[name]);
235
+ if (!url) return;
236
+ try {
237
+ buffers[name] = await context.decodeAudioData(await load(url));
238
+ } catch {}
239
+ };
240
+ const ready = Promise.all([
241
+ "beep",
242
+ "start",
243
+ "work"
244
+ ].map(decode)).then(() => Boolean(buffers.start && buffers.work));
245
+ return {
246
+ context,
247
+ master,
248
+ buffers,
249
+ ready
250
+ };
251
+ }
252
+ function resume(web) {
253
+ if (web.context.state === "suspended") Promise.resolve(web.context.resume()).catch(() => {});
254
+ }
255
+ function waitReady(web) {
256
+ return Promise.race([web.ready, new Promise((resolve) => setTimeout(resolve, readyTimeoutMs, false))]);
257
+ }
258
+ function playBuffer(web, buffer, destination, when) {
259
+ const source = web.context.createBufferSource();
260
+ source.buffer = buffer;
261
+ source.connect(destination);
262
+ source.start(when);
263
+ return source;
264
+ }
265
+ function track(target, source, cleanup) {
266
+ target.sources.add(source);
267
+ source.onended = () => {
268
+ target.sources.delete(source);
269
+ source.disconnect();
270
+ cleanup?.();
271
+ };
272
+ }
273
+ /**
274
+ * 排一段风声,并在它结束前交叉淡化接上下一段。
275
+ */
276
+ function loopFan(web, target, when) {
277
+ const buffer = web.buffers.work;
278
+ const crossfade = Math.min(soundTimings.loopCrossfadeMs / 1e3, buffer.duration / 2);
279
+ const gain = web.context.createGain();
280
+ gain.gain.value = 0;
281
+ gain.gain.setValueCurveAtTime(fadeCurve("in"), when, crossfade);
282
+ gain.gain.setValueCurveAtTime(fadeCurve("out"), when + buffer.duration - crossfade, crossfade);
283
+ gain.connect(target.fan);
284
+ const source = playBuffer(web, buffer, gain, when);
285
+ source.stop(when + buffer.duration);
286
+ track(target, source, () => gain.disconnect());
287
+ const next = when + buffer.duration - crossfade;
288
+ later(() => {
289
+ if (run === target) loopFan(web, target, next);
290
+ }, Math.max(0, (next - web.context.currentTime - 1) * 1e3));
291
+ }
292
+ function setFanLevel(level, rampMs) {
293
+ if (run && engine) {
294
+ const gain = run.fan.gain;
295
+ const now = engine.context.currentTime;
296
+ gain.cancelScheduledValues(now);
297
+ gain.setValueAtTime(gain.value, now);
298
+ gain.linearRampToValueAtTime(level, now + rampMs / 1e3);
299
+ } else tweenFallbackFan(level, rampMs);
300
+ }
301
+ /**
302
+ * 室温达标后风声变小;之后不定时随压缩机发力变大,再回落。
303
+ */
304
+ function startFanCycle() {
305
+ const quiet = () => {
306
+ later(() => {
307
+ setFanLevel(soundTimings.surgeLevel, soundTimings.surgeRampMs);
308
+ later(() => {
309
+ setFanLevel(soundTimings.settleLevel, soundTimings.surgeRampMs);
310
+ quiet();
311
+ }, randomBetween(soundTimings.surgeDurationMs, random));
312
+ }, randomBetween(soundTimings.quietDurationMs, random));
313
+ };
314
+ later(() => {
315
+ setFanLevel(soundTimings.settleLevel, soundTimings.settleRampMs);
316
+ quiet();
317
+ }, soundTimings.settleAfterMs);
318
+ }
319
+ function startWeb(web) {
320
+ const output = web.context.createGain();
321
+ output.connect(web.master);
322
+ const fan = web.context.createGain();
323
+ fan.connect(output);
324
+ const target = {
325
+ output,
326
+ fan,
327
+ sources: /* @__PURE__ */ new Set()
328
+ };
329
+ run = target;
330
+ const now = web.context.currentTime;
331
+ track(target, playBuffer(web, web.buffers.start, output, now));
332
+ loopFan(web, target, now + soundTimings.startDelayMs / 1e3);
333
+ later(startFanCycle, soundTimings.startDelayMs);
334
+ }
335
+ function stopWeb(fadeMs) {
336
+ const target = run;
337
+ run = void 0;
338
+ if (!target || !engine) return;
339
+ const now = engine.context.currentTime;
340
+ const end = now + fadeMs / 1e3;
341
+ const gain = target.output.gain;
342
+ gain.cancelScheduledValues(now);
343
+ gain.setValueAtTime(gain.value, now);
344
+ gain.linearRampToValueAtTime(0, end);
345
+ target.sources.forEach((source) => {
346
+ try {
347
+ source.stop(end);
348
+ } catch {}
349
+ });
350
+ setTimeout(() => target.output.disconnect(), fadeMs + 100);
351
+ }
352
+ function startFallback() {
353
+ const { start, work } = elements;
354
+ stopElement(work);
355
+ applyElementVolume(start);
356
+ playElement(start);
357
+ later(() => {
358
+ if (!work) return;
359
+ fallbackFanLevel = 0;
360
+ applyElementVolume(work, 0);
361
+ if (work.loop !== void 0) work.loop = true;
362
+ playElement(work);
363
+ tweenFallbackFan(1, soundTimings.loopCrossfadeMs);
364
+ startFanCycle();
84
365
  }, soundTimings.startDelayMs);
85
366
  }
367
+ function stopFallback(fadeMs) {
368
+ stopElement(elements.start);
369
+ if (fadeMs > 0) tweenFallbackFan(0, fadeMs, () => stopElement(elements.work));
370
+ else stopElement(elements.work);
371
+ }
372
+ function powerOn() {
373
+ const id = ++session;
374
+ clearTimers();
375
+ cancelFallbackTween();
376
+ stopWeb(0);
377
+ stopFallback(0);
378
+ const web = ensureEngine();
379
+ if (!web) {
380
+ startFallback();
381
+ return;
382
+ }
383
+ resume(web);
384
+ waitReady(web).then((ok) => {
385
+ if (id !== session) return;
386
+ if (ok) startWeb(web);
387
+ else startFallback();
388
+ });
389
+ }
390
+ function powerOff() {
391
+ session++;
392
+ clearTimers();
393
+ stopWeb(soundTimings.stopFadeMs);
394
+ stopFallback(soundTimings.stopFadeMs);
395
+ }
86
396
  return {
87
397
  beep() {
88
- play(elements.beep);
398
+ if (soundMode === "mute") return;
399
+ const web = ensureEngine();
400
+ if (web) {
401
+ resume(web);
402
+ if (web.buffers.beep) {
403
+ playBuffer(web, web.buffers.beep, web.master, web.context.currentTime);
404
+ return;
405
+ }
406
+ }
407
+ applyElementVolume(elements.beep);
408
+ playElement(elements.beep);
89
409
  },
90
410
  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;
95
- } else {
96
- clearWorkTimers();
97
- playStartSound();
98
- }
411
+ if (previousStatus) powerOff();
412
+ else powerOn();
413
+ },
414
+ setSoundMode(mode) {
415
+ soundMode = mode;
416
+ if (engine) engine.master.gain.setTargetAtTime(volume(), engine.context.currentTime, .08);
417
+ applyElementVolume(elements.beep);
418
+ applyElementVolume(elements.start);
419
+ applyElementVolume(elements.work, fallbackFanLevel);
99
420
  },
100
421
  dispose() {
101
- clearWorkTimers();
422
+ session++;
423
+ clearTimers();
424
+ cancelFallbackTween();
425
+ stopWeb(0);
426
+ stopFallback(0);
427
+ if (engine && !options.createAudioContext) Promise.resolve(engine.context.close()).catch(() => {});
428
+ engine = null;
429
+ }
430
+ };
431
+ }
432
+ //#endregion
433
+ //#region src/motion.ts
434
+ /**
435
+ * 动效 token:各框架视图层共用的时长与缓动曲线。
436
+ *
437
+ * 样式里统一通过 CSS 变量(`--acw-motion-*`)引用,
438
+ * 需要在 JS 里计时的地方(如 React 过渡组件)直接读取 `acMotion`。
439
+ */
440
+ const acMotion = {
441
+ duration: {
442
+ /** 按下反馈 */
443
+ instant: 90,
444
+ /** 悬停、指示灯、图标 */
445
+ fast: 160,
446
+ /** 显示屏、数字切换、提示 */
447
+ base: 240,
448
+ /** 导风板、出风淡入淡出 */
449
+ slow: 420,
450
+ /** 出风气流单次循环 */
451
+ flow: 1800
452
+ },
453
+ easing: {
454
+ /** 常规状态切换 */
455
+ standard: "cubic-bezier(0.2, 0, 0, 1)",
456
+ /** 进入:快起慢停 */
457
+ enter: "cubic-bezier(0, 0, 0, 1)",
458
+ /** 退出:慢起快走 */
459
+ exit: "cubic-bezier(0.3, 0, 1, 1)",
460
+ /** 轻微回弹(按钮松开、图标弹出) */
461
+ spring: "cubic-bezier(0.34, 1.56, 0.64, 1)"
462
+ }
463
+ };
464
+ /**
465
+ * `prefers-reduced-motion: reduce` 时使用的时长:
466
+ * 保留短促的淡入淡出(不涉及位移),去掉较长的过渡;循环动画由各样式表自行关闭。
467
+ */
468
+ const acReducedMotionDuration = {
469
+ instant: 0,
470
+ fast: 80,
471
+ base: 120,
472
+ slow: 120,
473
+ flow: 0
474
+ };
475
+ const acReducedMotionQuery = "(prefers-reduced-motion: reduce)";
476
+ /**
477
+ * 当前环境是否要求减少动效(SSR / 无 matchMedia 时返回 `false`)。
478
+ */
479
+ function prefersReducedMotion() {
480
+ return typeof globalThis.matchMedia === "function" && globalThis.matchMedia("(prefers-reduced-motion: reduce)").matches;
481
+ }
482
+ function declarations(durations, withEasing, indent) {
483
+ const lines = Object.keys(durations).map((key) => `${indent}--acw-motion-duration-${key}: ${durations[key]}ms;`);
484
+ if (withEasing) for (const key of Object.keys(acMotion.easing)) lines.push(`${indent}--acw-motion-ease-${key}: ${acMotion.easing[key]};`);
485
+ return lines.join("\n");
486
+ }
487
+ /**
488
+ * 生成动效 CSS 变量声明(含 reduced-motion 覆盖),供 Shadow DOM 注入或样式表同步使用。
489
+ *
490
+ * @param selector 变量挂载的选择器,如 `:root`、`:host`
491
+ */
492
+ function renderAcMotionCssVars(selector = ":root") {
493
+ return [
494
+ `${selector} {`,
495
+ declarations(acMotion.duration, true, " "),
496
+ "}",
497
+ "",
498
+ `@media ${acReducedMotionQuery} {`,
499
+ ` ${selector} {`,
500
+ declarations(acReducedMotionDuration, false, " "),
501
+ " }",
502
+ "}"
503
+ ].join("\n");
504
+ }
505
+ //#endregion
506
+ //#region src/layout.ts
507
+ /**
508
+ * 机身的设计尺寸(px),约 3:1,接近真实壁挂机(如 800–900mm × 280–300mm)的比例。
509
+ * 窄容器下按比例整体缩放,保持「长款」外观不被压扁。
510
+ *
511
+ * - `compact`:Vue / React 组件库 / Web Component 使用的 360 × 128 机身
512
+ * - `wide`:React 主站使用的 600 × 200 机身
513
+ */
514
+ const acShellSize = {
515
+ compact: {
516
+ width: 360,
517
+ height: 128
518
+ },
519
+ wide: {
520
+ width: 600,
521
+ height: 200
522
+ }
523
+ };
524
+ /**
525
+ * 根据可用宽度计算机身缩放比例:只缩小、不放大。
526
+ */
527
+ function getAcScale(availableWidth, designWidth) {
528
+ if (!(availableWidth > 0) || !(designWidth > 0)) return 1;
529
+ return Math.min(1, availableWidth / designWidth);
530
+ }
531
+ /**
532
+ * 监听容器宽度变化并回调缩放比例。
533
+ *
534
+ * 不支持 `ResizeObserver` 的环境(如 SSR)直接返回空的清理函数,保持 1 倍显示。
535
+ *
536
+ * @param target 被测量宽度的容器(不要传被缩放的元素本身)
537
+ * @param designWidth 机身的设计宽度
538
+ * @param onScale 比例变化时的回调
539
+ * @returns 停止监听的清理函数
540
+ */
541
+ function observeAcScale(target, designWidth, onScale) {
542
+ if (typeof ResizeObserver === "undefined") return () => {};
543
+ let current;
544
+ const update = (width) => {
545
+ const scale = getAcScale(width, designWidth);
546
+ if (scale !== current) {
547
+ current = scale;
548
+ onScale(scale);
102
549
  }
103
550
  };
551
+ update(target.getBoundingClientRect().width);
552
+ const observer = new ResizeObserver((entries) => {
553
+ for (const entry of entries) update(entry.contentRect.width);
554
+ });
555
+ observer.observe(target);
556
+ return () => observer.disconnect();
557
+ }
558
+ /** 指针跟随倾斜的最大角度(deg) */
559
+ const acMaxTilt = 4;
560
+ const finePointerQuery = "(hover: hover) and (pointer: fine)";
561
+ /**
562
+ * 指针在元素上移动时回调轻微的 3D 倾斜角度(`rotateX` / `rotateY`,单位 deg),离开时回到 0。
563
+ *
564
+ * 仅在有悬停能力的精细指针(鼠标 / 触控板)上启用;`prefers-reduced-motion: reduce`、
565
+ * 触屏或 SSR 下直接返回空的清理函数。
566
+ *
567
+ * @returns 停止监听的清理函数
568
+ */
569
+ function observeAcTilt(target, onTilt, maxTilt = 4) {
570
+ const matchMedia = globalThis.matchMedia;
571
+ if (typeof matchMedia !== "function" || !matchMedia(finePointerQuery).matches || matchMedia("(prefers-reduced-motion: reduce)").matches) return () => {};
572
+ let frame = 0;
573
+ const schedule = (rotateX, rotateY) => {
574
+ cancelAnimationFrame(frame);
575
+ frame = requestAnimationFrame(() => onTilt(rotateX, rotateY));
576
+ };
577
+ const onMove = (event) => {
578
+ const rect = target.getBoundingClientRect();
579
+ if (!rect.width || !rect.height) return;
580
+ const x = (event.clientX - rect.left) / rect.width - .5;
581
+ const y = (event.clientY - rect.top) / rect.height - .5;
582
+ const round = (value) => Math.round(value * 100) / 100;
583
+ schedule(round(-y * 2 * maxTilt), round(x * 2 * maxTilt));
584
+ };
585
+ const onLeave = () => schedule(0, 0);
586
+ target.addEventListener("pointermove", onMove);
587
+ target.addEventListener("pointerleave", onLeave);
588
+ return () => {
589
+ cancelAnimationFrame(frame);
590
+ target.removeEventListener("pointermove", onMove);
591
+ target.removeEventListener("pointerleave", onLeave);
592
+ };
104
593
  }
105
594
  //#endregion
106
595
  //#region src/reducer.ts
107
- function normalizeAcState(state) {
596
+ /**
597
+ * Merge a partial state over the defaults and clamp its temperature.
598
+ *
599
+ * @param state - Partial or stored state
600
+ * @param limits - Device limits; omit to keep the default 16–31 °C range
601
+ */
602
+ function normalizeAcState(state, limits) {
108
603
  return {
109
604
  ...defaultAcState,
110
605
  ...state,
111
- temperature: clampTemperature(state?.temperature ?? defaultAcState.temperature)
606
+ temperature: clampTemperature(state?.temperature ?? defaultAcState.temperature, limits),
607
+ sound: isAcSoundMode(state?.sound) ? state.sound : defaultAcState.sound
112
608
  };
113
609
  }
114
- function clampTemperature(temperature) {
115
- return Math.min(31, Math.max(16, temperature));
610
+ /**
611
+ * Clamp a temperature into range. When `limits` are given the value also
612
+ * snaps to the device step, measured from `limits.min`.
613
+ *
614
+ * @param temperature - Requested temperature in Celsius
615
+ * @param limits - Device limits; omit to clamp to 16–31 °C without snapping
616
+ */
617
+ function clampTemperature(temperature, limits) {
618
+ if (!limits) return Math.min(31, Math.max(16, temperature));
619
+ const { min, max, step } = limits;
620
+ const snapped = step > 0 ? Math.round((temperature - min) / step) * step + min : temperature;
621
+ return Number(Math.min(max, Math.max(min, snapped)).toFixed(4));
116
622
  }
117
- function acReducer(state, action) {
623
+ /**
624
+ * Apply an action to the state.
625
+ *
626
+ * @param state - Current state
627
+ * @param action - Action to apply
628
+ * @param limits - Device limits; increments use `limits.step`
629
+ */
630
+ function acReducer(state, action, limits) {
631
+ const step = limits?.step ?? defaultAcLimits.step;
118
632
  switch (action.type) {
119
633
  case "increment": return {
120
634
  ...state,
121
- temperature: clampTemperature(state.temperature + 1)
635
+ temperature: clampTemperature(state.temperature + step, limits)
122
636
  };
123
637
  case "decrement": return {
124
638
  ...state,
125
- temperature: clampTemperature(state.temperature - 1)
639
+ temperature: clampTemperature(state.temperature - step, limits)
126
640
  };
127
641
  case "toggleStatus": return {
128
642
  ...state,
@@ -136,25 +650,53 @@ function acReducer(state, action) {
136
650
  ...state,
137
651
  mode: action.mode
138
652
  };
653
+ case "sound": return {
654
+ ...state,
655
+ sound: isAcSoundMode(action.sound) ? action.sound : state.sound
656
+ };
657
+ case "cycleSound": return {
658
+ ...state,
659
+ sound: nextAcSoundMode(state.sound)
660
+ };
139
661
  case "update": return normalizeAcState({
140
662
  ...state,
141
663
  ...action.payload
142
- });
664
+ }, limits);
143
665
  default: throw new Error("Unexpected Ac Action");
144
666
  }
145
667
  }
146
668
  function getRecommendedTemperatureMessage(mode, temperature) {
147
669
  return `建议将空调的制${mode === "cold" ? "冷" : "热"}温度调至 ${temperature} 度以${mode === "cold" ? "上" : "下"},为节能减排贡献一份力量!`;
148
670
  }
149
- function getAcActionNotification(previousState, nextState, action) {
150
- if (action.type === "increment" && previousState.temperature >= 31) return {
671
+ function getSoundModeMessage(sound) {
672
+ return `${acSoundModeLabels[sound]}模式:${{
673
+ normal: "风声和按键音恢复正常",
674
+ sleep: "风声和按键音都调小了,晚安",
675
+ mute: "空调不再发出任何声音"
676
+ }[sound]}`;
677
+ }
678
+ /**
679
+ * Visual tone for a state: `idle` when off, otherwise `cool` or `heat`.
680
+ *
681
+ * @param state - Current state
682
+ */
683
+ function acTone(state) {
684
+ if (!state.status) return "idle";
685
+ return state.mode === "hot" ? "heat" : "cool";
686
+ }
687
+ function getAcActionNotification(previousState, nextState, action, limits = defaultAcLimits) {
688
+ if (action.type === "increment" && previousState.temperature >= limits.max) return {
151
689
  message: "已经是最大温度啦!",
152
690
  severity: "error"
153
691
  };
154
- if (action.type === "decrement" && previousState.temperature <= 16) return {
692
+ if (action.type === "decrement" && previousState.temperature <= limits.min) return {
155
693
  message: "已经是最小温度啦!",
156
694
  severity: "error"
157
695
  };
696
+ if ((action.type === "sound" || action.type === "cycleSound") && nextState.sound !== previousState.sound) return {
697
+ message: getSoundModeMessage(nextState.sound),
698
+ severity: "info"
699
+ };
158
700
  if (action.type === "mode" && nextState.mode === "cold" && previousState.temperature < 26) return {
159
701
  message: getRecommendedTemperatureMessage("cold", 26),
160
702
  severity: "success"
@@ -210,11 +752,12 @@ function createAirConditionerStore(options = {}) {
210
752
  const storageKey = options.storageKey ?? "ac:state";
211
753
  const storage = options.storage === void 0 ? getBrowserStorage() : options.storage;
212
754
  const persistedState = readAcState(storage, storageKey);
755
+ const limits = options.limits;
213
756
  let state = normalizeAcState({
214
757
  ...defaultAcState,
215
758
  ...persistedState,
216
759
  ...options.initialState
217
- });
760
+ }, limits);
218
761
  const listeners = /* @__PURE__ */ new Set();
219
762
  return {
220
763
  getState() {
@@ -222,8 +765,8 @@ function createAirConditionerStore(options = {}) {
222
765
  },
223
766
  dispatch(action) {
224
767
  const previousState = state;
225
- const nextState = acReducer(state, action);
226
- const notification = getAcActionNotification(previousState, nextState, action);
768
+ const nextState = acReducer(state, action, limits);
769
+ const notification = getAcActionNotification(previousState, nextState, action, limits);
227
770
  const event = {
228
771
  action,
229
772
  previousState,
@@ -245,4 +788,231 @@ function createAirConditionerStore(options = {}) {
245
788
  };
246
789
  }
247
790
  //#endregion
248
- export { acAudioFileNames, acModeIcons, acReducer, acStorageKey, clampTemperature, createAcAudioController, createAirConditionerStore, createMemoryStorage, defaultAcState, getAcActionNotification, getBrowserStorage, getRecommendedTemperatureMessage, maxTemperature, minTemperature, normalizeAcState, readAcState, recommendedColdTemperature, recommendedHotTemperature, resolveAcAudioAssets, soundTimings, writeAcState };
791
+ //#region src/thermal/levels.ts
792
+ const heatLevels = [
793
+ "nominal",
794
+ "fair",
795
+ "serious",
796
+ "critical"
797
+ ];
798
+ /** Default Celsius thresholds for fair, serious and critical. */
799
+ const defaultHeatThresholds = [
800
+ 60,
801
+ 75,
802
+ 90
803
+ ];
804
+ /**
805
+ * @param level - A heat level
806
+ * @returns Its rank from 0 (nominal) to 3 (critical)
807
+ */
808
+ function heatLevelRank(level) {
809
+ return heatLevels.indexOf(level);
810
+ }
811
+ function isHeatLevel(value) {
812
+ return heatLevels.includes(value);
813
+ }
814
+ /**
815
+ * Convert a temperature to a heat level. With a previous level, the value
816
+ * must fall `hysteresis` degrees below a threshold before dropping a level,
817
+ * which keeps readings near a threshold from flickering.
818
+ *
819
+ * @param celsius - Measured temperature
820
+ * @param thresholds - Lower bounds for fair, serious and critical
821
+ * @param previous - Level from the previous reading
822
+ * @param hysteresis - Degrees required below a threshold to step down
823
+ */
824
+ function celsiusToHeatLevel(celsius, thresholds = defaultHeatThresholds, previous, hysteresis = 5) {
825
+ const raw = thresholds.filter((threshold) => celsius >= threshold).length;
826
+ if (previous === void 0) return heatLevels[raw];
827
+ const held = thresholds.filter((threshold) => celsius >= threshold - hysteresis).length;
828
+ return heatLevels[Math.max(raw, Math.min(heatLevelRank(previous), held))];
829
+ }
830
+ /**
831
+ * Create a filter that raises the level immediately but only lowers it after
832
+ * lower readings persist for `dwellMs`, measured with `reading.at`.
833
+ *
834
+ * @param options - Governor options
835
+ * @param options.dwellMs - Time a lower level must persist; defaults to 30 seconds
836
+ * @returns A function that maps each reading to the settled level
837
+ */
838
+ function createHeatGovernor(options = {}) {
839
+ const dwellMs = options.dwellMs ?? 3e4;
840
+ let current;
841
+ let lowerSince;
842
+ return (reading) => {
843
+ if (current === void 0 || heatLevelRank(reading.level) >= heatLevelRank(current)) {
844
+ current = reading.level;
845
+ lowerSince = void 0;
846
+ return current;
847
+ }
848
+ lowerSince ??= reading.at;
849
+ if (reading.at - lowerSince >= dwellMs) {
850
+ current = reading.level;
851
+ lowerSince = void 0;
852
+ }
853
+ return current;
854
+ };
855
+ }
856
+ //#endregion
857
+ //#region src/thermal/plan.ts
858
+ const coolingByLevel = {
859
+ fair: {
860
+ temperature: 26,
861
+ airflow: .4
862
+ },
863
+ serious: {
864
+ temperature: 24,
865
+ airflow: .7
866
+ },
867
+ critical: {
868
+ temperature: 22,
869
+ airflow: 1
870
+ }
871
+ };
872
+ /**
873
+ * Decide how the virtual air conditioner should respond to a heat level.
874
+ *
875
+ * @param level - Settled heat level
876
+ * @param limits - Device limits used to clamp the target temperature
877
+ * @returns A cooling plan, or `null` at `nominal` so the user keeps control
878
+ */
879
+ function planCooling(level, limits) {
880
+ if (level === "nominal") return null;
881
+ const { temperature, airflow } = coolingByLevel[level];
882
+ return {
883
+ status: true,
884
+ mode: "cold",
885
+ temperature: clampTemperature(temperature, limits),
886
+ airflow
887
+ };
888
+ }
889
+ //#endregion
890
+ //#region src/thermal/pressure.ts
891
+ function getPressureObserver() {
892
+ return globalThis.PressureObserver;
893
+ }
894
+ /**
895
+ * Heat source backed by the browser Compute Pressure API. It reports CPU
896
+ * load levels, not temperatures; browsers expose no CPU temperature.
897
+ *
898
+ * Supported in Chromium-based browsers on secure origins. The API is only
899
+ * touched when the source is started.
900
+ *
901
+ * @param options - Sampling and error handling options
902
+ */
903
+ function createComputePressureSource(options = {}) {
904
+ return {
905
+ id: "compute-pressure",
906
+ isSupported: () => typeof getPressureObserver() === "function",
907
+ start(listener) {
908
+ const Observer = getPressureObserver();
909
+ if (!Observer) return () => {};
910
+ let stopped = false;
911
+ const observer = new Observer((records) => {
912
+ const record = records.at(-1);
913
+ if (stopped || !record || !isHeatLevel(record.state)) return;
914
+ listener({
915
+ level: record.state,
916
+ source: "compute-pressure",
917
+ at: Date.now()
918
+ });
919
+ });
920
+ observer.observe("cpu", { sampleInterval: options.sampleIntervalMs ?? 2e3 }).catch((error) => {
921
+ if (!stopped) options.onError?.(error);
922
+ });
923
+ return () => {
924
+ stopped = true;
925
+ observer.disconnect();
926
+ };
927
+ }
928
+ };
929
+ }
930
+ //#endregion
931
+ //#region src/ui.ts
932
+ /**
933
+ * 各框架视图层共用的界面数据:遥控器图标与能效标签的点阵布局。
934
+ * 保证 Vue / React / Web Component 渲染出完全一致的空调外观。
935
+ */
936
+ /**
937
+ * 遥控器按钮图标(24 × 24 viewBox 的 SVG path)。
938
+ */
939
+ const acIconPaths = {
940
+ cold: "m22 11h-4.17l3.24-3.24l-1.41-1.42L15 11h-2V9l4.66-4.66l-1.42-1.41L13 6.17V2h-2v4.17L7.76 2.93L6.34 4.34L11 9v2H9L4.34 6.34L2.93 7.76L6.17 11H2v2h4.17l-3.24 3.24l1.41 1.42L9 13h2v2l-4.66 4.66l1.42 1.41L11 17.83V22h2v-4.17l3.24 3.24l1.42-1.41L13 15v-2h2l4.66 4.66l1.41-1.42L17.83 13H22z",
941
+ power: "M13 3h-2v10h2zm4.83 2.17l-1.42 1.42A6.92 6.92 0 0 1 19 12a7 7 0 0 1-14 0a6.92 6.92 0 0 1 2.58-5.42L6.17 5.17A9 9 0 1 0 21 12a8.94 8.94 0 0 0-3.17-6.83",
942
+ hot: "M12 7a5 5 0 1 0 5 5a5 5 0 0 0-5-5m0-5a1 1 0 0 0-1 1v2a1 1 0 0 0 2 0V3a1 1 0 0 0-1-1m0 17a1 1 0 0 0-1 1v2a1 1 0 0 0 2 0v-2a1 1 0 0 0-1-1M5.64 6.05L4.22 4.64a1 1 0 0 0-1.41 1.41l1.41 1.42a1 1 0 0 0 1.42 0a1 1 0 0 0 0-1.42M21 11h-2a1 1 0 0 0 0 2h2a1 1 0 0 0 0-2M5 12a1 1 0 0 0-1-1H2a1 1 0 0 0 0 2h2a1 1 0 0 0 1-1m13.36-5.95a1 1 0 0 0 .7-.29l1.42-1.42a1 1 0 1 0-1.41-1.41l-1.42 1.41a1 1 0 0 0 0 1.42a1 1 0 0 0 .71.29m0 11.9a1 1 0 0 0-1.42 1.41l1.42 1.42a1 1 0 0 0 1.41 0a1 1 0 0 0 0-1.41ZM5.64 17.95l-1.42 1.42a1 1 0 0 0 0 1.41a1 1 0 0 0 1.41 0l1.42-1.42a1 1 0 0 0-1.41-1.41",
943
+ increase: "m12 8l6 8H6z",
944
+ decrease: "m12 16l-6-8h12z",
945
+ soundNormal: "M3 10v4c0 .55.45 1 1 1h3l3.29 3.29c.63.63 1.71.18 1.71-.71V6.41c0-.89-1.08-1.34-1.71-.71L7 9H4c-.55 0-1 .45-1 1m13.5 2A4.5 4.5 0 0 0 14 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02M14 4.45v.2c0 .38.25.71.6.85C17.18 6.53 19 9.06 19 12s-1.82 5.47-4.4 6.5c-.36.14-.6.47-.6.85v.2c0 .63.63 1.07 1.21.85C18.6 19.11 21 15.84 21 12s-2.4-7.11-5.79-8.4c-.58-.23-1.21.22-1.21.85",
946
+ soundSleep: "M11.65 3.46c.27-.71-.36-1.45-1.12-1.34c-5.52.8-9.47 6.07-8.34 11.88c.78 4.02 4.09 7.21 8.14 7.87c3.74.61 7.16-.87 9.32-3.44c.48-.57.19-1.48-.55-1.62c-6.02-1.15-9.68-7.54-7.45-13.35",
947
+ soundMute: "M3.63 3.63a.996.996 0 0 0 0 1.41L7.29 8.7L7 9H4c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h3l3.29 3.29c.63.63 1.71.18 1.71-.71v-4.17l4.18 4.18c-.49.37-1.02.68-1.6.91c-.36.15-.58.53-.58.92c0 .72.73 1.18 1.39.91c.8-.33 1.55-.77 2.22-1.31l1.34 1.34a.996.996 0 1 0 1.41-1.41L5.05 3.63c-.39-.39-1.02-.39-1.42 0M19 12c0 .82-.15 1.61-.41 2.34l1.53 1.53c.56-1.17.88-2.48.88-3.87c0-3.83-2.4-7.11-5.78-8.4c-.59-.23-1.22.23-1.22.86v.19c0 .38.25.71.61.85C17.18 6.54 19 9.06 19 12m-8.71-6.29l-.17.17L12 7.76V6.41c0-.89-1.08-1.33-1.71-.7M16.5 12A4.5 4.5 0 0 0 14 7.97v1.79l2.48 2.48c.01-.08.02-.16.02-.24"
948
+ };
949
+ /**
950
+ * 声音键在各声音模式下显示的图标。
951
+ */
952
+ const acSoundIcons = {
953
+ normal: "soundNormal",
954
+ sleep: "soundSleep",
955
+ mute: "soundMute"
956
+ };
957
+ /**
958
+ * 能效标签的点阵与等级条布局。
959
+ */
960
+ const acEnergyLabel = {
961
+ top: [{
962
+ num: 6,
963
+ size: 4,
964
+ mx: 2,
965
+ my: 0,
966
+ color: "white"
967
+ }],
968
+ detail: [
969
+ {
970
+ num: 11,
971
+ size: 2,
972
+ mx: .8,
973
+ my: 2,
974
+ color: "black"
975
+ },
976
+ {
977
+ num: 9,
978
+ size: 1.5,
979
+ mx: .8,
980
+ my: 2,
981
+ color: "black"
982
+ },
983
+ {
984
+ num: 10,
985
+ size: 1.2,
986
+ mx: .8,
987
+ my: 0,
988
+ color: "black"
989
+ }
990
+ ],
991
+ footer: {
992
+ num: 8,
993
+ size: 2,
994
+ mx: .8,
995
+ my: 0,
996
+ color: "white"
997
+ },
998
+ levels: [
999
+ {
1000
+ background: "lightgreen",
1001
+ width: "50%"
1002
+ },
1003
+ {
1004
+ background: "#ffc107",
1005
+ width: "60%"
1006
+ },
1007
+ {
1008
+ background: "orange",
1009
+ width: "70%"
1010
+ },
1011
+ {
1012
+ background: "red",
1013
+ width: "80%"
1014
+ }
1015
+ ]
1016
+ };
1017
+ //#endregion
1018
+ export { acAudioFileNames, acEnergyLabel, acIconPaths, acMaxTilt, acModeIcons, acMotion, acReducedMotionDuration, acReducedMotionQuery, acReducer, acShellSize, acSoundIcons, acSoundModeLabels, acSoundModes, acSoundVolumes, acStorageKey, acTone, celsiusToHeatLevel, clampTemperature, createAcAudioController, createAirConditionerStore, createComputePressureSource, createHeatGovernor, createMemoryStorage, defaultAcLimits, defaultAcState, defaultHeatThresholds, getAcActionNotification, getAcScale, getBrowserStorage, getRecommendedTemperatureMessage, getSoundModeMessage, heatLevelRank, heatLevels, isAcSoundMode, isHeatLevel, maxTemperature, minTemperature, nextAcSoundMode, normalizeAcState, observeAcScale, observeAcTilt, planCooling, prefersReducedMotion, readAcState, recommendedColdTemperature, recommendedHotTemperature, renderAcMotionCssVars, resolveAcAudioAssets, soundTimings, writeAcState };