Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

feat(timer): pick the sound a rest ends with: chime, classic, bell, beep-beep, whistle or soft (#306)

Duarte Santosa244048d2606
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java
index e331deb3d..d4aa022a0 100644
--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlert.java
@@ -45,7 +45,7 @@ public final class RestAlert {
static final String QUIET_CHANNEL_ID = "rest-over-quiet";
private static String lastAlertTitle = "Rest over";
private static boolean lastSound = true;
- private static boolean lastClassic = false;
+ private static String lastTone = "chime";
private static boolean lastVibrate = true;
private static boolean lastAlarmBuzz = false;
private static String lastChannel = CHANNEL_ID;
@@ -73,7 +73,7 @@ public final class RestAlert {
* alarm, which silent mode lets through, and the notification goes out on the quiet channel so
* a phone with its ringer on does not buzz twice.
*/
- public static void schedule(Context ctx, long at, int id, String title, boolean sound, boolean classic, boolean vibrate,
+ public static void schedule(Context ctx, long at, int id, String title, boolean sound, String tone, boolean vibrate,
boolean alarmBuzz, String channelId, String visibility, String importance,
boolean localOnly, String countdownTitle, long totalMs) {
alarmBuzz = vibrate && alarmBuzz;
@@ -82,7 +82,7 @@ public final class RestAlert {
intent.putExtra("id", id);
intent.putExtra("title", title == null ? "" : title);
intent.putExtra("sound", sound);
- intent.putExtra("classic", classic);
+ intent.putExtra("tone", tone == null ? "chime" : tone);
intent.putExtra("vibrate", vibrate);
intent.putExtra("alarmBuzz", alarmBuzz);
intent.putExtra("channelId", channelId);
@@ -108,7 +108,7 @@ public final class RestAlert {
}
lastAlertTitle = title == null ? "Rest over" : title;
lastSound = sound;
- lastClassic = classic;
+ lastTone = tone == null ? "chime" : tone;
lastVibrate = vibrate;
lastAlarmBuzz = alarmBuzz;
lastChannel = channelId;
@@ -150,7 +150,7 @@ public final class RestAlert {
intent.putExtra("id", NOTIFICATION_ID);
intent.putExtra("title", lastAlertTitle);
intent.putExtra("sound", lastSound);
- intent.putExtra("classic", lastClassic);
+ intent.putExtra("tone", lastTone);
intent.putExtra("vibrate", lastVibrate);
intent.putExtra("alarmBuzz", lastAlarmBuzz);
intent.putExtra("channelId", lastChannel);
@@ -193,9 +193,9 @@ public final class RestAlert {
// Settings → Vibrate off is off here too: without notifications this buzz is the alert.
else if (!shown && vibrate) vibrateFallback(ctx);
// Locked or in the background, the page does not play its chime, so this is the one:
- // the same chime (or classic beeps) as Settings → Sound picks for the page.
+ // the same sound as Settings → Sound picks for the page (RestTone.render).
boolean play = intent.getBooleanExtra("sound", true);
- if (play) playSound(ctx, intent.getBooleanExtra("classic", false));
+ if (play) playSound(ctx, toneOf(intent));
// The countdown card is the foreground-service notification. Drop it once the
// "rest over" alert is up and the tone has played, including when the WebView is
// frozen. Not before the tone: the service is what keeps this process in the
@@ -365,7 +365,7 @@ public final class RestAlert {
intent.putExtra("id", NOTIFICATION_ID);
intent.putExtra("title", lastAlertTitle);
intent.putExtra("sound", lastSound);
- intent.putExtra("classic", lastClassic);
+ intent.putExtra("tone", lastTone);
intent.putExtra("vibrate", lastVibrate);
intent.putExtra("alarmBuzz", lastAlarmBuzz);
intent.putExtra("channelId", lastChannel);
@@ -514,8 +514,18 @@ public final class RestAlert {
nm.createNotificationChannel(channel);
}
- private static void playSound(Context ctx, boolean classic) {
- playClip(ctx, RestTone.render(classic));
+ private static void playSound(Context ctx, String tone) {
+ playClip(ctx, RestTone.render(tone));
+ }
+
+ /**
+ * The sound an alarm asks for: its "tone" (#306), or for an alarm armed by the app before it,
+ * still pending across the update, its "classic" switch.
+ */
+ private static String toneOf(Intent intent) {
+ String tone = intent.getStringExtra("tone");
+ if (tone != null) return tone;
+ return intent.getBooleanExtra("classic", false) ? "classic" : "chime";
}
/**
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java
index 94b88249e..d570032c1 100644
--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestAlertPlugin.java
@@ -16,7 +16,7 @@ import com.getcapacitor.annotation.CapacitorPlugin;
* Usage from JS:
* import { registerPlugin } from '@capacitor/core';
* const RestAlert = registerPlugin('RestAlert');
- * await RestAlert.schedule({ id, at, title, sound, classic, vibrate, channelId, visibility, importance, localOnly });
+ * await RestAlert.schedule({ id, at, title, sound, tone, classic, vibrate, channelId, visibility, importance, localOnly });
* await RestAlert.cancel({ id });
* await RestAlert.buzz({ pattern: [200, 100, 200] }); // navigator.vibrate's shape, as an alarm
*/
@@ -84,7 +84,8 @@ public class RestAlertPlugin extends Plugin {
(int) number(call, "id", RestAlert.NOTIFICATION_ID),
call.getString("title", "Rest over"),
!Boolean.FALSE.equals(call.getBoolean("sound", Boolean.TRUE)),
- Boolean.TRUE.equals(call.getBoolean("classic", Boolean.FALSE)),
+ // Settings → Sound (#306): the sound by name; a page from before it sends only `classic`.
+ call.getString("tone", Boolean.TRUE.equals(call.getBoolean("classic", Boolean.FALSE)) ? "classic" : "chime"),
!Boolean.FALSE.equals(call.getBoolean("vibrate", Boolean.TRUE)),
Boolean.TRUE.equals(call.getBoolean("alarmBuzz", Boolean.FALSE)),
call.getString("channelId", RestAlert.CHANNEL_ID),
diff --git a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTone.java b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTone.java
index b65a151dd..1a5a38234 100644
--- a/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTone.java
+++ b/frontend/android/app/src/main/java/ch/duartesantos/opengym/RestTone.java
@@ -4,10 +4,12 @@ package ch.duartesantos.opengym;
* The end-of-rest tone the native side plays while the app is in the background or the screen
* is off, as 16-bit mono samples. Plain Java with no Android classes, so it has a unit test.
*
- * The page plays the same two choices through Web Audio (frontend/src/lib/sound.js chime()):
+ * The page plays the same choices through Web Audio (frontend/src/lib/sound.js chime()):
* the chime, high, low, then high and long, held near full scale in a bright timbre, and the
* classic three beeps. Until v1.3.11 this side only knew the classic beeps, so a locked phone
- * played the quiet old sound however Settings → Sound was set.
+ * played the quiet old sound however Settings → Sound was set. #306 added a bell, a beep-beep,
+ * a whistle and a soft one; their notes, peaks, holds and timbres are copied from
+ * frontend/src/lib/rest-sounds.js REST_SOUNDS and rendered the way the chime is.
*/
final class RestTone {
static final int RATE = 22050;
@@ -23,13 +25,37 @@ final class RestTone {
static final double CHIME_PEAK = 0.9;
private static final double[][] CHIME = {{1319, 0.16, 0}, {988, 0.16, 0.22}, {1319, 0.5, 0.44}};
private static final double CHIME_HOLD = 0.6;
- /** lib/sound.js setBright: the fundamental and three falling harmonics. */
+ /** lib/sound.js TIMBRES: the strengths of the fundamental and its harmonics. A sine is {1}. */
private static final double[] BRIGHT = {1, 0.6, 0.35, 0.2};
+ private static final double[] BELL = {1, 0.25, 0.5, 0.1, 0.3};
+ private static final double[] SINE = {1};
+
+ /** lib/rest-sounds.js REST_SOUNDS: notes of {freq, dur, when} or {freq, dur, when, glideTo}. */
+ private static final double[][] BELL_NOTES = {{1319, 0.9, 0}, {1047, 1.3, 0.4}};
+ private static final double[][] BEEP_NOTES = {{1760, 0.08, 0}, {1760, 0.08, 0.13}, {1760, 0.08, 0.4}, {1760, 0.08, 0.53}};
+ private static final double[][] WHISTLE_NOTES = {{1300, 0.16, 0, 2100}, {1500, 0.42, 0.22, 2500}};
+ private static final double[][] SOFT_NOTES = {{659, 0.4, 0}, {784, 0.4, 0.2}, {988, 0.8, 0.4}};
+
+ /** Every name Settings → Sound can hand over (lib/rest-sounds.js REST_SOUND_IDS). */
+ static final String[] KINDS = {"chime", "classic", "bell", "beep", "whistle", "soft"};
private RestTone() {}
static short[] render(boolean classic) {
- return withTail(classic ? renderBeeps() : renderChime());
+ return render(classic ? "classic" : "chime");
+ }
+
+ /** The sound named `kind`, with its silent tail; a name it does not know plays the chime. */
+ static short[] render(String kind) {
+ String k = kind == null ? "chime" : kind;
+ switch (k) {
+ case "classic": return withTail(renderBeeps());
+ case "bell": return withTail(renderNotes(BELL_NOTES, 0.55, 0, BELL));
+ case "beep": return withTail(renderNotes(BEEP_NOTES, 0.8, 0.8, BRIGHT));
+ case "whistle": return withTail(renderNotes(WHISTLE_NOTES, 0.7, 0.55, SINE));
+ case "soft": return withTail(renderNotes(SOFT_NOTES, 0.3, 0, SINE));
+ default: return withTail(renderChime());
+ }
}
/**
@@ -38,19 +64,31 @@ final class RestTone {
* Web Audio normalises a periodic wave.
*/
static short[] renderChime() {
+ return renderNotes(CHIME, CHIME_PEAK, CHIME_HOLD, BRIGHT);
+ }
+
+ /**
+ * Notes the way lib/sound.js tone() plays them: each with the gain curve of `gain`, in the
+ * timbre `harmonics` normalised to a peak of 1, a note with a fourth number sliding linearly
+ * to that frequency by its end (Web Audio's linearRampToValueAtTime). Overlapping notes add
+ * up; the sounds are tuned so they stay under full scale, and the sum is clamped all the same.
+ */
+ static short[] renderNotes(double[][] notes, double peak, double hold, double[] harmonics) {
double end = 0;
- for (double[] n : CHIME) end = Math.max(end, n[2] + n[1]);
+ for (double[] n : notes) end = Math.max(end, n[2] + n[1]);
double[] mix = new double[(int) Math.ceil(end * RATE)];
- double norm = brightPeak();
- for (double[] n : CHIME) {
- double freq = n[0], dur = n[1];
+ double norm = wavePeak(harmonics);
+ for (double[] n : notes) {
+ double freq = n[0], dur = n[1], to = n.length > 3 ? n[3] : freq;
int start = (int) Math.round(n[2] * RATE);
int len = (int) (dur * RATE);
for (int s = 0; s < len && start + s < mix.length; s++) {
double t = s / (double) RATE;
+ // the phase of a frequency rising linearly from `freq` to `to` over `dur`
+ double cycles = freq * t + (to - freq) * t * t / (2 * dur);
double wave = 0;
- for (int k = 0; k < BRIGHT.length; k++) wave += BRIGHT[k] * Math.sin(2 * Math.PI * freq * (k + 1) * t);
- mix[start + s] += wave / norm * chimeGain(t, dur);
+ for (int k = 0; k < harmonics.length; k++) wave += harmonics[k] * Math.sin(2 * Math.PI * cycles * (k + 1));
+ mix[start + s] += wave / norm * gain(t, dur, peak, hold);
}
}
short[] out = new short[mix.length];
@@ -60,20 +98,29 @@ final class RestTone {
/** The gain curve of lib/sound.js tone() with peak CHIME_PEAK and hold CHIME_HOLD. */
static double chimeGain(double t, double dur) {
- double floor = 0.001, attack = 0.02, holdEnd = dur * CHIME_HOLD;
+ return gain(t, dur, CHIME_PEAK, CHIME_HOLD);
+ }
+
+ /**
+ * lib/sound.js tone()'s gain: up from 0.001 to `peak` in 20 ms, held until `hold` of the note
+ * (never before the 20 ms are up, as Web Audio runs the ramps in order), then down to 0.001
+ * by the end.
+ */
+ static double gain(double t, double dur, double peak, double hold) {
+ double floor = 0.001, attack = 0.02, holdEnd = Math.max(attack, dur * hold);
if (t < 0) return 0;
- if (t < attack) return floor * Math.pow(CHIME_PEAK / floor, t / attack);
- if (t < holdEnd) return CHIME_PEAK;
- if (t < dur) return CHIME_PEAK * Math.pow(floor / CHIME_PEAK, (t - holdEnd) / (dur - holdEnd));
+ if (t < attack) return floor * Math.pow(peak / floor, t / attack);
+ if (t < holdEnd) return peak;
+ if (t < dur) return peak * Math.pow(floor / peak, (t - holdEnd) / (dur - holdEnd));
return 0;
}
- private static double brightPeak() {
+ private static double wavePeak(double[] harmonics) {
double max = 0;
for (int i = 0; i < 4096; i++) {
double x = 2 * Math.PI * i / 4096;
double v = 0;
- for (int k = 0; k < BRIGHT.length; k++) v += BRIGHT[k] * Math.sin((k + 1) * x);
+ for (int k = 0; k < harmonics.length; k++) v += harmonics[k] * Math.sin((k + 1) * x);
max = Math.max(max, Math.abs(v));
}
return max;
diff --git a/frontend/android/app/src/test/java/ch/duartesantos/opengym/RestToneTest.java b/frontend/android/app/src/test/java/ch/duartesantos/opengym/RestToneTest.java
index 7bb2dc524..ce9abc2cd 100644
--- a/frontend/android/app/src/test/java/ch/duartesantos/opengym/RestToneTest.java
+++ b/frontend/android/app/src/test/java/ch/duartesantos/opengym/RestToneTest.java
@@ -51,4 +51,34 @@ public class RestToneTest {
}
assertTrue(peak(RestTone.renderChime(), 0, 1) < 32767);
}
+
+ @Test
+ public void everySoundIsItsOwnEndsInSilenceAndNeverClips() {
+ java.util.Set<String> shapes = new java.util.HashSet<>();
+ for (String kind : RestTone.KINDS) {
+ short[] s = RestTone.render(kind);
+ double secs = s.length / (double) RestTone.RATE;
+ assertTrue(kind, peak(s, 0, secs - RestTone.TAIL_SEC) > 0.25 * 32767);
+ assertEquals(kind, 0, peak(s, secs - RestTone.TAIL_SEC + 0.01, secs));
+ for (short v : s) assertTrue(kind, Math.abs(v) <= 32767);
+ shapes.add(java.util.Arrays.toString(s));
+ }
+ assertEquals(RestTone.KINDS.length, shapes.size());
+ }
+
+ @Test
+ public void namesStandInForTheOldSwitchAndAnUnknownOneIsTheChime() {
+ assertArrayEquals(RestTone.render(false), RestTone.render("chime"));
+ assertArrayEquals(RestTone.render(true), RestTone.render("classic"));
+ assertArrayEquals(RestTone.render("chime"), RestTone.render("kazoo"));
+ assertArrayEquals(RestTone.render("chime"), RestTone.render((String) null));
+ }
+
+ @Test
+ public void aNoteWithoutAHoldFadesFromTheEndOfItsAttack() {
+ // the bell and the soft one: up in 20 ms, then straight down, as Web Audio runs the ramps
+ assertEquals(0.55, RestTone.gain(0.02, 0.9, 0.55, 0), 1e-9);
+ assertTrue(RestTone.gain(0.3, 0.9, 0.55, 0) < 0.55 / 4);
+ assertEquals(RestTone.chimeGain(0.25, 0.5), RestTone.gain(0.25, 0.5, RestTone.CHIME_PEAK, 0.6), 1e-12);
+ }
}
diff --git a/frontend/src/lib/rest-alert.js b/frontend/src/lib/rest-alert.js
index 72a7fe443..c172cf150 100644
--- a/frontend/src/lib/rest-alert.js
+++ b/frontend/src/lib/rest-alert.js
@@ -12,6 +12,7 @@ import { t } from './i18n-core.js'
import { argb } from './format.js'
import { accentPair } from './accent.js'
import { MOBILE, isAndroid } from './mobile.js'
+import { REST_SOUNDS } from './rest-sounds.js'
export const REST_ALERT_ID = 42
export const REST_CHANNEL_ID = 'rest-over'
@@ -28,8 +29,10 @@ export function accentColors(key) {
return { accent: argb(accent), ink: argb(ink) }
}
-export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, sound = true, classic = false, vibrate = true, alarmBuzz = false, now = Date.now() } = {}) {
+export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, sound = true, classic = false, tone = null, vibrate = true, alarmBuzz = false, now = Date.now() } = {}) {
if (typeof at !== 'number' || !(at > now)) return null
+ // Settings → Sound (#306): one of lib/sound.js REST_SOUNDS; without one, `classic` decides, as before.
+ const kind = Object.hasOwn(REST_SOUNDS, tone) ? tone : classic === true ? 'classic' : 'chime'
const totalMs = Math.max(1000, Math.round((totalSec > 0 ? totalSec : (at - now) / 1000) * 1000))
const colors = accentColors(accent)
return {
@@ -48,9 +51,11 @@ export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, so
at,
allowWhileIdle: true,
sound: !!sound,
- // Settings → Sound: the native side plays the same end tone the page does, the chime by
- // default or the classic beeps. Only `true` means classic, as in lib/sound.js chime().
- classic: classic === true,
+ // Settings → Sound: the native side plays the same end tone the page does (RestTone.java).
+ // `tone` names it; `classic` stays for an app shell from before #306, which reads only that
+ // and plays the chime for every other pick.
+ tone: kind,
+ classic: kind === 'classic',
vibrate: !!vibrate,
// Settings → "Vibrate when the phone is on silent" (#375): the end buzzes as an alarm, which
// silent mode lets through, instead of through the notification channel, which it mutes.
@@ -90,7 +95,7 @@ const restPlugin = () => pluginP || (pluginP = (async () => {
export function armRestAlert(at, opts = {}) {
if (!MOBILE) return Promise.resolve(false)
const mine = ++token
- const alert = buildRestAlert({ at, title: opts.title, countdownTitle: opts.countdownTitle, totalSec: opts.totalSec, accent: opts.accent, sound: opts.sound, classic: opts.classic === true, vibrate: opts.vibrate !== false, alarmBuzz: !!opts.alarmBuzz })
+ const alert = buildRestAlert({ at, title: opts.title, countdownTitle: opts.countdownTitle, totalSec: opts.totalSec, accent: opts.accent, sound: opts.sound, classic: opts.classic === true, tone: opts.tone, vibrate: opts.vibrate !== false, alarmBuzz: !!opts.alarmBuzz })
if (!alert) return Promise.resolve(false)
// Outside the chain and never awaited: the alarm, its tone and the alarm buzz do not need the
// notification permission, and a dialog left open while the phone is put away must not hold
@@ -208,6 +213,7 @@ async function deliver(alert) {
title: alert.title,
sound: alert.sound,
classic: alert.classic,
+ tone: alert.tone,
// The end of a rest the app is not in front for: the notification, or the buzz standing in
// for it where notifications are off. With the app in front the page buzzes (lib/sound.js).
vibrate: alert.vibrate,
diff --git a/frontend/src/lib/rest-alert.native.test.js b/frontend/src/lib/rest-alert.native.test.js
index 48265def8..05c585341 100644
--- a/frontend/src/lib/rest-alert.native.test.js
+++ b/frontend/src/lib/rest-alert.native.test.js
@@ -151,7 +151,9 @@ describe('the alarm buzz in the Android app', () => {
await alert.armRestAlert(Date.now() + 90_000, { totalSec: 90, sound: true })
expect(calls.schedule.at(-1)).toMatchObject({ sound: true, classic: false })
await alert.armRestAlert(Date.now() + 90_000, { totalSec: 90, sound: true, classic: true })
- expect(calls.schedule.at(-1)).toMatchObject({ sound: true, classic: true })
+ expect(calls.schedule.at(-1)).toMatchObject({ sound: true, classic: true, tone: 'classic' })
+ await alert.armRestAlert(Date.now() + 90_000, { totalSec: 90, sound: true, tone: 'whistle' })
+ expect(calls.schedule.at(-1)).toMatchObject({ sound: true, classic: false, tone: 'whistle' })
})
it('buzzAsAlarm reaches the plugin with the pattern and answers true', async () => {
diff --git a/frontend/src/lib/rest-alert.test.js b/frontend/src/lib/rest-alert.test.js
index 196e3ae4f..1a58e6802 100644
--- a/frontend/src/lib/rest-alert.test.js
+++ b/frontend/src/lib/rest-alert.test.js
@@ -39,6 +39,15 @@ describe('buildRestAlert', () => {
expect(buildRestAlert({ at: now + 1000, classic: 'kind', now }).classic).toBe(false)
})
+ // #306: more sounds to pick from. `tone` names the one; `classic` stays for an older app shell.
+ it('names the picked sound for the native side, with classic set for the classic beeps only', () => {
+ expect(buildRestAlert({ at: now + 1000, now })).toMatchObject({ tone: 'chime', classic: false })
+ expect(buildRestAlert({ at: now + 1000, tone: 'bell', now })).toMatchObject({ tone: 'bell', classic: false })
+ expect(buildRestAlert({ at: now + 1000, tone: 'classic', now })).toMatchObject({ tone: 'classic', classic: true })
+ expect(buildRestAlert({ at: now + 1000, classic: true, now })).toMatchObject({ tone: 'classic', classic: true })
+ for (const junk of ['kazoo', 'constructor', 7]) expect(buildRestAlert({ at: now + 1000, tone: junk, now }).tone).toBe('chime')
+ })
+
// A channel keeps the vibration it was created with, so Vibrate off cannot switch 'rest-over'
// off: that end goes out on a channel that never buzzes.
it('buzzes on the rest channel by default, and uses the quiet one when Vibrate is off', () => {
diff --git a/frontend/src/lib/rest-sounds.js b/frontend/src/lib/rest-sounds.js
new file mode 100644
index 000000000..399040962
--- /dev/null
+++ b/frontend/src/lib/rest-sounds.js
@@ -0,0 +1,34 @@
+// The end-of-rest sounds (Settings → Sound, #306) as data: what lib/sound.js chime() plays
+// through Web Audio, and what android/.../RestTone.java renders, number for number, for a locked
+// phone. Kept apart from lib/sound.js so the store, Settings and the native alarm (lib/rest-alert.js)
+// can read the choice without the audio code. See lib/sound.js chime() for how a sound is played.
+export const CHIME_PEAK = 0.9
+const CHIME = [[1319, 0.16, 0], [988, 0.16, 0.22], [1319, 0.5, 0.44]]
+const CLASSIC = [[880, 0.15, 0], [880, 0.15, 0.25], [1320, 0.4, 0.5]]
+export const REST_SOUNDS = {
+ chime: { notes: CHIME, peak: CHIME_PEAK, hold: 0.6, timbre: 'bright' },
+ classic: { notes: CLASSIC },
+ // ding-dong: two strikes a major third apart, left to ring out
+ bell: { notes: [[1319, 0.9, 0], [1047, 1.3, 0.4]], peak: 0.55, hold: 0, timbre: 'bell' },
+ // a sports watch: two pairs of short, square-cut beeps
+ beep: { notes: [[1760, 0.08, 0], [1760, 0.08, 0.13], [1760, 0.08, 0.4], [1760, 0.08, 0.53]], peak: 0.8, hold: 0.8, timbre: 'bright' },
+ // a coach's "wheet-wheeet", up both times
+ whistle: { notes: [[1300, 0.16, 0, 2100], [1500, 0.42, 0.22, 2500]], peak: 0.7, hold: 0.55 },
+ // three low, rising notes that melt into each other, for a quiet room or headphones
+ soft: { notes: [[659, 0.4, 0], [784, 0.4, 0.2], [988, 0.8, 0.4]], peak: 0.3, hold: 0 },
+}
+export const REST_SOUND_IDS = Object.keys(REST_SOUNDS)
+
+/**
+ * The end-of-rest sound a profile plays. `S.restSound` names it; `S.classicChime` is how the
+ * choice was stored before there were more than two, and an app from before #306 still writes
+ * only that. So `classicChime: true` always means the classic beeps (this app clears it for any
+ * other pick, so true can only be an older app's later choice), and a stored `restSound` of
+ * 'classic' without it means that older app switched back to the chime.
+ */
+export function restSoundOf(S) {
+ if (S?.classicChime === true) return 'classic'
+ const k = S?.restSound
+ return Object.hasOwn(REST_SOUNDS, k) && k !== 'classic' ? k : 'chime'
+}
+
diff --git a/frontend/src/lib/rest-sounds.test.js b/frontend/src/lib/rest-sounds.test.js
new file mode 100644
index 000000000..de6040938
--- /dev/null
+++ b/frontend/src/lib/rest-sounds.test.js
@@ -0,0 +1,65 @@
+// #306: the end-of-rest sounds are played twice over, by the page (lib/sound.js, Web Audio) and by
+// a locked Android phone (RestTone.java, rendered samples). The Java side cannot run here (no
+// gradle in the test run), so its numbers are read out of the source and held against the table
+// the page plays from: a note changed on one side only fails here.
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { REST_SOUNDS, REST_SOUND_IDS } from './rest-sounds.js'
+import { TIMBRES } from './sound.js'
+
+const java = name => readFileSync(new URL(`../../android/app/src/main/java/ch/duartesantos/opengym/${name}.java`, import.meta.url), 'utf8')
+const tone = java('RestTone')
+const numbers = text => text.match(/-?\d+(\.\d+)?/g).map(Number)
+// `{{a, b, c}, {d, e, f, g}}` → [[a, b, c], [d, e, f, g]]
+const notesOf = name => {
+ const m = new RegExp(`${name}\\s*=\\s*\\{(\\{[^;]*\\})\\};`).exec(tone)
+ expect(m, name).toBeTruthy()
+ return m[1].split(/\}\s*,\s*\{/).map(numbers)
+}
+const arrayOf = name => {
+ const m = new RegExp(`double\\[\\] ${name}\\s*=\\s*\\{([^}]*)\\}`).exec(tone)
+ expect(m, name).toBeTruthy()
+ return numbers(m[1])
+}
+// case "bell": return withTail(renderNotes(BELL_NOTES, 0.55, 0, BELL));
+const caseOf = kind => {
+ const m = new RegExp(`case "${kind}": return withTail\\(renderNotes\\((\\w+), ([\\d.]+), ([\\d.]+), (\\w+)\\)\\)`).exec(tone)
+ expect(m, kind).toBeTruthy()
+ return { notes: notesOf(m[1]), peak: Number(m[2]), hold: Number(m[3]), timbre: m[4] }
+}
+const TIMBRE_OF = { BRIGHT: 'bright', BELL: 'bell', SINE: undefined }
+
+describe('RestTone.java plays what the page plays', () => {
+ it('knows every sound Settings offers, by the same names', () => {
+ const kinds = /KINDS = \{([^}]*)\}/.exec(tone)[1].match(/"(\w+)"/g).map(s => s.slice(1, -1))
+ expect(kinds).toEqual(REST_SOUND_IDS)
+ for (const k of REST_SOUND_IDS.filter(k => k !== 'chime' && k !== 'classic')) expect(tone).toContain(`case "${k}"`)
+ })
+
+ it('has the same timbres', () => {
+ expect(arrayOf('BRIGHT')).toEqual(TIMBRES.bright)
+ expect(arrayOf('BELL')).toEqual(TIMBRES.bell)
+ expect(arrayOf('SINE')).toEqual([1])
+ })
+
+ it('has the chime\'s notes, peak and hold', () => {
+ expect(notesOf('CHIME')).toEqual(REST_SOUNDS.chime.notes)
+ expect(Number(/CHIME_PEAK = ([\d.]+);/.exec(tone)[1])).toBe(REST_SOUNDS.chime.peak)
+ expect(Number(/CHIME_HOLD = ([\d.]+);/.exec(tone)[1])).toBe(REST_SOUNDS.chime.hold)
+ })
+
+ it('has every other sound number for number', () => {
+ for (const k of ['bell', 'beep', 'whistle', 'soft']) {
+ const j = caseOf(k), page = REST_SOUNDS[k]
+ expect(j.notes, k).toEqual(page.notes)
+ expect([j.peak, j.hold, TIMBRE_OF[j.timbre]], k).toEqual([page.peak, page.hold, page.timbre])
+ }
+ })
+
+ it('takes the sound from the page by name, and the old classic switch from a page before it', () => {
+ expect(java('RestAlertPlugin')).toMatch(/call\.getString\("tone", Boolean\.TRUE\.equals\(call\.getBoolean\("classic", Boolean\.FALSE\)\) \? "classic" : "chime"\)/)
+ const alert = java('RestAlert')
+ expect(alert).toMatch(/intent\.getStringExtra\("tone"\)/)
+ expect(alert).toMatch(/RestTone\.render\(tone\)/)
+ })
+})
diff --git a/frontend/src/lib/sound.js b/frontend/src/lib/sound.js
index b7711ba41..8e38da52c 100644
--- a/frontend/src/lib/sound.js
+++ b/frontend/src/lib/sound.js
@@ -19,6 +19,8 @@
// The context is suspended again a second after the last tone: an idle context otherwise keeps
// rendering silence for the rest of the page, and under 'playback' keeps the phone's audio
// session busy. (Suspending does NOT hand the phone back to a paused music app — see 1.)
+import { REST_SOUNDS } from './rest-sounds.js'
+
let audioCtx = null
let idleTm = null
let idleAt = 0
@@ -47,31 +49,37 @@ const sleepAfter = endSec => {
}, at - Date.now())
}
-// A timbre brighter than a sine: the fundamental plus three falling harmonics. It carries over
-// music and through a phone speaker's weak low end without a square wave's buzz. The browser
-// normalises a periodic wave to a peak of 1, so the gain alone decides how loud it gets. Built
-// once per context; a browser without createPeriodicWave gets the nearest built-in shape.
-let brightWave = null
-let brightCtx = null
-const setBright = (ctx, o) => {
+// Timbres richer than a sine, as the strengths of the fundamental and its harmonics. `bright`
+// (the fundamental plus three falling harmonics) carries over music and through a phone
+// speaker's weak low end without a square wave's buzz; `bell` leans on the 3rd and 5th for a
+// struck, glassy ring. The browser normalises a periodic wave to a peak of 1, so the gain alone
+// decides how loud it gets. Built once per context; a browser without createPeriodicWave gets
+// the nearest built-in shape. android/.../RestTone.java renders the same harmonics.
+export const TIMBRES = { bright: [1, 0.6, 0.35, 0.2], bell: [1, 0.25, 0.5, 0.1, 0.3] }
+let waves = {}
+let wavesCtx = null
+const setTimbre = (ctx, o, name) => {
if (typeof ctx.createPeriodicWave !== 'function') { o.type = 'triangle'; return }
- if (brightCtx !== ctx) {
- brightCtx = ctx
- brightWave = ctx.createPeriodicWave(new Float32Array([0, 0, 0, 0, 0]), new Float32Array([0, 1, 0.6, 0.35, 0.2]))
+ if (wavesCtx !== ctx) { wavesCtx = ctx; waves = {} }
+ if (!waves[name]) {
+ const h = TIMBRES[name]
+ waves[name] = ctx.createPeriodicWave(new Float32Array(h.length + 1), new Float32Array([0, ...h]))
}
- o.setPeriodicWave(brightWave)
+ o.setPeriodicWave(waves[name])
}
// One tone. The defaults are every beep the app has always made: a sine that reaches 0.35 and
// fades from there at once. `peak`, `hold` (the share of the tone kept at its peak before the
-// fade) and `bright` exist for the timer chime below.
-const tone = (freq, dur, when, { peak = 0.35, hold = 0, bright = false } = {}) => {
+// fade), `timbre` (one of TIMBRES; `bright: true` is the chime's) and `glide` (a frequency the
+// tone slides to by its end, for the whistle) exist for the end-of-rest sounds below.
+const tone = (freq, dur, when, { peak = 0.35, hold = 0, bright = false, timbre = bright ? 'bright' : null, glide = 0 } = {}) => {
const ctx = wake()
const o = ctx.createOscillator(), g = ctx.createGain()
o.connect(g); g.connect(ctx.destination)
- o.frequency.value = freq
- if (bright) setBright(ctx, o); else o.type = 'sine'
+ if (timbre && TIMBRES[timbre]) setTimbre(ctx, o, timbre); else o.type = 'sine'
const t0 = ctx.currentTime + when
+ o.frequency.value = freq
+ if (glide > 0) { o.frequency.setValueAtTime(freq, t0); o.frequency.linearRampToValueAtTime(glide, t0 + dur) }
g.gain.setValueAtTime(0.001, t0)
g.gain.exponentialRampToValueAtTime(peak, t0 + 0.02)
if (hold > 0) g.gain.setValueAtTime(peak, t0 + dur * hold)
@@ -104,14 +112,23 @@ export function beep(enabled, freq, dur, when) {
// as the chime below, so both share one gating/try-catch and one sleepAfter bookkeeping.
// The Android app plays this end tone natively while the app is in the background or the screen
// is off (android/.../RestTone.java). Change the notes or the shape here, change them there too.
-export const CHIME_PEAK = 0.9
-const CHIME = [[1319, 0.16, 0], [988, 0.16, 0.22], [1319, 0.5, 0.44]]
-const CLASSIC = [[880, 0.15, 0], [880, 0.15, 0.25], [1320, 0.4, 0.5]]
-export function chime(enabled, classic) {
+//
+// Settings → Sound (#306) adds a few more to pick from. Each is notes of [freq, dur, when] (and a
+// frequency to glide to, for the whistle) played with one shape: a peak, a hold and a timbre.
+// Notes that overlap (the bell's ring, the soft one's) have peaks low enough that, decaying from
+// the first millisecond, they still stay under 1 when they add up. RestTone.java mirrors every
+// one of these, number for number. The table itself is lib/rest-sounds.js, which has no audio in
+// it, so the store and the native alarm can read the choice without this module.
+export { CHIME_PEAK, REST_SOUNDS, REST_SOUND_IDS, restSoundOf } from './rest-sounds.js'
+// `kind` is a REST_SOUNDS id; `true` (the old "classic" switch) still means the classic beeps.
+export function chime(enabled, kind) {
if (!enabled) return
+ const id = kind === true ? 'classic' : kind
+ const snd = Object.hasOwn(REST_SOUNDS, id) ? REST_SOUNDS[id] : REST_SOUNDS.chime
try {
- if (classic) CLASSIC.forEach(([freq, dur, when]) => tone(freq, dur, when))
- else CHIME.forEach(([freq, dur, when]) => tone(freq, dur, when, { peak: CHIME_PEAK, hold: 0.6, bright: true }))
+ for (const [freq, dur, when, glide] of snd.notes) {
+ tone(freq, dur, when, snd === REST_SOUNDS.classic ? {} : { peak: snd.peak, hold: snd.hold, timbre: snd.timbre, glide })
+ }
} catch (e) { /* */ }
}
diff --git a/frontend/src/lib/sound.test.js b/frontend/src/lib/sound.test.js
index bb6af59dd..348de62bf 100644
--- a/frontend/src/lib/sound.test.js
+++ b/frontend/src/lib/sound.test.js
@@ -30,7 +30,7 @@ class FakeCtx {
createOscillator() {
const ctx = this
const o = {
- frequency: { value: 0 }, type: '', wave: null, connect() {},
+ frequency: { value: 0, ramps: [], setValueAtTime() {}, linearRampToValueAtTime(v, at) { this.ramps.push([v, at]) } }, type: '', wave: null, connect() {},
setPeriodicWave(w) { o.wave = w },
start(at) { ctx.tones.push({ freq: o.frequency.value, at }); ctx.oscs.push(o); o.at = at },
stop(at) { o.until = at },
@@ -324,6 +324,81 @@ describe('chime(enabled, classic) — the original three beeps', () => {
})
})
+// #306: a few more end-of-rest sounds to pick from, each its own shape, none of them clipping.
+describe('the end-of-rest sounds (Settings → Sound)', () => {
+ const peakOf = events => Math.max(...events.map(([, v]) => v))
+ // The module keeps its context between sounds: start each one's record over.
+ const fresh = () => { const c = ctx(); if (c) { c.tones = []; c.gains = []; c.oscs = [] } }
+ // The loudest the notes of a sound can add up to, sampling each one's gain curve as Web Audio
+ // would run it: up from 0.001 in 20 ms, held, then down to 0.001 by the note's end.
+ const loudest = name => {
+ const { notes, peak = 0.35, hold = 0 } = sound.REST_SOUNDS[name]
+ const gain = (t, dur) => {
+ const end = Math.max(0.02, dur * hold)
+ if (t < 0 || t > dur) return 0
+ if (t < 0.02) return 0.001 * Math.pow(peak / 0.001, t / 0.02)
+ if (t < end) return peak
+ return peak * Math.pow(0.001 / peak, (t - end) / (dur - end))
+ }
+ let max = 0
+ for (let t = 0; t < 3; t += 0.001) max = Math.max(max, notes.reduce((a, [, dur, when]) => a + gain(t - when, dur), 0))
+ return max
+ }
+
+ it('offers the chime, the classic beeps and four more, each sounding different', () => {
+ expect(sound.REST_SOUND_IDS).toEqual(['chime', 'classic', 'bell', 'beep', 'whistle', 'soft'])
+ const shapes = new Set()
+ for (const id of sound.REST_SOUND_IDS) {
+ fresh()
+ sound.chime(true, id)
+ shapes.add(JSON.stringify(ctx().tones))
+ }
+ expect(shapes.size).toBe(sound.REST_SOUND_IDS.length)
+ })
+
+ it('never adds up past the point where the output clips', () => {
+ for (const id of sound.REST_SOUND_IDS) expect(loudest(id), id).toBeLessThanOrEqual(1)
+ })
+
+ it('plays each note at its own peak, in its own timbre', () => {
+ sound.chime(true, 'bell')
+ expect(ctx().gains.map(peakOf)).toEqual([0.55, 0.55])
+ expect(ctx().oscs.every(o => o.wave && o.wave.imag[3] === 0.5)).toBe(true) // the bell's strong 3rd
+ fresh()
+ sound.chime(true, 'soft')
+ expect(ctx().oscs.every(o => o.type === 'sine')).toBe(true)
+ expect(Math.max(...ctx().gains.map(peakOf))).toBeLessThan(sound.CHIME_PEAK / 2)
+ })
+
+ it('glides the whistle upwards, and nothing else', () => {
+ sound.chime(true, 'whistle')
+ expect(ctx().oscs.map(o => o.frequency.ramps.map(([v]) => v))).toEqual([[2100], [2500]])
+ fresh()
+ sound.chime(true, 'bell')
+ expect(ctx().oscs.every(o => !o.frequency.ramps.length)).toBe(true)
+ })
+
+ it('falls back to the chime for a name it does not know, and true still means classic', () => {
+ sound.chime(true, 'kazoo')
+ expect(ctx().tones.map(tn => tn.freq)).toEqual([1319, 988, 1319])
+ fresh()
+ sound.chime(true, true)
+ expect(ctx().tones.map(tn => tn.freq)).toEqual([880, 880, 1320])
+ })
+
+ it('reads the profile\'s pick, with the old classic switch and an older app\'s later choice', () => {
+ expect(sound.restSoundOf({})).toBe('chime')
+ expect(sound.restSoundOf(undefined)).toBe('chime')
+ expect(sound.restSoundOf({ restSound: 'bell' })).toBe('bell')
+ expect(sound.restSoundOf({ restSound: 'kazoo' })).toBe('chime')
+ expect(sound.restSoundOf({ classicChime: true })).toBe('classic')
+ // an older app switched to Classic after this one picked the bell: classic it is
+ expect(sound.restSoundOf({ restSound: 'bell', classicChime: true })).toBe('classic')
+ // an older app switched Classic off again: back to the chime, not classic
+ expect(sound.restSoundOf({ restSound: 'classic', classicChime: false })).toBe('chime')
+ })
+})
+
// Discord (asierlama): vibration on or off on its own, the way sound is.
describe('vibrate switch', () => {
let calls
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 8006d220f..8a41f45e1 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -2224,4 +2224,14 @@ export default {
'Remove note': 'إزالة الملاحظة',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'الحياة تحدث. اترك لنفسك ملاحظة، وسيترك تذكير الأيام الفائتة هذا اليوم وشأنه.',
'Anything else? (optional)': 'أي شيء آخر؟ (اختياري)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'جرس',
+ 'Beep-beep': 'بيب-بيب',
+ 'Whistle': 'صفارة',
+ 'Soft': 'هادئ',
+ 'Tap one to hear it.': 'اضغط على أحدها لتسمعه.',
+ 'Ding-dong. Rest is over, class is in.': 'دينغ-دونغ. انتهت الراحة، عُد إلى التمرين.',
+ 'Your sports watch, calling you back.': 'ساعتك الرياضية تناديك للعودة.',
+ 'Coach wants you back on the bar.': 'المدرب يريدك أن تعود إلى البار.',
+ 'Gentle, for headphones or a quiet room.': 'هادئ، للسماعات أو لغرفة هادئة.',
}
diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.js
index acb212c24..d028c1fd5 100644
--- a/frontend/src/locales/bn.js
+++ b/frontend/src/locales/bn.js
@@ -2248,4 +2248,14 @@ export default {
'Remove note': 'নোট সরান',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'জীবনে এমন হয়। নিজের জন্য একটি নোট রাখুন, আর মিস করা দিনের রিমাইন্ডার এই দিনটিকে ছেড়ে দেবে।',
'Anything else? (optional)': 'আর কিছু? (ঐচ্ছিক)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'ঘণ্টা',
+ 'Beep-beep': 'বিপ-বিপ',
+ 'Whistle': 'বাঁশি',
+ 'Soft': 'নরম',
+ 'Tap one to hear it.': 'শুনতে যেকোনো একটিতে ট্যাপ করুন।',
+ 'Ding-dong. Rest is over, class is in.': 'ডিং-ডং। বিশ্রাম শেষ, আবার কাজে।',
+ 'Your sports watch, calling you back.': 'আপনার স্পোর্টস ঘড়ি আপনাকে ফিরে ডাকছে।',
+ 'Coach wants you back on the bar.': 'কোচ আপনাকে আবার বারে চান।',
+ 'Gentle, for headphones or a quiet room.': 'মৃদু, হেডফোন বা শান্ত ঘরের জন্য।',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index eda15e5da..e83ed35b0 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -2189,4 +2189,14 @@ export default {
'Remove note': 'Notiz entfernen',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'Das Leben passiert. Hinterlass dir eine Notiz, und die Erinnerung an verpasste Tage lässt diesen hier in Ruhe.',
'Anything else? (optional)': 'Sonst noch was? (optional)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Glocke',
+ 'Beep-beep': 'Piep-piep',
+ 'Whistle': 'Pfeife',
+ 'Soft': 'Sanft',
+ 'Tap one to hear it.': 'Tippe auf einen, um ihn zu hören.',
+ 'Ding-dong. Rest is over, class is in.': 'Ding-dong. Pause vorbei, weiter geht’s.',
+ 'Your sports watch, calling you back.': 'Deine Sportuhr ruft dich zurück.',
+ 'Coach wants you back on the bar.': 'Der Coach will dich zurück an der Stange.',
+ 'Gentle, for headphones or a quiet room.': 'Leise, für Kopfhörer oder einen ruhigen Raum.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index ef22a5bee..4d09d11b2 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -2169,4 +2169,14 @@ export default {
'Remove note': 'Eliminar nota',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'La vida pasa. Déjate una nota y el aviso de días perdidos dejará este en paz.',
'Anything else? (optional)': '¿Algo más? (opcional)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Campana',
+ 'Beep-beep': 'Bip-bip',
+ 'Whistle': 'Silbato',
+ 'Soft': 'Suave',
+ 'Tap one to hear it.': 'Toca uno para escucharlo.',
+ 'Ding-dong. Rest is over, class is in.': 'Din-don. Se acabó el descanso, a clase.',
+ 'Your sports watch, calling you back.': 'Tu reloj deportivo te llama de vuelta.',
+ 'Coach wants you back on the bar.': 'El coach te quiere de vuelta en la barra.',
+ 'Gentle, for headphones or a quiet room.': 'Suave, para auriculares o una sala tranquila.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 5302677ff..997ac9bf1 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -2169,4 +2169,14 @@ export default {
'Remove note': 'Supprimer la note',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'La vie, ça arrive. Laisse-toi une note, et le rappel des jours manqués laissera celui-ci tranquille.',
'Anything else? (optional)': 'Autre chose ? (facultatif)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Cloche',
+ 'Beep-beep': 'Bip-bip',
+ 'Whistle': 'Sifflet',
+ 'Soft': 'Doux',
+ 'Tap one to hear it.': 'Touche-en un pour l’écouter.',
+ 'Ding-dong. Rest is over, class is in.': 'Ding-dong. Fin de la pause, au boulot.',
+ 'Your sports watch, calling you back.': 'Ta montre de sport te rappelle.',
+ 'Coach wants you back on the bar.': 'Le coach te veut de retour à la barre.',
+ 'Gentle, for headphones or a quiet room.': 'Tout doux, pour un casque ou une pièce calme.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index c7e6cdfcb..f014a476a 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -2169,4 +2169,14 @@ export default {
'Remove note': 'नोट हटाएँ',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'ज़िंदगी है, होता है। अपने लिए एक नोट छोड़ दें, और छूटे दिन की याद दिलाने वाला इस दिन को छोड़ देगा।',
'Anything else? (optional)': 'और कुछ? (वैकल्पिक)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'घंटी',
+ 'Beep-beep': 'बीप-बीप',
+ 'Whistle': 'सीटी',
+ 'Soft': 'हल्की',
+ 'Tap one to hear it.': 'सुनने के लिए किसी एक पर टैप करें।',
+ 'Ding-dong. Rest is over, class is in.': 'डिंग-डॉन्ग। आराम ख़त्म, फिर से काम पर।',
+ 'Your sports watch, calling you back.': 'आपकी स्पोर्ट्स घड़ी आपको वापस बुला रही है।',
+ 'Coach wants you back on the bar.': 'कोच आपको बार पर वापस चाहते हैं।',
+ 'Gentle, for headphones or a quiet room.': 'धीमी, हेडफ़ोन या शांत कमरे के लिए।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index efe05c06f..8dd6238e8 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -2172,4 +2172,14 @@ export default {
'Remove note': 'Jegyzet törlése',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'Az élet közbeszól. Hagyj magadnak egy jegyzetet, és a kihagyott napok emlékeztetője ezt a napot békén hagyja.',
'Anything else? (optional)': 'Még valami? (nem kötelező)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Harang',
+ 'Beep-beep': 'Bip-bip',
+ 'Whistle': 'Síp',
+ 'Soft': 'Lágy',
+ 'Tap one to hear it.': 'Koppints egyre, hogy meghalld.',
+ 'Ding-dong. Rest is over, class is in.': 'Ding-dong. Vége a pihenőnek, vissza a munkához.',
+ 'Your sports watch, calling you back.': 'A sportórád visszahív.',
+ 'Coach wants you back on the bar.': 'Az edző visszavár a rúdhoz.',
+ 'Gentle, for headphones or a quiet room.': 'Halk, fülhallgatóhoz vagy csendes helyre.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 24f25bb34..ae6cab735 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -2169,4 +2169,14 @@ export default {
'Remove note': 'Rimuovi nota',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'Capita. Lasciati una nota e il promemoria dei giorni saltati lascerà stare questo.',
'Anything else? (optional)': 'Altro? (facoltativo)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Campana',
+ 'Beep-beep': 'Bip-bip',
+ 'Whistle': 'Fischietto',
+ 'Soft': 'Delicato',
+ 'Tap one to hear it.': 'Toccane uno per sentirlo.',
+ 'Ding-dong. Rest is over, class is in.': 'Din-don. Pausa finita, si torna in classe.',
+ 'Your sports watch, calling you back.': 'Il tuo orologio sportivo ti richiama.',
+ 'Coach wants you back on the bar.': 'Il coach ti vuole di nuovo al bilanciere.',
+ 'Gentle, for headphones or a quiet room.': 'Delicato, per le cuffie o una stanza silenziosa.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index fba6262cf..6c24518ea 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -2169,4 +2169,14 @@ export default {
'Remove note': '메모 삭제',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': '그런 날도 있죠. 메모를 남겨 두면 놓친 날 알림이 이 날은 그냥 넘어가요.',
'Anything else? (optional)': '더 남길 말이 있나요? (선택)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': '종소리',
+ 'Beep-beep': '삐삐',
+ 'Whistle': '호루라기',
+ 'Soft': '부드럽게',
+ 'Tap one to hear it.': '탭하면 들어볼 수 있어요.',
+ 'Ding-dong. Rest is over, class is in.': '딩동. 휴식 끝, 다시 시작해요.',
+ 'Your sports watch, calling you back.': '스포츠 시계가 다시 부르고 있어요.',
+ 'Coach wants you back on the bar.': '코치가 바 앞으로 돌아오래요.',
+ 'Gentle, for headphones or a quiet room.': '이어폰이나 조용한 곳에 어울려요.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 3a84389db..b066d9fb8 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -2169,4 +2169,14 @@ export default {
'Remove note': 'Usuń notatkę',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'Życie się zdarza. Zostaw sobie notatkę, a przypomnienie o pominiętych dniach odpuści ten dzień.',
'Anything else? (optional)': 'Coś jeszcze? (opcjonalnie)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Dzwonek',
+ 'Beep-beep': 'Pip-pip',
+ 'Whistle': 'Gwizdek',
+ 'Soft': 'Delikatny',
+ 'Tap one to hear it.': 'Dotknij, aby posłuchać.',
+ 'Ding-dong. Rest is over, class is in.': 'Ding-dong. Koniec przerwy, wracamy do pracy.',
+ 'Your sports watch, calling you back.': 'Zegarek sportowy wzywa z powrotem.',
+ 'Coach wants you back on the bar.': 'Trener czeka przy sztandze.',
+ 'Gentle, for headphones or a quiet room.': 'Cichy, do słuchawek albo spokojnego pomieszczenia.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index a91da25bf..aeb7a7cf7 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1342,6 +1342,16 @@ export const PT_BR_OVERRIDES = {
'Remove note': 'Remover anotação',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'A vida acontece. Deixe uma anotação e o lembrete de dias perdidos deixa este em paz.',
'Anything else? (optional)': 'Mais alguma coisa? (opcional)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Sino',
+ 'Beep-beep': 'Bip-bip',
+ 'Whistle': 'Apito',
+ 'Soft': 'Suave',
+ 'Tap one to hear it.': 'Toque em um para ouvir.',
+ 'Ding-dong. Rest is over, class is in.': 'Ding-dong. Acabou o descanso, de volta ao treino.',
+ 'Your sports watch, calling you back.': 'Seu relógio esportivo chamando você de volta.',
+ 'Coach wants you back on the bar.': 'O coach quer você de volta na barra.',
+ 'Gentle, for headphones or a quiet room.': 'Suave, para fones de ouvido ou um lugar silencioso.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 9922f160b..5a99fc36c 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -2169,4 +2169,14 @@ export default {
'Remove note': 'Remover nota',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'A vida acontece. Deixa-te uma nota e o lembrete de dias falhados deixa este em paz.',
'Anything else? (optional)': 'Mais alguma coisa? (opcional)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Sino',
+ 'Beep-beep': 'Bip-bip',
+ 'Whistle': 'Apito',
+ 'Soft': 'Suave',
+ 'Tap one to hear it.': 'Toca num para o ouvir.',
+ 'Ding-dong. Rest is over, class is in.': 'Ding-dong. Acabou o descanso, toca a trabalhar.',
+ 'Your sports watch, calling you back.': 'O teu relógio desportivo a chamar-te de volta.',
+ 'Coach wants you back on the bar.': 'O coach quer-te de volta à barra.',
+ 'Gentle, for headphones or a quiet room.': 'Suave, para auscultadores ou uma sala sossegada.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 0ee130f92..257faf8f8 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -2173,4 +2173,14 @@ export default {
'Remove note': 'Удалить заметку',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'Всякое бывает. Оставьте себе заметку, и напоминание о пропущенных днях оставит этот день в покое.',
'Anything else? (optional)': 'Что-нибудь ещё? (необязательно)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Колокол',
+ 'Beep-beep': 'Бип-бип',
+ 'Whistle': 'Свисток',
+ 'Soft': 'Мягкий',
+ 'Tap one to hear it.': 'Нажмите, чтобы послушать.',
+ 'Ding-dong. Rest is over, class is in.': 'Динь-дон. Отдых окончен, за работу.',
+ 'Your sports watch, calling you back.': 'Ваши спортивные часы зовут вас обратно.',
+ 'Coach wants you back on the bar.': 'Тренер ждёт вас обратно у штанги.',
+ 'Gentle, for headphones or a quiet room.': 'Тихий, для наушников или спокойного зала.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index ef31937ff..11a69c41c 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -2180,4 +2180,14 @@ export default {
'Remove note': 'ลบบันทึก',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'ชีวิตก็แบบนี้ ทิ้งบันทึกไว้ให้ตัวเอง แล้วการเตือนวันที่พลาดจะปล่อยวันนี้ไป',
'Anything else? (optional)': 'มีอะไรอีกไหม (ไม่บังคับ)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'ระฆัง',
+ 'Beep-beep': 'บี๊บ-บี๊บ',
+ 'Whistle': 'นกหวีด',
+ 'Soft': 'นุ่มนวล',
+ 'Tap one to hear it.': 'แตะเพื่อฟังเสียง',
+ 'Ding-dong. Rest is over, class is in.': 'ติ๊ง-ต่อง หมดเวลาพัก กลับไปลุยกัน',
+ 'Your sports watch, calling you back.': 'นาฬิกาสปอร์ตเรียกคุณกลับมาแล้ว',
+ 'Coach wants you back on the bar.': 'โค้ชอยากให้คุณกลับมาที่บาร์',
+ 'Gentle, for headphones or a quiet room.': 'เบา ๆ สำหรับหูฟังหรือห้องที่เงียบ',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index b097beaee..5a7fbb814 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -2169,4 +2169,14 @@ export default {
'Remove note': 'Notu sil',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'Hayat bu. Kendine bir not bırak, kaçırılan gün hatırlatıcısı bu günü rahat bıraksın.',
'Anything else? (optional)': 'Başka bir şey? (isteğe bağlı)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Zil',
+ 'Beep-beep': 'Bip-bip',
+ 'Whistle': 'Düdük',
+ 'Soft': 'Yumuşak',
+ 'Tap one to hear it.': 'Dinlemek için birine dokun.',
+ 'Ding-dong. Rest is over, class is in.': 'Ding-dong. Mola bitti, iş başına.',
+ 'Your sports watch, calling you back.': 'Spor saatin seni geri çağırıyor.',
+ 'Coach wants you back on the bar.': 'Koç seni bara geri bekliyor.',
+ 'Gentle, for headphones or a quiet room.': 'Sakin, kulaklık ya da sessiz bir oda için.',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index dc5222054..c782f6b43 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -2166,4 +2166,14 @@ export default {
'Remove note': 'Видалити нотатку',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': 'Всяке буває. Залиште собі нотатку, і нагадування про пропущені дні дасть цьому дню спокій.',
'Anything else? (optional)': 'Щось іще? (необов’язково)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': 'Дзвін',
+ 'Beep-beep': 'Біп-біп',
+ 'Whistle': 'Свисток',
+ 'Soft': 'М’який',
+ 'Tap one to hear it.': 'Торкніться, щоб послухати.',
+ 'Ding-dong. Rest is over, class is in.': 'Дзень-дзелень. Відпочинок скінчився, до роботи.',
+ 'Your sports watch, calling you back.': 'Ваш спортивний годинник кличе вас назад.',
+ 'Coach wants you back on the bar.': 'Тренер чекає вас назад біля штанги.',
+ 'Gentle, for headphones or a quiet room.': 'Тихий, для навушників або спокійної кімнати.',
}
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index bccd87dff..bb6a19cc7 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -2162,4 +2162,14 @@ export default {
'Remove note': '刪除備註',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': '生活總有意外。給自己留個備註,錯過訓練的提醒就會放過這一天。',
'Anything else? (optional)': '還有別的嗎?(選填)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': '鈴聲',
+ 'Beep-beep': '嗶嗶',
+ 'Whistle': '哨子',
+ 'Soft': '柔和',
+ 'Tap one to hear it.': '點一下就能試聽。',
+ 'Ding-dong. Rest is over, class is in.': '叮咚。休息結束,回來上課。',
+ 'Your sports watch, calling you back.': '你的運動手錶在叫你回來。',
+ 'Coach wants you back on the bar.': '教練等你回到槓鈴前。',
+ 'Gentle, for headphones or a quiet room.': '輕柔,適合耳機或安靜的房間。',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index b8cb04486..1301897bd 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -2169,4 +2169,14 @@ export default {
'Remove note': '删除备注',
'Life happens. Leave yourself a note, and the missed-day nudge lets this one go.': '生活总有意外。给自己留个备注,错过训练的提醒就会放过这一天。',
'Anything else? (optional)': '还有别的吗?(可选)',
+ // --- rest-end sounds (#306) ---
+ 'Bell': '铃声',
+ 'Beep-beep': '哔哔',
+ 'Whistle': '哨子',
+ 'Soft': '柔和',
+ 'Tap one to hear it.': '点一下就能试听。',
+ 'Ding-dong. Rest is over, class is in.': '叮咚。休息结束,回来上课。',
+ 'Your sports watch, calling you back.': '你的运动手表在叫你回来。',
+ 'Coach wants you back on the bar.': '教练等你回到杠铃前。',
+ 'Gentle, for headphones or a quiet room.': '轻柔,适合耳机或安静的房间。',
}
diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.js
index fab0fc9c0..59489f8c1 100644
--- a/frontend/src/store/useUI.js
+++ b/frontend/src/store/useUI.js
@@ -1,6 +1,7 @@
import { create } from 'zustand'
import { uid } from '../lib/format.js'
import { beep, chime, vibrate, alertBuzz } from '../lib/sound.js'
+import { restSoundOf } from '../lib/rest-sounds.js'
import { api } from '../lib/api.js'
import { t } from '../lib/i18n.js'
import { deviceId } from '../lib/push.js'
@@ -26,7 +27,7 @@ const bookRestEnd = (endsAt, totalSec, kind) => {
const switching = kind === 'switch'
if (!MOBILE) { if (!switching) pushRestTimer(Math.max(1, Math.round((endsAt - Date.now()) / 1000))); return }
const { S } = useStore.getState()
- armRestAlert(endsAt, { title: switching ? t('Switch sides') : t('Rest’s over. Next set!'), countdownTitle: switching ? t('Switch sides') : t('Rest'), totalSec, accent: accentValue(S), sound: !!S.sound, classic: S.classicChime === true, vibrate: S.vibrate !== false, alarmBuzz: S.vibrate !== false && !!S.vibrateOnSilent })
+ armRestAlert(endsAt, { title: switching ? t('Switch sides') : t('Rest’s over. Next set!'), countdownTitle: switching ? t('Switch sides') : t('Rest'), totalSec, accent: accentValue(S), sound: !!S.sound, classic: restSoundOf(S) === 'classic', tone: restSoundOf(S), vibrate: S.vibrate !== false, alarmBuzz: S.vibrate !== false && !!S.vibrateOnSilent })
.then(ok => {
// Only for the rest that asked: one skipped or moved since then has booked its own end.
const tm = useUI.getState().timer
@@ -105,10 +106,11 @@ const runWork = (set, get) => {
const seenLive = !document.hidden && pageHiddenAt === null
if (!document.hidden) pageHiddenAt = null
if (left === wk.left) return
- const { sound: snd, classicChime } = useStore.getState().S
+ const { S: st } = useStore.getState()
+ const snd = st.sound, endSound = restSoundOf(st)
if (left <= 0) {
if (seenLive && !wk.alerted) {
- chime(snd, classicChime)
+ chime(snd, endSound)
alertBuzz([200, 100, 200]); get().flashTimer()
}
if (wk.overtime && left > -MAX_WORK_OVERTIME_SEC) { set({ work: { ...wk, left, alerted: true } }); return }
@@ -167,11 +169,12 @@ const runRest = (set, get) => {
const seenLive = !document.hidden && pageHiddenAt === null
if (!document.hidden) pageHiddenAt = null
if (left === tm.left) return
- const { sound: snd, classicChime } = useStore.getState().S
+ const { S: st } = useStore.getState()
+ const snd = st.sound, endSound = restSoundOf(st)
if (left <= 0 && tm.kind === 'switch') {
// Over like a hold is: the chime and its buzz, then the bar goes. No "Ready", no toast:
// the other side is the next thing, one tap away.
- if (seenLive) { chime(snd, classicChime); alertBuzz([200, 100, 200]); get().flashTimer() }
+ if (seenLive) { chime(snd, endSound); alertBuzz([200, 100, 200]); get().flashTimer() }
stopRestTicking()
set({ timer: null })
return
@@ -180,7 +183,7 @@ const runRest = (set, get) => {
if (seenLive) {
// The Android alarm for this end stays quiet while the app is on screen, so this chime is
// the only one. Locked, this branch never runs and the alarm's tone does.
- chime(snd, classicChime)
+ chime(snd, endSound)
alertBuzz([200, 100, 200]); get().flashTimer()
}
// The toast stays even when the rest ran out while the app was hidden: a guest, or anyone
diff --git a/frontend/src/store/useUI.silent-buzz.test.js b/frontend/src/store/useUI.silent-buzz.test.js
index e54852b78..defbae136 100644
--- a/frontend/src/store/useUI.silent-buzz.test.js
+++ b/frontend/src/store/useUI.silent-buzz.test.js
@@ -18,14 +18,14 @@ vi.mock('../lib/api.js', () => ({ api: vi.fn(() => Promise.resolve({ ok: true })
import { useUI } from './useUI.js'
import { useStore } from './useStore.js'
import { armRestAlert } from '../lib/rest-alert.js'
-import { alertBuzz, vibrate } from '../lib/sound.js'
+import { alertBuzz, chime, vibrate } from '../lib/sound.js'
let original
beforeEach(() => {
vi.useFakeTimers()
original = useStore.getState().S
useUI.setState({ timer: null, timerFlashId: 0 })
- for (const f of [armRestAlert, alertBuzz, vibrate]) f.mockClear()
+ for (const f of [armRestAlert, alertBuzz, chime, vibrate]) f.mockClear()
Object.defineProperty(document, 'hidden', { configurable: true, get: () => false })
})
afterEach(() => {
@@ -58,7 +58,18 @@ describe('vibrate on silent', () => {
expect(armRestAlert).toHaveBeenLastCalledWith(expect.any(Number), expect.objectContaining({ sound: true, classic: false }))
withSettings({ sound: true, classicChime: true })
useUI.getState().startRest(60)
- expect(armRestAlert).toHaveBeenLastCalledWith(expect.any(Number), expect.objectContaining({ sound: true, classic: true }))
+ expect(armRestAlert).toHaveBeenLastCalledWith(expect.any(Number), expect.objectContaining({ sound: true, classic: true, tone: 'classic' }))
+ withSettings({ sound: true, restSound: 'bell' })
+ useUI.getState().startRest(60)
+ expect(armRestAlert).toHaveBeenLastCalledWith(expect.any(Number), expect.objectContaining({ sound: true, classic: false, tone: 'bell' }))
+ })
+
+ // #306: the page plays the picked sound too, on screen, at the end of a rest.
+ it('chimes the sound Settings → Sound picked', async () => {
+ withSettings({ sound: true, restSound: 'soft' })
+ useUI.getState().startRest(2)
+ await vi.advanceTimersByTimeAsync(3000)
+ expect(chime).toHaveBeenCalledWith(true, 'soft')
})
it('the end of a rest seen on screen buzzes through alertBuzz', async () => {
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index f2eb01a06..7fc7b5bd3 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -11,7 +11,8 @@ import { ACCENTS, ACCENT_NAMES, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY,
import { inventoryFor, ownsPlates } from '../lib/plates.js'
import { effortOf } from '../lib/history.js'
import { figureOf } from '../lib/exercises.js'
-import { unlock, playOnSilentSupported, vibrateSupported, appleTouchDevice } from '../lib/sound.js'
+import { unlock, chime, playOnSilentSupported, vibrateSupported, appleTouchDevice } from '../lib/sound.js'
+import { REST_SOUND_IDS, restSoundOf } from '../lib/rest-sounds.js'
import { scheduleModeOf, chooseFixedWeek, chooseRotation } from '../lib/rotation.js'
import { queueOf } from '../lib/queue.js'
import { api, webauthnOK, passkeyRegister, passkeyError, IS_ANDROID } from '../lib/api.js'
@@ -566,14 +567,10 @@ export default function Settings({ page = null, find = null, via = null }) {
</Row>
{/* The chime that replaced the original three beeps (Discord: "too quiet under music")
is not an improvement for everyone: louder is a cost with headphones or in a quiet
- room. The chime by default; Classic brings the original back unchanged
- (lib/sound.js's CLASSIC). Stored as S.classicChime, as before. */}
- {S.sound && <SelectRow icon="speaker" iconTint="var(--pink)" title={t('Sound')}
- value={S.classicChime ? 'classic' : 'chime'} onChange={v => update(s => { s.classicChime = v === 'classic' })}
- options={[
- { value: 'chime', label: t('Chime (louder)') },
- { value: 'classic', label: t('Classic beeps'), subtitle: t('The quieter three-beep sound from before 1.3.9, instead of the louder chime.') },
- ]} />}
+ room, and some want a sound that feels like theirs (#306). The chime by default; the
+ sheet plays each one as you tap it (restSoundSheet). */}
+ {S.sound && <Row icon="speaker" iconTint="var(--pink)" title={t('Sound')} value={t(REST_SOUND_LABEL[restSoundOf(S)])}
+ accessory="chevron" onClick={restSoundSheet} />}
{/* iOS only (WebKit's audio-session API, iOS 17+): with it off the ring/silent switch
mutes the timer. On, the phone treats the timer like a music player (exclusive, and
the music app is not told it may resume), so it is a choice, off by default. */}
@@ -1002,6 +999,39 @@ const DownloadProgress = forwardRef(function DownloadProgress(_, ref) {
)
})
+// Settings → Sound (#306): every end-of-rest sound, each played as it is picked so you hear it
+// before the next rest does. The sheet stays open for the next one; Done closes it. Stored as
+// S.restSound, with S.classicChime kept for an app from before (lib/rest-sounds.js restSoundOf).
+const REST_SOUND_LABEL = { chime: 'Chime (louder)', classic: 'Classic beeps', bell: 'Bell', beep: 'Beep-beep', whistle: 'Whistle', soft: 'Soft' }
+const REST_SOUND_HINT = {
+ classic: 'The quieter three-beep sound from before 1.3.9, instead of the louder chime.',
+ bell: 'Ding-dong. Rest is over, class is in.',
+ beep: 'Your sports watch, calling you back.',
+ whistle: 'Coach wants you back on the bar.',
+ soft: 'Gentle, for headphones or a quiet room.',
+}
+export function pickRestSound(id) {
+ unlock(true)
+ useStore.getState().update(s => { s.restSound = id; s.classicChime = id === 'classic' })
+ chime(true, id)
+}
+export function RestSoundSheet({ close }) {
+ const S = useStore(s => s.S)
+ const cur = restSoundOf(S)
+ return <>
+ <h3>{t('Sound')}</h3>
+ <div className="muted small" style={{ marginBottom: 12 }}>{t('Tap one to hear it.')}</div>
+ <Section>
+ {REST_SOUND_IDS.map(id => <Row key={id} icon={id === cur ? 'speaker' : 'play'} iconTint="var(--pink)" title={t(REST_SOUND_LABEL[id])}
+ subtitle={REST_SOUND_HINT[id] ? t(REST_SOUND_HINT[id]) : null} accessory={id === cur ? 'check' : 'none'}
+ onClick={() => pickRestSound(id)} />)}
+ </Section>
+ <div style={{ height: 14 }} />
+ <Button variant="primary" onClick={close}>{t('Done')}</Button>
+ </>
+}
+const restSoundSheet = () => useUI.getState().openSheet(close => <RestSoundSheet close={close} />)
+
function effortHelpSheet() {
useUI.getState().openSheet(close => <>
<h3>{t('Effort per set')}</h3>
diff --git a/frontend/src/views/Settings.sound.test.jsx b/frontend/src/views/Settings.sound.test.jsx
index ceff2d2ed..05ede6e60 100644
--- a/frontend/src/views/Settings.sound.test.jsx
+++ b/frontend/src/views/Settings.sound.test.jsx
@@ -2,8 +2,8 @@
import React, { act } from 'react'
import { createRoot } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import Settings from './Settings.jsx'
-import { unlock } from '../lib/sound.js'
+import Settings, { RestSoundSheet } from './Settings.jsx'
+import { chime, unlock } from '../lib/sound.js'
globalThis.IS_REACT_ACT_ENVIRONMENT = true
@@ -49,7 +49,7 @@ vi.mock('../sheets.jsx', () => ({
// unlock is spied on so the Sounds switch can be checked for its tap-time side effect.
vi.mock('../lib/sound.js', async importOriginal => {
const real = await importOriginal()
- return { ...real, unlock: vi.fn() }
+ return { ...real, unlock: vi.fn(), chime: vi.fn() }
})
globalThis.__APP_VERSION__ ??= 'test'
@@ -64,6 +64,7 @@ beforeEach(() => {
setAudioSession({ type: 'auto' })
Object.defineProperty(navigator, 'userAgent', { value: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148', configurable: true })
unlock.mockClear()
+ chime.mockClear()
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
@@ -211,4 +212,42 @@ describe('Settings — which sound', () => {
mount()
expect(rowTitled('Sound')).toBeUndefined()
})
+
+ // #306: a few sounds to pick from, each heard as it is picked.
+ it('names the picked sound on the row; an older app\'s classic switch still reads as Classic', () => {
+ mocks.S.restSound = 'whistle'
+ mount()
+ expect(rowTitled('Sound').querySelector('.lrow-v').textContent).toBe('Whistle')
+ mocks.S.classicChime = true
+ mount()
+ expect(rowTitled('Sound').querySelector('.lrow-v').textContent).toBe('Classic beeps')
+ })
+
+ it('the sheet lists every sound, ticks the current one, and plays and stores each one tapped', () => {
+ const close = vi.fn()
+ // the mocked store does not re-render on its own: render again to read the new tick
+ const render = () => act(() => root.render(<RestSoundSheet close={close} />))
+ render()
+ expect([...host.querySelectorAll('.lrow-t')].map(e => e.textContent)).toEqual(['Chime (louder)', 'Classic beeps', 'Bell', 'Beep-beep', 'Whistle', 'Soft'])
+ expect(rowTitled('Chime (louder)').querySelector('.lrow-k')).toBeTruthy()
+
+ act(() => { rowTitled('Bell').click() })
+ expect(mocks.S).toMatchObject({ restSound: 'bell', classicChime: false })
+ expect(chime).toHaveBeenLastCalledWith(true, 'bell')
+ expect(unlock).toHaveBeenCalled()
+ render()
+ expect(rowTitled('Bell').querySelector('.lrow-k')).toBeTruthy()
+ expect(rowTitled('Chime (louder)').querySelector('.lrow-k')).toBeNull()
+ expect(close).not.toHaveBeenCalled()
+
+ // Classic keeps the old switch in step, so an app from before #306 plays it too
+ act(() => { rowTitled('Classic beeps').click() })
+ expect(mocks.S).toMatchObject({ restSound: 'classic', classicChime: true })
+ expect(chime).toHaveBeenLastCalledWith(true, 'classic')
+ act(() => { rowTitled('Soft').click() })
+ expect(mocks.S).toMatchObject({ restSound: 'soft', classicChime: false })
+
+ act(() => { [...host.querySelectorAll('button')].find(b => b.textContent === 'Done').click() })
+ expect(close).toHaveBeenCalled()
+ })
})
diff --git a/frontend/src/views/settings-pages.js b/frontend/src/views/settings-pages.js
index c1cc04c49..2ec53ef9e 100644
--- a/frontend/src/views/settings-pages.js
+++ b/frontend/src/views/settings-pages.js
@@ -70,7 +70,7 @@ export const SEARCH = [
{ page: 'advanced', title: 'Move, swap and remove buttons below the exercise', icon: 'swap', tint: 'var(--teal)', kw: 'move swap remove replace workout controls' },
// Timer alerts
{ page: 'alerts', title: 'Play a sound', icon: 'speaker', tint: 'var(--pink)', kw: 'sound sounds audio beep chime volume' },
- { page: 'alerts', title: 'Sound', icon: 'bell', tint: 'var(--pink)', kw: 'classic timer sound beep chime tone', opts: ['Chime (louder)', 'Classic beeps'], when: c => c.sound },
+ { page: 'alerts', title: 'Sound', icon: 'bell', tint: 'var(--pink)', kw: 'classic timer sound beep chime tone bell whistle soft ringtone custom rest end', opts: ['Chime (louder)', 'Classic beeps', 'Bell', 'Beep-beep', 'Whistle', 'Soft'], when: c => c.sound },
{ page: 'alerts', title: 'Play even on silent', icon: 'speaker', tint: 'var(--orange)', kw: 'silent mute ring switch iphone music', when: c => c.sound && c.playOnSilent },
{ page: 'alerts', title: 'Vibrate', icon: 'vibrate', tint: 'var(--indigo)', kw: 'vibrate vibration haptic haptics buzz' },
{ page: 'alerts', title: 'Vibrate on silent too', icon: 'vibrate', tint: 'var(--indigo)', kw: 'alarm silent vibrate android', when: c => c.mobile && c.android && c.canVibrate && c.vibrate },