Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(web): 界面音效:按钮、开关、菜单、弹层与状态通知各配一声轻响,设置里可关

longmeidao996d6618914a
diff --git a/README.en.md b/README.en.md
index a2a051644..ff3356f39 100644
--- a/README.en.md
+++ b/README.en.md
@@ -39,7 +39,7 @@ Local disks alone work. 115 and PikPak arrive as folders mounted by CloudDrive:
Follow sources include FANBOX, Patreon, SubscribeStar, Kemono, Pawchive, Coomer, the Rule34 family, F95zone and SimpCity (needs your own login cookie). Availability depends on the site and your access rights. See [source collection](docs/SOURCING.md) for supported workflows and boundaries.
-Interface preferences are saved in the current browser and live under Settings: default sort, official covers or preview images for JAV works, autoplay when details open, and SFW mode, which blurs, desaturates and dims images and video and stops hover previews.
+Interface preferences are saved in the current browser and live under Settings: default sort, official covers or preview images for JAV works, autoplay when details open, UI sounds (a soft cue for buttons, switches and action receipts), and SFW mode, which blurs, desaturates and dims images and video and stops hover previews.
“Video thumbnail capture”, in the same place, belongs to the computer running Peach rather than to each browser: pick precise (a frame every 10 seconds) or coarse (every 30 seconds) and it captures frames in the background, so dragging the progress bar shows the picture at that point in time. It is off by default and only covers videos on local disks; every frame from a mounted cloud drive costs one fetch from the source. The images are cleaned up together with the video on the data management page.
diff --git a/README.md b/README.md
index 24c2b51e0..fcc8a36d9 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ Peach 是单用户、本地优先的个人媒体系统。在自己的电脑上
关注来源包括 FANBOX、Patreon、SubscribeStar,以及 Kemono、Pawchive、Coomer、Rule34 系列、F95zone 与 SimpCity(需要你自己的登录 cookie)。来源可用性受站点和使用者权限限制;采集边界与支持情况见 [来源采集](docs/SOURCING.md)。
-界面偏好保存在当前浏览器,在右上角「设置」里改:默认排序、JAV 封面用官方封面还是预览图、打开详情是否自动播放,以及把图像模糊降饱和、关掉悬停预览的「SFW 模式」。
+界面偏好保存在当前浏览器,在右上角「设置」里改:默认排序、JAV 封面用官方封面还是预览图、打开详情是否自动播放、按钮开关和操作回执要不要配一声轻响的「界面音效」,以及把图像模糊降饱和、关掉悬停预览的「SFW 模式」。
同一处的「视频缩略图采集」跟着运行 Peach 的这台电脑走,不是每个浏览器各存一份:选精准(每 10 秒一帧)或粗略(每 30 秒一帧)后它在后台按密度抽帧,拖动进度条时按时间点显示画面。默认关闭,只采集本机磁盘上的片子;网盘上的每抽一帧都要回源拉一次。产物随片子一起在数据管理页清理。
diff --git a/frontend/test/ui-sounds.test.ts b/frontend/test/ui-sounds.test.ts
new file mode 100644
index 000000000..671e9e413
--- /dev/null
+++ b/frontend/test/ui-sounds.test.ts
@@ -0,0 +1,179 @@
+/* 界面音效模块的行为:开关、配方的安全边界、document 上的两路监听。
+ * happy-dom 没有 Web Audio,这里搭一个只记录调度的假 AudioContext。模块里的
+ * AudioContext 是单例,整份文件从头到尾只该建出这一个,所以用例按顺序共用它。 */
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+// @ts-expect-error 遗留模块由浏览器直接加载,此测试调用实际实现。
+import { UI_SOUNDS, playUiSound, setUiSoundsEnabled, uiSoundsEnabled, wireUiSounds } from '../../web/js/ui-sounds.js';
+
+interface Ramp { value: number; at: number }
+interface Param {
+ sets: Ramp[];
+ ramps: Ramp[];
+ value: number;
+ setValueAtTime(value: number, at: number): void;
+ exponentialRampToValueAtTime(value: number, at: number): void;
+}
+interface Node {
+ kind: string;
+ params: Record<string, Param>;
+ connected: unknown[];
+ started?: number;
+ stopped?: number;
+ onended?: () => void;
+ connect(target: unknown): void;
+ disconnect(): void;
+ start(at: number): void;
+ stop(at: number): void;
+}
+
+function param(): Param {
+ const created: Param = {
+ sets: [], ramps: [], value: 0,
+ setValueAtTime(value, at) { created.sets.push({ value, at }); },
+ exponentialRampToValueAtTime(value, at) {
+ if (value <= 0) throw new RangeError('指数斜坡不能落到 0');
+ created.ramps.push({ value, at });
+ },
+ };
+ return created;
+}
+
+class FakeContext {
+ static created = 0;
+ static current: FakeContext | null = null;
+ state = 'suspended';
+ currentTime = 10;
+ sampleRate = 48000;
+ destination = { kind: 'destination' };
+ nodes: Node[] = [];
+ constructor() { FakeContext.created += 1; FakeContext.current = this; }
+ resume() { this.state = 'running'; return Promise.resolve(); }
+ createOscillator() { return this.node('oscillator', ['frequency'], { type: 'sine' }); }
+ createGain() { return this.node('gain', ['gain']); }
+ createBiquadFilter() { return this.node('filter', ['frequency', 'Q'], { type: 'lowpass' }); }
+ createBuffer(channels: number, length: number, rate: number) {
+ const data = new Float32Array(length);
+ return { channels, length, rate, getChannelData: () => data };
+ }
+ createBufferSource() { return this.node('source', []); }
+ private node(kind: string, names: string[], extra: Record<string, unknown> = {}) {
+ const created: Node & Record<string, unknown> = {
+ kind, params: {}, connected: [], ...extra,
+ connect(target) { created.connected.push(target); },
+ disconnect() { created.connected.length = 0; },
+ start(at) { created.started = at; },
+ stop(at) { created.stopped = at; },
+ };
+ for (const name of names) {
+ const value = param();
+ created.params[name] = value;
+ created[name] = value;
+ }
+ this.nodes.push(created);
+ return created;
+ }
+}
+
+(globalThis as Record<string, unknown>).AudioContext = FakeContext;
+const nodes = () => FakeContext.current!.nodes;
+const kind = (name: string) => nodes().filter((node) => node.kind === name);
+
+beforeEach(() => { FakeContext.current?.nodes.splice(0); });
+afterEach(() => {
+ setUiSoundsEnabled(false);
+ document.body.replaceChildren();
+});
+
+describe('开关', () => {
+ it('关着时不出声也不建 AudioContext', () => {
+ setUiSoundsEnabled(false);
+ expect(uiSoundsEnabled()).toBe(false);
+ expect(playUiSound('click')).toBe(false);
+ expect(FakeContext.created).toBe(0);
+ });
+ it('不认识的名字直接抛,别把拼错的音效名当成静音', () => {
+ expect(() => playUiSound('ding')).toThrow('ding');
+ });
+});
+
+describe('配方', () => {
+ it('全部音效共用一个 AudioContext,音量不越过 0.8,尾音都收在 0.001', () => {
+ setUiSoundsEnabled(true);
+ expect(UI_SOUNDS).toEqual(['click', 'toggle-on', 'toggle-off', 'success', 'warning', 'error', 'whoosh', 'pop']);
+ for (const name of UI_SOUNDS) expect(playUiSound(name)).toBe(true);
+ expect(FakeContext.created).toBe(1);
+ const gains = kind('gain');
+ expect(gains.length).toBeGreaterThanOrEqual(UI_SOUNDS.length);
+ for (const gain of gains) {
+ const level = gain.params.gain!;
+ const peak = Math.max(...level.sets.map((set) => set.value), ...level.ramps.map((ramp) => ramp.value));
+ expect(peak).toBeLessThanOrEqual(0.8);
+ expect(level.ramps.at(-1)!.value).toBe(0.001);
+ }
+ for (const osc of kind('oscillator')) expect(osc.stopped!).toBeGreaterThan(osc.started!);
+ });
+ it('开关音的方向就是状态:开升、关降', () => {
+ setUiSoundsEnabled(true);
+ playUiSound('toggle-on');
+ const rising = kind('oscillator')[0]!.params.frequency!;
+ expect(rising.ramps[0]!.value).toBeGreaterThan(rising.sets[0]!.value);
+ nodes().splice(0);
+ playUiSound('toggle-off');
+ const falling = kind('oscillator')[0]!.params.frequency!;
+ expect(falling.ramps[0]!.value).toBeLessThan(falling.sets[0]!.value);
+ });
+ it('噪声源放完把整条链拆掉', () => {
+ setUiSoundsEnabled(true);
+ playUiSound('click');
+ const source = kind('source')[0]!;
+ expect(source.connected).toHaveLength(1);
+ source.onended!();
+ expect(nodes().every((node) => node.connected.length === 0)).toBe(true);
+ });
+});
+
+describe('document 监听', () => {
+ it('按钮点一下响一声,禁用的不响,开关走 change 而不是 click', () => {
+ setUiSoundsEnabled(true);
+ const root = document.createElement('div');
+ document.body.append(root);
+ wireUiSounds(root);
+ const button = document.createElement('button');
+ const disabled = document.createElement('button');
+ disabled.disabled = true;
+ const busy = document.createElement('button');
+ busy.setAttribute('aria-disabled', 'true');
+ const label = document.createElement('label');
+ const toggle = document.createElement('input');
+ toggle.type = 'checkbox';
+ toggle.setAttribute('role', 'switch');
+ label.append(toggle);
+ root.append(button, disabled, busy, label);
+
+ button.click();
+ expect(kind('source')).toHaveLength(1);
+ nodes().splice(0);
+ disabled.click();
+ busy.click();
+ expect(nodes()).toHaveLength(0);
+
+ toggle.click();
+ expect(kind('source')).toHaveLength(0);
+ const oscillators = kind('oscillator');
+ expect(oscillators).toHaveLength(1);
+ const sweep = oscillators[0]!.params.frequency!;
+ expect(sweep.ramps[0]!.value).toBeGreaterThan(sweep.sets[0]!.value);
+ });
+ it('页面在自己那层 stopPropagation 也拦不住这一声', () => {
+ setUiSoundsEnabled(true);
+ const root = document.createElement('div');
+ document.body.append(root);
+ wireUiSounds(root);
+ const button = document.createElement('button');
+ button.addEventListener('click', (event) => event.stopPropagation());
+ root.append(button);
+ button.click();
+ expect(kind('source')).toHaveLength(1);
+ expect(FakeContext.created).toBe(1);
+ });
+});
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index bd1bb61ae..3288dc72e 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -1671,6 +1671,42 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("panel.classList.add('closing')")
self.assertPageContains("prefers-reduced-motion: reduce")
+ def test_ui_sounds_are_one_synthesised_module_behind_one_switch(self):
+ """界面音效只有一个来源、一个开关,关着时连 AudioContext 都不建。
+
+ 声音由 `web/js/ui-sounds.js` 用 Web Audio 当场合成,别处不许再建第二个
+ AudioContext:浏览器限制同时打开的路数,两份实现也会各带一套音量口径。
+ 开关在设置「界面」组,偏好存在 `appSettings.uiSounds`,默认开;页面进来先把
+ 它灌进模块再挂 document 监听,顺序反了首屏那几下点击就按默认的「关」处理。
+ 配方里 `exponentialRampToValueAtTime` 落到 0 会直接抛错,收尾一律 0.001。
+ """
+ web = Path(__file__).resolve().parents[1] / "web"
+ sounds = (web / "js" / "ui-sounds.js").read_text(encoding="utf-8")
+ for path in [web / "index.html", web / "app.js", *sorted((web / "js").glob("*.js"))]:
+ if path.name == "ui-sounds.js":
+ continue
+ self.assertNotIn("AudioContext", path.read_text(encoding="utf-8"),
+ f"{path.name} 不该自己建 AudioContext,声音都从 ui-sounds.js 发")
+ self.assertIn("if(!audioContext)audioContext=new Context();", sounds)
+ self.assertIn("if(!enabled)return false;", sounds)
+ self.assertNotRegex(sounds, r"exponentialRampToValueAtTime\(\s*0\s*,",
+ "指数斜坡不能落到 0")
+ self.assertPageContains('class="ptoggle" type="checkbox" id="uiSoundsSetting" role="switch" aria-describedby="uiSoundsDescription"')
+ self.assertPageContains('<b>界面音效</b><small id="uiSoundsDescription">')
+ self.assertPageContains("appSettings.uiSounds=appSettings.uiSounds!==false;")
+ self.assertCode("setUiSoundsEnabled(appSettings.uiSounds);\nwireUiSounds();")
+ self.assertPageContains("$('#uiSoundsSetting').checked=appSettings.uiSounds;")
+ self.assertPageContains("$('#uiSoundsSetting').onchange=")
+ self.assertPageContains("if(appSettings.uiSounds)playUiSound('toggle-on');")
+ # 回执、菜单、弹层、设置面板各在自己的入口响,点击与开关由 document 上的监听统一发。
+ # 表状态的通知三档取音:默认按 warn 分成功与失败,部分来源失败这类提醒是警告。
+ self.assertPageContains("playUiSound(sound||(alert?'error':'success'));")
+ self.assertPageContains("{warn:!!failed,timeout:failed?8000:6000,sound:failed?'warning':'success',")
+ self.assertPageContains("toast({text:'当前筛选下没有可直接播放的内容'},{sound:'warning'})")
+ self.assertPageContains("if(menu.hidden)playUiSound('whoosh');")
+ self.assertEqual(self.page.count("playUiSound('pop');"), 2, "formModal 与 confirmModal 各响一声")
+ self.assertIn("},{capture:true});", sounds)
+
def test_settings_titlebar_owns_the_full_width_above_its_scroll_container(self):
self.assertPageContains(".settingsscroll{flex:1;min-height:0;overflow-y:auto;padding:0 20px 20px")
self.assertPageContains("padding:0 20px 20px;overscroll-behavior:contain}")
@@ -6769,7 +6805,8 @@ class WebUiSourceTests(unittest.TestCase):
self.assertCode("menu.dataset.placement=downward?'bottom':'top';")
self.assertCode("export function dismissMenu(menu,finish){")
self.assertCode("if(getComputedStyle(menu).animationName==='none'){done();return}")
- self.assertCode("export function presentMenu(menu){leavingMenus.delete(menu);menu.classList.remove('leaving');menu.hidden=false}")
+ self.assertCode("export function presentMenu(menu){\n leavingMenus.delete(menu);menu.classList.remove('leaving');\n"
+ " if(menu.hidden)playUiSound('whoosh');\n menu.hidden=false;\n}")
self.assertCode("let open=false;")
self.assertCode("return {setOpen,isOpen:()=>open};")
# 进场起手是 scale(.95),定位量框只能读 offsetWidth。
diff --git a/web/app.js b/web/app.js
index bd535a52d..c7453c8e3 100644
--- a/web/app.js
+++ b/web/app.js
@@ -11,6 +11,7 @@ import { javDisplayName, javTitleHtml } from './js/jav-title.js';
import { matchRoute, routeLabel } from './js/routes.js';
import { initMiddleTruncate } from './js/middle-truncate.js';
import { tagLabel } from './js/tags.js';
+import { playUiSound, setUiSoundsEnabled, wireUiSounds } from './js/ui-sounds.js';
import { DEFAULT_HOME_GLOW, GLOW_SPOT_LABELS, GLOW_SWATCHES, GLOW_SWATCH_FAMILIES, HOME_GLOW_CHOICES, HOME_GLOW_PRESETS, HOME_GLOW_SPOTS, glowChipFill, glowColor, glowPalette, glowPresetName, normalizeHomeGlow, paintHomeGlow } from './js/home-glow.js';
import { mountIsland, unmountIsland, islandMounted, createReviewSelection, wireReviewSelection, updateReviewSticky, groupReviewRows, paginationHtml, pageCount, clampPage, identityEvidenceHtml, reviewImageHtml, wireReviewPictures, preferredDirection } from './dist/peach-ui.js';
import { catalogSuggestions, catalogEmptyHtml, emptyCatalogLayout, syncSidebarSurface, sidebarTagCounts, sidebarHasCatalogContent, cleanupSkeletonHtml, cloudLocations, cloudPreferenceLocations } from './dist/peach-ui.js';
@@ -509,6 +510,7 @@ appSettings.theaterMode=appSettings.theaterMode===true;
appSettings.groupCollapse=appSettings.groupCollapse!==false;
appSettings.detailAutoplay=appSettings.detailAutoplay!==false;
appSettings.miniplayer=appSettings.miniplayer!==false;
+appSettings.uiSounds=appSettings.uiSounds!==false;
appSettings.searchHistoryLimit=boundedPreference(+appSettings.searchHistoryLimit,0,50,10);
appSettings.relatedLimit=boundedPreference(+appSettings.relatedLimit,0,60,20);
const METADATA_REFRESH_DAYS=[0,7,30,90];
@@ -520,6 +522,10 @@ const sidebarKeyAlias=key=>key==='ads'||key==='dupes'?'data-cleanup':key;
appSettings.sidebarOrder=[...new Set((Array.isArray(appSettings.sidebarOrder)?appSettings.sidebarOrder:DEFAULT_SIDEBAR_ORDER).map(sidebarKeyAlias))].filter(key=>ALL_SIDEBAR_KEYS.includes(key));
if(!appSettings.sidebarOrder.length)appSettings.sidebarOrder=[...DEFAULT_SIDEBAR_ORDER];
document.documentElement.style.setProperty('--hover-delay',`${appSettings.hoverDelaySeconds}s`);
+/* 音效跟着偏好走。点击与开关那两声由 document 上的一对监听统一发;回执、菜单和弹层
+ 在各自的入口自己响。 */
+setUiSoundsEnabled(appSettings.uiSounds);
+wireUiSounds();
const saveSettings=()=>localStorage.setItem(SETTINGS_KEY,JSON.stringify(appSettings));
if(sortDefaultsMigrated)saveSettings();
/* 主题只写属性,不写颜色:两套色板都在 web/css/01-base.css,选跟随系统就把属性摘掉,
@@ -757,6 +763,7 @@ function syncSettingsPanel(){
$('#groupCollapseSetting').checked=appSettings.groupCollapse;
$('#detailAutoplaySetting').checked=appSettings.detailAutoplay;
$('#miniplayerSetting').checked=appSettings.miniplayer;
+ $('#uiSoundsSetting').checked=appSettings.uiSounds;
renderSettingSelects();
renderThemeSetting();
renderHomeGlowSetting();
@@ -774,6 +781,7 @@ function openSettings(open=true,section=''){
settingsRequestedSection=section;
settingsTransition++;panel.classList.remove('closing');
settingsReturnFocus=settingsReturnFocus||document.activeElement;panel.hidden=false;
+ playUiSound('whoosh');
document.documentElement.style.overflow='hidden';
document.body.classList.add('settings-open');syncSettingsPanel();void syncMachineSettings();refreshSettingsTabs?.();
queueMicrotask(()=>$('#settingsClose').focus());return
@@ -809,6 +817,12 @@ $('#settingsPanel').onkeydown=e=>{
时做的,不重画的话已经被跳过的那些卡不会自己冒出来。 */
$('#groupCollapseSetting').onchange=e=>{appSettings.groupCollapse=!!e.target.checked;saveSettings();reloadCurrentSurface()};
$('#detailAutoplaySetting').onchange=e=>{appSettings.detailAutoplay=e.target.checked;saveSettings()};
+/* 开这一格时立刻响一声开关音,人才知道它开了。关的那一声由 document 上的 change 监听
+ 发出:捕获阶段排在这个处理器前面,那时开关还没关掉,最后一声还能响出来。 */
+$('#uiSoundsSetting').onchange=e=>{
+ appSettings.uiSounds=e.target.checked;setUiSoundsEnabled(appSettings.uiSounds);saveSettings();
+ if(appSettings.uiSounds)playUiSound('toggle-on');
+};
/* 关掉小窗播放时正开着的那个小窗也一起收:设置说的是「离开详情不再进小窗」,留着一个
已经进去的反而像没生效。 */
$('#miniplayerSetting').onchange=e=>{appSettings.miniplayer=e.target.checked;saveSettings();if(!appSettings.miniplayer)closeMiniplayer()};
@@ -936,7 +950,9 @@ let runtimeConfigurable=null;
const toastBody=message=>message&&typeof message==='object'&&'html' in message
? String(message.html)
: esc(message&&typeof message==='object'?(message.text??''):message??'');
-const toast=(message,{timeout=6000,warn=false,action=null}={})=>{
+/* 音效按通知表达的状态分三档:成功、警告、失败。默认由 `warn` 取成功或失败;事情
+ 做完了但有一部分要留意(几个来源失败、筛出来没有能放的)的传 `sound:'warning'`。 */
+const toast=(message,{timeout=6000,warn=false,action=null,sound=null}={})=>{
const root=$('#toasts');
const item=document.createElement('div');
item.className='toast'+(warn?' warn':'');
@@ -944,6 +960,7 @@ const toast=(message,{timeout=6000,warn=false,action=null}={})=>{
const paint=(body,alert)=>{
item.classList.toggle('warn',!!alert);
item.setAttribute('role',alert?'alert':'status');
+ playUiSound(sound||(alert?'error':'success'));
item.innerHTML=`<span class="board-notification-icon" aria-hidden="true">${icon(alert?'circle-alert':'check')}</span><p>${body}</p>${
action&&!alert&&body===initial?`<button class="tact">${esc(action.label)}</button>`:''
}<button class="tclose" title="关闭" aria-label="关闭提示">${icon('x')}</button>`;
@@ -5886,7 +5903,7 @@ function followCheckToast(report){
toast({html:`检查了 <b>${rows.length}</b> 个来源:${bits.join(' · ')}`+
(exhausted?` · <b>${exhausted} 个没有更多内容</b>`:'')+
(failed?` · <b>${failed} 个失败</b>`:'')},
- {warn:!!failed,timeout:failed?8000:6000,
+ {warn:!!failed,timeout:failed?8000:6000,sound:failed?'warning':'success',
action:{label:'去看更新',run:()=>openFollow()}});
}
/* ── 看的那一页 ── */
@@ -9370,7 +9387,7 @@ async function openTok(startId,push=true){
const selectedItem=await api('/api/item?id='+startId);
if(selectedItem.id)tokList=[selectedItem,...tokList.filter(x=>x.id!==startId)];
}
- if(!tokList.length){$('#tokClose').click();toast({text:'当前筛选下没有可直接播放的内容'});return}
+ if(!tokList.length){$('#tokClose').click();toast({text:'当前筛选下没有可直接播放的内容'},{sound:'warning'});return}
tokIdx=Math.max(0,tokList.findIndex(x=>x.id===startId));
await tokShow();
}catch(_e){setTokLoading(false);$('#tokClose').click()}
diff --git a/web/index.html b/web/index.html
index 6fc160bee..917af4916 100644
--- a/web/index.html
+++ b/web/index.html
@@ -290,6 +290,7 @@
<section class="settinggroup"><h3>界面</h3>
<div class="settingrow"><span><b>主题</b><small>跟随系统,或固定用浅色、深色。</small></span><div id="themeSetting"></div></div>
+ <label class="settingrow"><span><b>界面音效</b><small id="uiSoundsDescription">按钮、开关、菜单、弹层和操作回执各配一声轻响。</small></span><input class="ptoggle" type="checkbox" id="uiSoundsSetting" role="switch" aria-describedby="uiSoundsDescription"></label>
<label class="settingrow"><span><b>侧栏光晕</b><small id="homeGlowDescription">左栏玻璃面上那几团慢慢漂动的光。配色在左栏底部那枚配色钮上挑,这里调强度、颗粒和每一枚光晕的颜色。浅色主题按同一组颜色淡一档显示。</small></span><input type="checkbox" id="homeGlowSetting" class="ptoggle" role="switch" aria-describedby="homeGlowDescription"></label>
<section class="glowsetting" id="homeGlowControls" aria-label="侧栏光晕参数"></section>
<section class="sidebarsetting" aria-labelledby="sidebarOrderTitle"><span><b id="sidebarOrderTitle">左侧导航</b><small>直接拖动排序;可隐藏入口,也可从具体页面列表重新添加。窄栏和筛选抽屉会保持一致。</small></span><div class="sidebarorder" id="sidebarOrderSetting"></div></section>
diff --git a/web/js/ui-components.js b/web/js/ui-components.js
index fe63fe41e..2c0f87e8e 100644
--- a/web/js/ui-components.js
+++ b/web/js/ui-components.js
@@ -1,4 +1,5 @@
import { esc, icon, requestErrorMessage } from './core.js';
+import { playUiSound } from './ui-sounds.js';
export { MEDIA_SOURCE_ICONS } from './media-source-icons.js';
const NOTE_VARIANTS=new Set(['secondary','warning','error','success']);
@@ -879,7 +880,11 @@ export function closeAnchoredMenu(){if(openedMenu)openedMenu.setOpen(false)}
CSS 决定:读到的 animation-name 是 none(旧界面、prefers-reduced-motion)就当场藏起来。
全站的菜单都从这两个口进出,`hidden` 才始终是「看不见了」,不会有一份自己写的 150ms。 */
const leavingMenus=new WeakMap();
-export function presentMenu(menu){leavingMenus.delete(menu);menu.classList.remove('leaving');menu.hidden=false}
+export function presentMenu(menu){
+ leavingMenus.delete(menu);menu.classList.remove('leaving');
+ if(menu.hidden)playUiSound('whoosh');
+ menu.hidden=false;
+}
export function dismissMenu(menu,finish){
if(menu.hidden||leavingMenus.has(menu))return;
const done=()=>{if(leavingMenus.get(menu)!==done)return;
@@ -1138,6 +1143,7 @@ export function formModal({title,description='',body='',confirmLabel,cancelLabel
}finally{busy=false}
};
dialog.showModal();
+ playUiSound('pop');
(dialog.querySelector('.geist-modal-fields input:not([type="checkbox"])')||accept).focus();
return {dialog,confirmButton:accept,done,close:()=>dialog.close()};
}
@@ -1202,6 +1208,7 @@ export function confirmModal({title,body,confirmLabel,cancelLabel='取消',onCon
}finally{busy=false}
};
dialog.showModal();
+ playUiSound('pop');
(danger?cancel:accept).focus();
});
}
diff --git a/web/js/ui-sounds.js b/web/js/ui-sounds.js
new file mode 100644
index 000000000..7c3d23218
--- /dev/null
+++ b/web/js/ui-sounds.js
@@ -0,0 +1,148 @@
+/* 界面音效:按钮、开关、菜单、弹层和操作回执各配一声轻响。
+
+ 声音全部由 Web Audio 当场合成,不带音频文件,也不多一个网络请求。配方取自
+ dannyjpwilliams/ui-sound-design-skill 的 `references/sound-recipes.md`(MIT):
+ 点击是带通滤过的噪声、开关是一段正弦扫频、成功是升一个大三度、出错是压暗的下行
+ 锯齿波、警告是中频的两下短脉冲、菜单是滤波噪声扫过、弹层是一记音高骤降的正弦。
+ 音量按这个库的口径调到
+ 配方给的下限附近:它们一天里要响几百次,只能是陪衬。
+
+ 全站只开一个 AudioContext,而且要等到第一声真要响时才建:浏览器在用户手势之前
+ 不让出声,页面一进来就建会被挂起,还多占一路系统音频。开关状态由 app.js 的
+ `appSettings.uiSounds` 决定,通过 `setUiSoundsEnabled` 灌进来;关着时这里连
+ AudioContext 都不碰。 */
+
+let audioContext=null;
+let enabled=false;
+
+/* 单例:`exponentialRampToValueAtTime` 不能落到 0,收尾一律 0.001,听不见但合法。
+ 每个配方开头读一次 `currentTime`,之后全从它推——中途再读,节点就排到了过去。 */
+function context(){
+ const Context=globalThis.AudioContext||globalThis.webkitAudioContext;
+ if(!Context)return null;
+ if(!audioContext)audioContext=new Context();
+ /* 没有用户手势时 resume 会被拒:那一声本来就不该响,吞掉即可,别在控制台留一条未处理的拒绝。 */
+ if(audioContext.state==='suspended')audioContext.resume()?.catch?.(()=>{});
+ return audioContext;
+}
+
+function tone(ctx,now,{type='sine',from,to=from,duration,volume,attack=0,start=0,filter=null}){
+ const at=now+start;
+ const osc=ctx.createOscillator();
+ const gain=ctx.createGain();
+ osc.type=type;
+ osc.frequency.setValueAtTime(from,at);
+ if(to!==from)osc.frequency.exponentialRampToValueAtTime(to,at+duration);
+ if(attack){
+ gain.gain.setValueAtTime(0.001,at);
+ gain.gain.exponentialRampToValueAtTime(volume,at+attack);
+ }else gain.gain.setValueAtTime(volume,at);
+ gain.gain.exponentialRampToValueAtTime(0.001,at+duration);
+ let tail=osc;
+ if(filter){
+ const shape=ctx.createBiquadFilter();
+ shape.type=filter.type;
+ shape.frequency.value=filter.frequency;
+ shape.Q.value=filter.Q??1;
+ osc.connect(shape);tail=shape;
+ }
+ tail.connect(gain);
+ gain.connect(ctx.destination);
+ osc.start(at);
+ osc.stop(at+duration+0.01);
+}
+
+/* 噪声源是一次性的:每响一声造一段新缓冲,放完把整条链拆掉。振荡器 stop 之后会
+ 自己断开,BufferSource 不会,滤波器和增益节点就一直挂在图上。 */
+function noise(ctx,now,{duration,volume,filter,sweepTo=null,attack=0}){
+ const length=Math.max(1,Math.round(ctx.sampleRate*duration));
+ const buffer=ctx.createBuffer(1,length,ctx.sampleRate);
+ const data=buffer.getChannelData(0);
+ for(let i=0;i<length;i++)data[i]=Math.random()*2-1;
+ const source=ctx.createBufferSource();
+ source.buffer=buffer;
+ const shape=ctx.createBiquadFilter();
+ shape.type='bandpass';
+ shape.Q.value=filter.Q;
+ shape.frequency.setValueAtTime(filter.frequency,now);
+ if(sweepTo)shape.frequency.exponentialRampToValueAtTime(sweepTo,now+duration);
+ const gain=ctx.createGain();
+ if(attack){
+ gain.gain.setValueAtTime(0.001,now);
+ gain.gain.exponentialRampToValueAtTime(volume,now+attack);
+ }else gain.gain.setValueAtTime(volume,now);
+ gain.gain.exponentialRampToValueAtTime(0.001,now+duration);
+ source.connect(shape);
+ shape.connect(gain);
+ gain.connect(ctx.destination);
+ source.onended=()=>{source.disconnect();shape.disconnect();gain.disconnect()};
+ source.start(now);
+}
+
+/** 名字对应界面上的一类动作,不对应某个控件;同一类动作在哪一页都是同一声。 */
+const RECIPES={
+ /* 软点击:配方的 Soft click 变体,再往低压一档音量。 */
+ click:(ctx,now)=>noise(ctx,now,{duration:0.06,volume:0.12,filter:{frequency:1200,Q:1}}),
+ /* 开关:升是开、降是关,配方的 Minimal toggle 变体,两头音量一致。 */
+ 'toggle-on':(ctx,now)=>tone(ctx,now,{from:550,to:650,duration:0.08,volume:0.15}),
+ 'toggle-off':(ctx,now)=>tone(ctx,now,{from:650,to:550,duration:0.08,volume:0.15}),
+ /* 成功:C5 起升一个大三度,两个音之间留 80ms。 */
+ success:(ctx,now)=>{
+ tone(ctx,now,{from:523,duration:0.12,volume:0.18});
+ tone(ctx,now,{from:523*1.25,duration:0.12,volume:0.18,start:0.2});
+ },
+ /* 警告:中频三角波两下短脉冲,说的是「留意一下」,不带出错那种负面。 */
+ warning:(ctx,now)=>{
+ tone(ctx,now,{type:'triangle',from:600,duration:0.08,volume:0.15});
+ tone(ctx,now,{type:'triangle',from:600,duration:0.08,volume:0.15,start:0.16});
+ },
+ /* 出错:锯齿波经低通压暗后下行,配方默认参数按音量下限取。 */
+ error:(ctx,now)=>tone(ctx,now,{type:'sawtooth',from:400,to:200,duration:0.25,volume:0.15,
+ filter:{type:'lowpass',frequency:1500,Q:1}}),
+ /* 菜单与面板进场:配方的 Quick swipe 变体。 */
+ whoosh:(ctx,now)=>noise(ctx,now,{duration:0.12,volume:0.08,attack:0.036,
+ filter:{frequency:1000,Q:1},sweepTo:6000}),
+ /* 弹层进场:配方的 Light tap 变体。 */
+ pop:(ctx,now)=>tone(ctx,now,{from:1500,to:500,duration:0.04,volume:0.15}),
+};
+
+export const UI_SOUNDS=Object.freeze(Object.keys(RECIPES));
+
+export function setUiSoundsEnabled(on){enabled=on===true}
+export function uiSoundsEnabled(){return enabled}
+
+/** 响一声;关着、浏览器没有 Web Audio 时什么都不做并返回 false。 */
+export function playUiSound(name){
+ const recipe=RECIPES[name];
+ if(!recipe)throw new Error(`没有「${name}」这种界面音效`);
+ if(!enabled)return false;
+ const ctx=context();
+ if(!ctx)return false;
+ recipe(ctx,ctx.currentTime);
+ return true;
+}
+
+/* 会响的控件按角色认,不按类名:React 子树的按钮和旧壳的按钮长得不一样,但都是
+ `button`。开关走 change 而不是 click:一次点击只该响一声,而且响的是开还是关要看
+ 点完的状态。禁用中的(`disabled`、`aria-disabled`)不响——它没有发生任何事。 */
+const CLICKABLE='button,[role="button"],[role="tab"],[role="menuitem"],[role="menuitemradio"],'
+ +'[role="menuitemcheckbox"],[role="option"],summary,a[href]';
+const SWITCH='input[type="checkbox"][role="switch"]';
+
+function inert(control){
+ return control.disabled===true||control.getAttribute('aria-disabled')==='true';
+}
+
+/** 挂到 document 上:用捕获阶段,哪个页面在自己那层 stopPropagation 都拦不住这一声。 */
+export function wireUiSounds(root=document){
+ root.addEventListener('click',event=>{
+ const control=event.target?.closest?.(CLICKABLE);
+ if(!control||inert(control))return;
+ playUiSound('click');
+ },{capture:true});
+ root.addEventListener('change',event=>{
+ const control=event.target;
+ if(!control?.matches?.(SWITCH)||inert(control))return;
+ playUiSound(control.checked?'toggle-on':'toggle-off');
+ },{capture:true});
+}