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.

Accent: a colour of your own can be the accent, checked and made readable per theme

Duarte Santose492552beed6
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 1f4b73eec..b31cb0c89 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -3,7 +3,8 @@ import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation, useNavig
import { useStore } from './store/useStore.js'
import { useUI } from './store/useUI.js'
import { bindUI } from './components/ui.jsx'
-import { ACCENTS, setWeightDecimals } from './lib/format.js'
+import { setWeightDecimals } from './lib/format.js'
+import { accentValue, applyAccent } from './lib/accent.js'
import { setLang, useLang, baseLang } from './lib/i18n.js'
import { effectiveLang } from './lib/default-lang.js'
import { setPlayOnSilent, setVibrate, setAlarmBuzzer } from './lib/sound.js'
@@ -58,7 +59,7 @@ const resolveTheme = theme => theme === 'light' || theme === 'dark'
function applyPrefs(theme, accent) {
const de = document.documentElement
de.dataset.theme = resolveTheme(theme)
- de.dataset.accent = ACCENTS[accent] ? accent : 'lime'
+ applyAccent(de, accent, de.dataset.theme)
const meta = document.querySelector('meta[name="theme-color"]')
if (meta) meta.content = de.dataset.theme === 'light' ? '#f2f2f7' : '#000000'
if (MOBILE) setSystemBarsLight(de.dataset.theme === 'light')
@@ -94,17 +95,19 @@ function Shell() {
navigate('/workout', { replace: true })
exitWorkoutEdit(() => navigate(destination, { replace: true }))
}, [loc.pathname, loc.search, S.active?.editingWorkoutId, navigate])
- useEffect(() => { applyPrefs(S.theme, S.accent) }, [S.theme, S.accent])
+ // A preset key, or the user's own colour as '#rrggbb' (lib/accent.js), already checked.
+ const accent = accentValue(S)
+ useEffect(() => { applyPrefs(S.theme, accent) }, [S.theme, accent])
// 'system' needs to react live if the OS theme flips while the app is open, not just on
// the next mount — a fixed 'dark'/'light' choice never re-fires this since matchMedia
// isn't consulted for those.
useEffect(() => {
if (S.theme !== 'system' || !window.matchMedia) return
const mql = window.matchMedia('(prefers-color-scheme: dark)')
- const onChange = () => applyPrefs(S.theme, S.accent)
+ const onChange = () => applyPrefs(S.theme, accent)
mql.addEventListener('change', onChange)
return () => mql.removeEventListener('change', onChange)
- }, [S.theme, S.accent])
+ }, [S.theme, accent])
// A profile that never picked a language follows the instance default or the browser (#303) —
// worked out here, on this device, and never written into the synced state (lib/default-lang.js).
const config = useStore(s => s.config)
diff --git a/frontend/src/lib/accent.js b/frontend/src/lib/accent.js
new file mode 100644
index 000000000..018f9e201
--- /dev/null
+++ b/frontend/src/lib/accent.js
@@ -0,0 +1,174 @@
+// The accent colour: one of the presets (lib/format.js ACCENTS) or a colour of the user's own.
+//
+// Stored as two synced settings: `accent` names the choice ('lime', 'sky', … or 'custom') and
+// `accentCustom` keeps the user's own colour as '#rrggbb', also while a preset is picked, so
+// going back to it brings the same colour back. An app from before this knows no 'custom' and
+// draws its default green (App.jsx falls back on any key it does not know), and leaves
+// `accentCustom` alone like any other key it does not read.
+//
+// Nothing here trusts the stored value: it comes from other devices, backups and the server, and
+// the colour ends up in CSS custom properties and in the Android notification. Only a plain
+// six-digit hex gets that far; anything else is the default accent.
+//
+// A preset has a dark and a light shade of its own (index.css). The user's colour is one colour,
+// so for each theme it is checked against that theme's backgrounds and, when it would vanish into
+// them (navy on black, pale yellow on white), made lighter or darker just far enough to be read.
+// The bars come from the presets: each one clears them as shipped, all but yellow in light mode
+// (THEMES below, accent.test.js).
+import { ACCENTS, ACCENT_INK } from './format.js'
+
+export const DEFAULT_ACCENT = 'lime'
+export const CUSTOM = 'custom'
+
+const HEX = /^#[0-9a-f]{6}$/i
+// What a stored `accent` may be at all: a short lowercase word. One this version does not know
+// (a preset added later) is kept as it is and drawn as the default until the app learns it.
+const KEY = /^[a-z][a-z0-9-]{0,23}$/
+
+/** '#rrggbb' in lowercase, or null for anything else ('#abc', 'red', 'url(…)', a number). */
+export function cleanHex(v) {
+ return typeof v === 'string' && HEX.test(v.trim()) ? v.trim().toLowerCase() : null
+}
+
+/**
+ * A copy's accent fields made safe, in place: a malformed `accentCustom` is dropped and an
+ * `accent` that is not even a word goes back to the default. Returns the copy.
+ */
+export function sanitizeAccent(s) {
+ if (!s || typeof s !== 'object') return s
+ if ('accentCustom' in s) {
+ const hex = cleanHex(s.accentCustom)
+ if (hex) s.accentCustom = hex; else delete s.accentCustom
+ }
+ if ('accent' in s && !(typeof s.accent === 'string' && KEY.test(s.accent))) s.accent = DEFAULT_ACCENT
+ return s
+}
+
+/** The choice to draw: a known preset key, 'custom' with a usable colour, or the default. */
+export function accentKey(S) {
+ const k = S?.accent
+ if (typeof k === 'string' && Object.hasOwn(ACCENTS, k)) return k
+ if (k === CUSTOM && cleanHex(S?.accentCustom)) return CUSTOM
+ return DEFAULT_ACCENT
+}
+
+/**
+ * The value the rest of the app passes around (the rest alert, the native countdown): a preset
+ * key, or the user's colour itself as '#rrggbb'.
+ */
+export function accentValue(S) {
+ const k = accentKey(S)
+ return k === CUSTOM ? cleanHex(S.accentCustom) : k
+}
+
+// --- colour maths (sRGB, WCAG 2 relative luminance) ---
+const rgb = hex => { const n = parseInt(hex.slice(1), 16); return [n >> 16, (n >> 8) & 255, n & 255] }
+const toHex = c => '#' + c.map(v => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, '0')).join('')
+const lin = v => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4 }
+
+export function luminance(hex) {
+ const [r, g, b] = rgb(hex)
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
+}
+
+/** WCAG contrast ratio of two '#rrggbb' colours, 1 to 21. */
+export function contrast(a, b) {
+ const x = luminance(a), y = luminance(b)
+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05)
+}
+
+/** `hex` moved `t` (0–1) of the way to `to`. */
+export function mix(hex, to, t) {
+ const a = rgb(hex), b = rgb(to)
+ return toHex(a.map((v, i) => v + (b[i] - v) * t))
+}
+
+/** Black or white, whichever reads better on `hex` (black on a tie). */
+export function inkOn(hex) {
+ return contrast(hex, '#000000') >= contrast(hex, '#ffffff') ? '#000000' : '#ffffff'
+}
+
+// Each theme's page and card fill (index.css --bg / --surface), and how far the accent has to
+// stand out from the weaker of the two. Dark: the bluest presets sit at 4.7:1 on a card, so 3:1
+// (the WCAG bar for large text and controls) leaves them all untouched. Light: Apple's own green
+// and orange stand at about 2:1 on the light page, so 1.8:1 keeps every preset but yellow (1.35,
+// the one preset that is hard to read there) and turns a pastel that would be invisible darker.
+export const THEMES = {
+ dark: { bgs: ['#000000', '#1c1c1e'], min: 3, toward: '#ffffff' },
+ light: { bgs: ['#f2f2f7', '#ffffff'], min: 1.8, toward: '#000000' },
+}
+
+const worst = (hex, bgs) => Math.min(...bgs.map(b => contrast(hex, b)))
+
+// HSL, for moving a colour's lightness without washing it out: mixing navy with white gives a
+// greyish lilac, raising its lightness gives a clear blue (and a pale yellow turns gold, not khaki).
+function toHsl(hex) {
+ const [r, g, b] = rgb(hex).map(v => v / 255)
+ const max = Math.max(r, g, b), min = Math.min(r, g, b), l = (max + min) / 2, d = max - min
+ if (!d) return [0, 0, l]
+ const s = d / (1 - Math.abs(2 * l - 1))
+ const h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4
+ return [h * 60, s, l]
+}
+function fromHsl([h, s, l]) {
+ const c = (1 - Math.abs(2 * l - 1)) * s, x = c * (1 - Math.abs(((h / 60) % 2) - 1)), m = l - c / 2
+ const [r, g, b] = h < 60 ? [c, x, 0] : h < 120 ? [x, c, 0] : h < 180 ? [0, c, x] : h < 240 ? [0, x, c] : h < 300 ? [x, 0, c] : [c, 0, x]
+ return toHex([r, g, b].map(v => (v + m) * 255))
+}
+
+/**
+ * `hex` as drawn in `theme`: unchanged when it already stands out enough, otherwise made lighter
+ * (dark theme) or darker (light theme) in small steps of HSL lightness until it does, hue and
+ * saturation kept.
+ */
+export function readableIn(hex, theme) {
+ const th = THEMES[theme] || THEMES.dark
+ if (worst(hex, th.bgs) >= th.min) return hex
+ const [h, s, l] = toHsl(hex)
+ const up = th.toward === '#ffffff'
+ for (let i = 1; i <= 50; i++) {
+ const c = fromHsl([h < 0 ? h + 360 : h, s, up ? Math.min(1, l + i * 0.02) : Math.max(0, l - i * 0.02)])
+ if (worst(c, th.bgs) >= th.min) return c
+ }
+ return th.toward
+}
+
+/** Whether `hex` is drawn differently from itself in `theme` (Settings says so). */
+export const adjustedIn = (hex, theme) => readableIn(hex, theme) !== hex
+
+/**
+ * The CSS custom properties for the user's colour in `theme`, the same set a preset defines in
+ * index.css: the accent, its pressed shade and the text on it. The soft and line tints are
+ * mixed from --acc in index.css and follow on their own. null for anything but a valid hex.
+ */
+export function customAccentVars(hex, theme) {
+ const c = cleanHex(hex)
+ if (!c) return null
+ const acc = readableIn(c, theme)
+ return { '--acc': acc, '--acc-2': mix(acc, '#000000', 0.25), '--on-acc': inkOn(acc) }
+}
+
+/** The colour and its text colour for a preset key or a '#rrggbb' value (native notification). */
+export function accentPair(v) {
+ const hex = cleanHex(v)
+ if (hex) return { accent: hex, ink: inkOn(hex) }
+ const k = typeof v === 'string' && Object.hasOwn(ACCENTS, v) ? v : DEFAULT_ACCENT
+ return { accent: ACCENTS[k], ink: ACCENT_INK[k] }
+}
+
+const CUSTOM_VARS = ['--acc', '--acc-2', '--on-acc']
+
+/**
+ * Puts the accent on the page root: a preset by `data-accent` (index.css does the rest), the
+ * user's colour as inline custom properties for the resolved `theme`. `value` is accentValue's.
+ */
+export function applyAccent(el, value, theme) {
+ const vars = customAccentVars(value, theme)
+ if (vars) {
+ el.dataset.accent = CUSTOM
+ for (const [k, v] of Object.entries(vars)) el.style.setProperty(k, v)
+ return
+ }
+ el.dataset.accent = typeof value === 'string' && Object.hasOwn(ACCENTS, value) ? value : DEFAULT_ACCENT
+ for (const k of CUSTOM_VARS) el.style.removeProperty(k)
+}
diff --git a/frontend/src/lib/accent.test.js b/frontend/src/lib/accent.test.js
new file mode 100644
index 000000000..dc91043a0
--- /dev/null
+++ b/frontend/src/lib/accent.test.js
@@ -0,0 +1,158 @@
+// @vitest-environment happy-dom
+import { describe, expect, it } from 'vitest'
+import { ACCENTS } from './format.js'
+import {
+ cleanHex, sanitizeAccent, accentKey, accentValue, contrast, inkOn, readableIn, adjustedIn,
+ customAccentVars, accentPair, applyAccent, THEMES,
+} from './accent.js'
+import { mergeStates } from './sync-merge.js'
+
+describe('cleanHex', () => {
+ it('takes #rrggbb only, in lowercase', () => {
+ expect(cleanHex('#A1b2C3')).toBe('#a1b2c3')
+ expect(cleanHex(' #00ff00 ')).toBe('#00ff00')
+ for (const bad of ['#abc', 'abcdef', '#abcdeg', '#abcdef00', 'red', 'rgb(1,2,3)', '', null, undefined, 123, {}, ['#abcdef'],
+ '#000000;background:url(x)', '#000000}body{display:none', 'var(--x)'])
+ expect(cleanHex(bad), String(bad)).toBe(null)
+ })
+})
+
+describe('sanitizeAccent', () => {
+ it('drops a malformed own colour and keeps a good one', () => {
+ expect(sanitizeAccent({ accent: 'custom', accentCustom: '#FF00AA' })).toEqual({ accent: 'custom', accentCustom: '#ff00aa' })
+ expect(sanitizeAccent({ accent: 'custom', accentCustom: 'red;}' })).toEqual({ accent: 'custom' })
+ })
+ it('keeps an unknown preset word (a newer app’s) but not junk', () => {
+ expect(sanitizeAccent({ accent: 'mint' }).accent).toBe('mint')
+ expect(sanitizeAccent({ accent: '"><script>' }).accent).toBe('lime')
+ expect(sanitizeAccent({ accent: 42 }).accent).toBe('lime')
+ expect(sanitizeAccent({ theme: 'dark' })).toEqual({ theme: 'dark' })
+ })
+})
+
+describe('accentKey / accentValue', () => {
+ it('draws a preset, the own colour, or the default', () => {
+ expect(accentKey({ accent: 'sky' })).toBe('sky')
+ expect(accentKey({})).toBe('lime')
+ expect(accentKey({ accent: 'mint' })).toBe('lime')
+ expect(accentKey({ accent: 'toString' })).toBe('lime')
+ expect(accentKey({ accent: 'custom' })).toBe('lime')
+ expect(accentKey({ accent: 'custom', accentCustom: 'nope' })).toBe('lime')
+ expect(accentValue({ accent: 'custom', accentCustom: '#123ABC' })).toBe('#123abc')
+ // the own colour is kept while a preset is the accent
+ expect(accentValue({ accent: 'red', accentCustom: '#123abc' })).toBe('red')
+ })
+})
+
+describe('contrast and the text on the accent', () => {
+ it('measures WCAG contrast', () => {
+ expect(contrast('#000000', '#ffffff')).toBeCloseTo(21, 5)
+ expect(contrast('#777777', '#777777')).toBeCloseTo(1, 5)
+ })
+ it('puts black on light colours and white on dark ones', () => {
+ expect(inkOn('#ffd60a')).toBe('#000000')
+ expect(inkOn('#30d158')).toBe('#000000')
+ expect(inkOn('#1a237e')).toBe('#ffffff')
+ expect(inkOn('#8b0000')).toBe('#ffffff')
+ })
+ it('the chosen ink always reads at least 4.5:1', () => {
+ for (let i = 0; i < 400; i++) {
+ const hex = '#' + Math.floor((i * 2654435761) % 0xffffff).toString(16).padStart(6, '0')
+ expect(contrast(hex, inkOn(hex)), hex).toBeGreaterThanOrEqual(4.5)
+ }
+ })
+})
+
+describe('readable on the theme', () => {
+ const darkPresets = ['#30d158', '#0a84ff', '#ff9f0a', '#bf5af2', '#ff375f', '#ff453a', '#40c8e0', '#ffd60a']
+ const lightPresets = ['#34c759', '#007aff', '#ff9500', '#af52de', '#ff2d55', '#ff3b30', '#30b0c7']
+ it('leaves every preset shade as it is (yellow aside in light mode)', () => {
+ for (const c of darkPresets) expect(adjustedIn(c, 'dark'), c).toBe(false)
+ for (const c of lightPresets) expect(adjustedIn(c, 'light'), c).toBe(false)
+ expect(adjustedIn('#ffcc00', 'light')).toBe(true)
+ })
+ it('lightens a very dark colour in dark mode and darkens a very light one in light mode', () => {
+ const navy = readableIn('#000033', 'dark')
+ expect(navy).not.toBe('#000033')
+ for (const bg of THEMES.dark.bgs) expect(contrast(navy, bg)).toBeGreaterThanOrEqual(THEMES.dark.min)
+ expect(readableIn('#000033', 'light')).toBe('#000033')
+ const pale = readableIn('#fff8e1', 'light')
+ expect(pale).not.toBe('#fff8e1')
+ for (const bg of THEMES.light.bgs) expect(contrast(pale, bg)).toBeGreaterThanOrEqual(THEMES.light.min)
+ expect(readableIn('#fff8e1', 'dark')).toBe('#fff8e1')
+ // the extremes still end somewhere readable
+ expect(contrast(readableIn('#000000', 'dark'), '#1c1c1e')).toBeGreaterThanOrEqual(3)
+ expect(contrast(readableIn('#ffffff', 'light'), '#f2f2f7')).toBeGreaterThanOrEqual(1.8)
+ })
+ it('a colour is never adjusted for both themes', () => {
+ for (let i = 0; i < 400; i++) {
+ const hex = '#' + Math.floor((i * 40503 * 977) % 0xffffff).toString(16).padStart(6, '0')
+ expect(adjustedIn(hex, 'dark') && adjustedIn(hex, 'light'), hex).toBe(false)
+ }
+ })
+})
+
+describe('CSS for the own colour', () => {
+ it('derives the accent, its pressed shade and its text', () => {
+ expect(customAccentVars('#0a84ff', 'dark')).toEqual({ '--acc': '#0a84ff', '--acc-2': '#0863bf', '--on-acc': '#000000' })
+ const v = customAccentVars('#000033', 'dark')
+ expect(v['--acc']).toBe(readableIn('#000033', 'dark'))
+ expect(v['--on-acc']).toBe(inkOn(v['--acc']))
+ })
+ it('gives nothing for a value that is not a colour', () => {
+ expect(customAccentVars('red}body{', 'dark')).toBe(null)
+ expect(customAccentVars('lime', 'dark')).toBe(null)
+ })
+ it('puts a preset or the own colour on the page root and takes the own colour off again', () => {
+ const el = document.createElement('html')
+ applyAccent(el, '#ff00aa', 'light')
+ expect(el.dataset.accent).toBe('custom')
+ expect(el.style.getPropertyValue('--acc')).toBe('#ff00aa')
+ expect(el.style.getPropertyValue('--on-acc')).toBe(inkOn('#ff00aa'))
+ applyAccent(el, 'sky', 'light')
+ expect(el.dataset.accent).toBe('sky')
+ expect(el.style.getPropertyValue('--acc')).toBe('')
+ applyAccent(el, 'url(x)', 'dark')
+ expect(el.dataset.accent).toBe('lime')
+ })
+})
+
+describe('the native countdown colours', () => {
+ it('takes a preset key or the own colour', () => {
+ expect(accentPair('sky')).toEqual({ accent: ACCENTS.sky, ink: '#ffffff' })
+ expect(accentPair('#ffd60a')).toEqual({ accent: '#ffd60a', ink: '#000000' })
+ expect(accentPair('nonsense')).toEqual({ accent: ACCENTS.lime, ink: '#000000' })
+ expect(accentPair(undefined)).toEqual({ accent: ACCENTS.lime, ink: '#000000' })
+ })
+})
+
+describe('sync with an app from before own colours', () => {
+ const base = { _ts: 1, unit: 'kg', workouts: [], routines: [], bodyweight: [] }
+ it('an older copy picking a preset keeps the own colour for later', () => {
+ const mine = { ...base, _ts: 10, accent: 'custom', accentCustom: '#ff00aa', edited: { accent: 10, accentCustom: 10 } }
+ // the old app knows nothing of accentCustom; its copy still carries it untouched
+ const old = { ...base, _ts: 20, accent: 'sky', accentCustom: '#ff00aa', edited: { accent: 20, accentCustom: 10 } }
+ const out = mergeStates(mine, old)
+ expect(out.accent).toBe('sky')
+ expect(out.accentCustom).toBe('#ff00aa')
+ expect(accentValue(out)).toBe('sky')
+ })
+ it('an older copy without the field does not lose it, and a newer one draws it', () => {
+ const mine = { ...base, _ts: 30, accent: 'custom', accentCustom: '#123456', edited: { accent: 30, accentCustom: 30 } }
+ const old = { ...base, _ts: 20, accent: 'lime' }
+ const out = mergeStates(old, mine)
+ expect(accentValue(out)).toBe('#123456')
+ })
+ it('what an old app makes of "custom": its own default, nothing broken', () => {
+ // App.jsx before own colours: ACCENTS[accent] ? accent : 'lime'
+ const S = { accent: 'custom', accentCustom: '#123456' }
+ expect(ACCENTS[S.accent] ? S.accent : 'lime').toBe('lime')
+ })
+ it('a malformed colour from the other copy is dropped by the merge', () => {
+ const mine = { ...base, _ts: 10, accent: 'red' }
+ const theirs = { ...base, _ts: 20, accent: 'custom', accentCustom: '#fff;}*{color:red' }
+ const out = mergeStates(mine, theirs)
+ expect('accentCustom' in out).toBe(false)
+ expect(accentValue(out)).toBe('lime')
+ })
+})
diff --git a/frontend/src/lib/rest-alert.js b/frontend/src/lib/rest-alert.js
index 070771204..d304ebfff 100644
--- a/frontend/src/lib/rest-alert.js
+++ b/frontend/src/lib/rest-alert.js
@@ -9,7 +9,8 @@
//
// The web build keeps Web Push (useUI). This file no-ops there; MOBILE is a build-time flag.
import { t } from './i18n-core.js'
-import { ACCENTS, ACCENT_INK, argb } from './format.js'
+import { argb } from './format.js'
+import { accentPair } from './accent.js'
import { MOBILE, isAndroid } from './mobile.js'
export const REST_ALERT_ID = 42
@@ -21,9 +22,10 @@ export const REST_QUIET_CHANNEL_ID = 'rest-over-quiet'
// One object the native side schedules. Public + high is what the notification shade can show.
// The lock screen follows the user's notification settings.
+// `key` is a preset's key or the user's own colour as '#rrggbb' (lib/accent.js accentValue).
export function accentColors(key) {
- const k = ACCENTS[key] ? key : 'lime'
- return { accent: argb(ACCENTS[k]), ink: argb(ACCENT_INK[k]) }
+ const { accent, ink } = accentPair(key)
+ return { accent: argb(accent), ink: argb(ink) }
}
export function buildRestAlert({ at, title, countdownTitle, totalSec, accent, sound = true, vibrate = true, alarmBuzz = false, now = Date.now() } = {}) {
diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.js
index 073ed1212..99f41bc35 100644
--- a/frontend/src/lib/sync-merge.js
+++ b/frontend/src/lib/sync-merge.js
@@ -70,6 +70,7 @@
import { beatsWeight } from './exercises.js'
import { bestWeightForEntry } from './history.js'
import { convertStateUnit, convertBodyWeight } from './units.js'
+import { sanitizeAccent } from './accent.js'
const clone = o => JSON.parse(JSON.stringify(o))
const list = v => (Array.isArray(v) ? v : [])
@@ -612,6 +613,8 @@ export function mergeStates(a0, b0, { prefer } = {}) {
if (resetIds) out.resetIds = resetIds
else delete out.resetIds
delete out._rev
+ // The accent fields end up in CSS: whatever either copy brought, only a clean value goes on.
+ sanitizeAccent(out)
return out
}
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 7ca9cf9c1..974ad855b 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -23,6 +23,7 @@ import { RTL_LANGS } from '../lib/i18n-core.js'
import { DEFAULT_TEMPLATE_ID } from '../lib/structuralBalanceTemplates.js'
import { WC_DEFAULT } from '../lib/workout-controls.js'
+import { sanitizeAccent } from '../lib/accent.js'
const KEY = 'gym_state_v1'
// Where the saved copy stands with the server: the revision it descends from, and its own `_ts`
@@ -241,7 +242,7 @@ function loadState() {
const raw = localStorage.getItem(KEY)
if (raw) {
const saved = JSON.parse(raw)
- const s = Object.assign(clone(DEF), saved)
+ const s = sanitizeAccent(Object.assign(clone(DEF), saved))
if (!saved.lang) s.lang = detectedLang()
return s
}
@@ -260,7 +261,7 @@ const hasData = st => !!((st.workouts || []).length || (st.routines || []).lengt
// session belongs to the device that is currently running it.
export function restoredStateFor(local, remote, dirty = false) {
if (!remote || (hasData(local) && (dirty || (remote._ts || 0) < (local._ts || 0)))) return null
- const next = Object.assign(clone(DEF), remote)
+ const next = sanitizeAccent(Object.assign(clone(DEF), remote))
if (local.active) next.active = local.active
return next
}
@@ -1118,7 +1119,7 @@ export const useStore = create((set, get) => {
// preferred, in the backup's unit), pushed against that revision like any other change, so a
// workout logged meanwhile elsewhere, or here, is not lost either.
importBackup(backup, { mergeWith } = {}) {
- const next = Object.assign(clone(DEF), backup)
+ const next = sanitizeAccent(Object.assign(clone(DEF), backup))
if (!mergeWith?.state || !get().user) { get().replaceState(next, !!get().user); return }
const others = mergeWith.local ? mergeStates(get().S, mergeWith.state) : mergeWith.state
const merged = keepReset(get().S, Object.assign(clone(DEF), mergeStates(next, others, { prefer: 'a' })))
@@ -1279,7 +1280,7 @@ export const useStore = create((set, get) => {
const changed = dirty || localChanged(S)
if (!serverMoved) { if (changed) await get().pushState(); else confirmed(S); return }
if (!state) { writeSync(rev, 0); if (hasData(S)) await get().pushState(); return }
- if (!changed) { const next = Object.assign(clone(DEF), state); next.active = carryActive(S, next); adopt(next, rev); confirmed(get().S); return }
+ if (!changed) { const next = sanitizeAccent(Object.assign(clone(DEF), state)); next.active = carryActive(S, next); adopt(next, rev); confirmed(get().S); return }
mergeInto(S, state, rev)
pushPending = false
await get().pushState()
diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.js
index 3783ab638..abc97980e 100644
--- a/frontend/src/store/useUI.js
+++ b/frontend/src/store/useUI.js
@@ -8,6 +8,7 @@ import { MOBILE } from '../lib/mobile.js'
import { armRestAlert, bindNativeRest, disarmRestAlert, holdRestAlert } from '../lib/rest-alert.js'
import { useStore } from './useStore.js'
import { REST_MAX } from '../lib/duration.js'
+import { accentValue } from '../lib/accent.js'
// Fire-and-forget: lets the server push a "rest over" alert if this tab gets suspended
// before the local timer completes. No-ops for guests / offline. The device id keeps the
@@ -25,7 +26,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: S.accent, sound: !!S.sound, 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, 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