diff --git a/src/app/features/dings/dings.test.ts b/src/app/features/dings/dings.test.ts new file mode 100644 index 00000000..a8dcde40 --- /dev/null +++ b/src/app/features/dings/dings.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it, vi } from 'vitest'; +import { DING_VOLUME, createDingPlayer, motifFor, parseManifest, pickDing } from './dings'; + +const manifest = parseManifest({ + neutral: { mention: 'neutral/mention.ogg', message: 'neutral/message.ogg' }, + senders: { + eureka: { mention: 'eureka/mention.ogg', message: 'eureka/message.ogg', dm: 'eureka/dm.ogg' }, + nibu: { message: 'nibu/message.ogg' }, + }, +})!; + +describe('dings manifest', () => { + it('is read defensively: junk is no manifest, bad paths are dropped', () => { + expect(parseManifest(undefined)).toBeUndefined(); + expect(parseManifest('x')).toBeUndefined(); + expect(parseManifest({ neutral: 3, senders: [] })).toBeUndefined(); + const m = parseManifest({ + neutral: { message: '../../etc/passwd.ogg', mention: 'https://evil.example/a.ogg' }, + senders: { void: { message: 'void/message.wav', dm: 'void/dm.ogg', mention: '/abs.ogg' } }, + })!; + expect(m.neutral).toEqual({}); + expect(m.senders.void).toEqual({ dm: 'void/dm.ogg' }); + }); +}); + +describe('which ding plays', () => { + it('uses the sender instrument for the motif', () => { + expect(pickDing(manifest, 'eureka', 'mention')).toEqual({ + path: 'eureka/mention.ogg', + volume: DING_VOLUME.mention, + }); + }); + + it('falls back to the neutral ding for an unknown sender', () => { + expect(pickDing(manifest, 'stranger', 'message')?.path).toBe('neutral/message.ogg'); + }); + + it('falls back to neutral when the sender has no clip for that motif', () => { + expect(pickDing(manifest, 'nibu', 'mention')?.path).toBe('neutral/mention.ogg'); + }); + + it('is silent when neither the sender nor neutral has a clip', () => { + expect(pickDing(manifest, 'eureka', 'invite')).toBeUndefined(); + expect(pickDing(manifest, 'stranger', 'dm')).toBeUndefined(); + }); + + it('is loud for mentions and DMs and quiet for ordinary messages', () => { + expect(DING_VOLUME.mention).toBe(1); + expect(DING_VOLUME.dm).toBe(1); + expect(DING_VOLUME.message).toBeLessThan(DING_VOLUME.invite); + expect(DING_VOLUME.invite).toBeLessThan(DING_VOLUME.mention); + }); + + it('names the motif: invite over mention over DM over message', () => { + expect(motifFor({ invite: true, highlight: true, direct: true })).toBe('invite'); + expect(motifFor({ highlight: true, direct: true })).toBe('mention'); + expect(motifFor({ highlight: false, direct: true })).toBe('dm'); + expect(motifFor({ highlight: false, direct: false })).toBe('message'); + }); +}); + +describe('audio unlock', () => { + const make = () => { + const listeners = new Map void>(); + const target = { + addEventListener: (t: string, f: () => void) => listeners.set(t, f), + removeEventListener: (t: string) => listeners.delete(t), + }; + const played: Array<{ url: string; volume: number }> = []; + const player = createDingPlayer((url) => { + const clip = { volume: 1, play: vi.fn(async () => undefined) }; + played.push({ + url, + get volume() { + return clip.volume; + }, + } as never); + return clip; + }, target); + return { listeners, player, played }; + }; + + it('does not play before the first user gesture, and plays after it', () => { + const { listeners, player, played } = make(); + expect(player.play('a.ogg', 1)).toBe(false); + expect(played).toHaveLength(0); + listeners.get('pointerdown')!(); + expect(player.play('a.ogg', 0.3)).toBe(true); + expect(played).toHaveLength(1); + expect(played[0].volume).toBe(0.3); + }); + + it('stops listening once unlocked', () => { + const { listeners, player } = make(); + listeners.get('keydown')!(); + expect(listeners.size).toBe(0); + expect(player.unlocked()).toBe(true); + }); + + it('a clip the browser refuses does not throw', async () => { + const target = { + addEventListener: (_t: string, f: () => void) => f(), + removeEventListener: () => undefined, + }; + const player = createDingPlayer( + () => ({ volume: 1, play: () => Promise.reject(new Error('NotAllowedError')) }), + target + ); + expect(() => player.play('a.ogg', 1)).not.toThrow(); + await Promise.resolve(); + }); +}); diff --git a/src/app/features/dings/dings.ts b/src/app/features/dings/dings.ts new file mode 100644 index 00000000..ac27fd8e --- /dev/null +++ b/src/app/features/dings/dings.ts @@ -0,0 +1,96 @@ +// Dings: pre-rendered earcons shipped as static assets, `dings//.ogg` plus +// `dings/manifest.json` (docs/gamecult/ratatoskr-target.md, Agreements). The sender picks the +// instrument, the event picks the motif. This file is the whole decision; the client only asks it. + +export type Motif = 'mention' | 'dm' | 'message' | 'invite'; +type Clips = Partial>; +export type DingManifest = { neutral: Clips; senders: Record }; + +const MOTIFS: Motif[] = ['mention', 'dm', 'message', 'invite']; + +// Mentions and DMs loud, an ordinary message quiet. +export const DING_VOLUME: Record = { + mention: 1, + dm: 1, + invite: 0.7, + message: 0.3, +}; + +const isRecord = (v: unknown): v is Record => + typeof v === 'object' && v !== null && !Array.isArray(v); + +// A clip path stays inside dings/: relative, ogg or mp3 (not wav), no dot segments, no scheme. +const isClipPath = (v: unknown): v is string => + typeof v === 'string' && + /^[A-Za-z0-9_-]+(\/[A-Za-z0-9_.-]+)*\.(ogg|mp3)$/.test(v) && + !v.split('/').includes('..'); + +const readClips = (v: unknown): Clips => { + const clips: Clips = {}; + if (!isRecord(v)) return clips; + MOTIFS.forEach((m) => { + if (Object.prototype.hasOwnProperty.call(v, m) && isClipPath(v[m])) clips[m] = v[m] as string; + }); + return clips; +}; + +/** The manifest is JSON from outside the typed world: read it defensively, undefined if unusable. */ +export const parseManifest = (json: unknown): DingManifest | undefined => { + if (!isRecord(json) || !isRecord(json.neutral) || !isRecord(json.senders)) return undefined; + const senders: Record = Object.create(null); + Object.keys(json.senders).forEach((localpart) => { + senders[localpart] = readClips( + json.senders && (json.senders as Record)[localpart] + ); + }); + return { neutral: readClips(json.neutral), senders }; +}; + +/** The sender's own clip, else the neutral one, else nothing: silence. */ +export const pickDing = ( + manifest: DingManifest, + localpart: string, + motif: Motif +): { path: string; volume: number } | undefined => { + const own = Object.prototype.hasOwnProperty.call(manifest.senders, localpart) + ? manifest.senders[localpart][motif] + : undefined; + const path = own ?? manifest.neutral[motif]; + return path === undefined ? undefined : { path, volume: DING_VOLUME[motif] }; +}; + +export const motifFor = (e: { invite?: boolean; highlight: boolean; direct: boolean }): Motif => { + if (e.invite) return 'invite'; + if (e.highlight) return 'mention'; + return e.direct ? 'dm' : 'message'; +}; + +type Clip = { volume: number; play: () => Promise }; +type GestureTarget = { + addEventListener: (type: string, listener: () => void) => void; + removeEventListener: (type: string, listener: () => void) => void; +}; +const GESTURES = ['pointerdown', 'keydown', 'touchend']; + +/** + * Browsers refuse audio until the first user gesture. The player stays silent until one has + * happened, then plays; a clip the browser still refuses is dropped, never thrown. + */ +export const createDingPlayer = (make: (url: string) => Clip, target: GestureTarget) => { + let unlocked = false; + const unlock = () => { + unlocked = true; + GESTURES.forEach((g) => target.removeEventListener(g, unlock)); + }; + GESTURES.forEach((g) => target.addEventListener(g, unlock)); + return { + unlocked: () => unlocked, + play(url: string, volume: number): boolean { + if (!unlocked) return false; + const clip = make(url); + clip.volume = volume; + clip.play().catch(() => undefined); + return true; + }, + }; +};