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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Accent: own colours stay readable and never look switched off; the picker saves once per pick
Duarte Santos65ea77333d7e
diff --git a/frontend/src/index.css b/frontend/src/index.cssindex 1823faa1c..a531d991a 100644--- a/frontend/src/index.css+++ b/frontend/src/index.css@@ -99,7 +99,7 @@:root[data-accent="pink"] { --acc:var(--pink); --acc-2:#d70036; --on-acc:#fff }:root[data-accent="red"] { --acc:var(--red); --acc-2:#d70015; --on-acc:#fff }:root[data-accent="teal"] { --acc:var(--teal); --acc-2:#0071a4; --on-acc:#000 }-:root[data-accent="gold"] { --acc:var(--yellow); --acc-2:#b25000; --on-acc:#000 }+:root[data-accent="gold"] { --acc:var(--yellow); --acc-2:#b25000; --on-acc:#000; --knob-ring:rgba(0,0,0,.28) }/* Label colour on a filled accent button is picked per accent by measured contrast,not by taste. Button text is 17px/600, so the AA bar is 3:1 (large text). White onthe light-theme green is 2.22:1 and on teal 2.57:1 — both fail, and green is the@@ -655,6 +655,10 @@ body.chips-dragging *{cursor:inherit}transition:transform var(--med) var(--ease),width var(--fast) var(--ease);}.sw.on{background:var(--acc)}+/* On an accent nearly as light as the knob (an own white or pale yellow, the gold preset) the+ knob gets a hairline ring so it does not vanish into the track. lib/accent.js sets --knob-ring+ for an own colour; it is transparent everywhere else. */+.sw.on .knob{box-shadow:0 0 0 1px var(--knob-ring,transparent),0 3px 8px rgba(0,0,0,.15),0 1px 1px rgba(0,0,0,.16)}.sw.on .knob{transform:translateX(20px)}.sw:active .knob{width:31px}.sw.on:active .knob{transform:translateX(16px)}diff --git a/frontend/src/lib/accent.js b/frontend/src/lib/accent.jsindex 018f9e201..87b226fcd 100644--- a/frontend/src/lib/accent.js+++ b/frontend/src/lib/accent.js@@ -13,8 +13,7 @@// 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).+// A grey goes further, so it never looks like a switched-off button (THEMES below, accent.test.js).import { ACCENTS, ACCENT_INK } from './format.js'export const DEFAULT_ACCENT = 'lime'@@ -88,15 +87,24 @@ 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.+// Each theme's page and card fill (index.css --bg / --surface), how far the user's colour has to+// stand out from the weaker of the two, and the theme's secondary label (index.css --label-2,+// laid over each fill). 3:1 is the WCAG bar for large text and controls: in dark mode the bluest+// presets sit at 4.7:1 on a card and stay untouched; in light mode a pastel or a bright yellow+// turns a darker shade of itself, so accent-coloured links and labels stay readable. The presets+// are not run through this: they keep their own index.css shades.+//+// A grey has no hue to keep, so lightening or darkening it only gives another grey, and one near+// --label-2 makes every button look switched off. A grey goes further: to text contrast (4.5:1)+// on the theme, and at least 2:1 away from --label-2.export const THEMES = {- dark: { bgs: ['#000000', '#1c1c1e'], min: 3, toward: '#ffffff' },- light: { bgs: ['#f2f2f7', '#ffffff'], min: 1.8, toward: '#000000' },+ dark: { bgs: ['#000000', '#1c1c1e'], min: 3, toward: '#ffffff', label2: ['#8d8d93', '#98989f'] },+ light: { bgs: ['#f2f2f7', '#ffffff'], min: 3, toward: '#000000', label2: ['#85858b', '#8a8a8e'] },}+// Below this HSL saturation a colour counts as a grey (white, black, #808080, near-whites).+export const GREY_SAT = 0.25+export const GREY_TEXT = 4.5+export const GREY_GAP = 2const worst = (hex, bgs) => Math.min(...bgs.map(b => contrast(hex, b)))@@ -116,19 +124,30 @@ function fromHsl([h, s, l]) {return toHex([r, g, b].map(v => (v + m) * 255))}+/** Whether `hex` is a grey for readableIn (see GREY_SAT). */+export const isGrey = hex => toHsl(hex)[1] < GREY_SAT+/*** `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.+ * saturation kept. A grey has to clear the stricter grey bar (THEMES above).*/export function readableIn(hex, theme) {const th = THEMES[theme] || THEMES.dark- if (worst(hex, th.bgs) >= th.min) return hex+ const grey = isGrey(hex)+ const ok = c => grey+ ? worst(c, th.bgs) >= GREY_TEXT && worst(c, th.label2) >= GREY_GAP+ : worst(c, th.bgs) >= th.min+ if (ok(hex)) return hexconst [h, s, l] = toHsl(hex)const up = th.toward === '#ffffff'+ const hue = h < 0 ? h + 360 : h+ // A yellow darkened at its own hue turns olive; drifting it a little towards orange on the way+ // down gives the gold a light theme uses for yellow (#ffff00 ends as a dark gold, not khaki).+ const yellow = !up && hue >= 48 && hue <= 72for (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+ const c = fromHsl([yellow ? Math.max(42, hue - i * 1.5) : hue, s, up ? Math.min(1, l + i * 0.02) : Math.max(0, l - i * 0.02)])+ if (ok(c)) return c}return th.toward}@@ -136,16 +155,39 @@ export function readableIn(hex, theme) {/** Whether `hex` is drawn differently from itself in `theme` (Settings says so). */export const adjustedIn = (hex, theme) => readableIn(hex, theme) !== hex+/**+ * The text colour for a button that is `acc` at rest and `acc2` while pressed: the one that reads+ * better on `acc` (inkOn), unless it drops under 3:1 (large text) on the pressed shade and the+ * other one holds up better across both. Over the whole sRGB cube that keeps at least 3:1 pressed+ * and about 4.35:1 at rest (accent.test.js).+ */+export function inkOnBoth(acc, acc2) {+ const ink = inkOn(acc)+ if (contrast(acc2, ink) >= 3) return ink+ const other = ink === '#000000' ? '#ffffff' : '#000000'+ const score = k => Math.min(contrast(acc, k), contrast(acc2, k))+ return score(other) > score(ink) ? other : ink+}++// A switch knob is white. On an accent nearly as light (white, pale yellow in dark mode) it would+// vanish into the track, so it gets a hairline ring there (index.css .sw.on .knob).+const KNOB_RING = 'rgba(0,0,0,.28)'+/*** 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.+ * index.css: the accent, its pressed shade, the text on it, and the switch knob's ring. 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 nullconst acc = readableIn(c, theme)- return { '--acc': acc, '--acc-2': mix(acc, '#000000', 0.25), '--on-acc': inkOn(acc) }+ const acc2 = mix(acc, '#000000', 0.25)+ return {+ '--acc': acc, '--acc-2': acc2, '--on-acc': inkOnBoth(acc, acc2),+ '--knob-ring': contrast('#ffffff', acc) < 1.5 ? KNOB_RING : 'transparent',+ }}/** The colour and its text colour for a preset key or a '#rrggbb' value (native notification). */@@ -156,7 +198,7 @@ export function accentPair(v) {return { accent: ACCENTS[k], ink: ACCENT_INK[k] }}-const CUSTOM_VARS = ['--acc', '--acc-2', '--on-acc']+const CUSTOM_VARS = ['--acc', '--acc-2', '--on-acc', '--knob-ring']/*** Puts the accent on the page root: a preset by `data-accent` (index.css does the rest), thediff --git a/frontend/src/lib/accent.test.js b/frontend/src/lib/accent.test.jsindex dc91043a0..acd9ed397 100644--- a/frontend/src/lib/accent.test.js+++ b/frontend/src/lib/accent.test.js@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'import { ACCENTS } from './format.js'import {cleanHex, sanitizeAccent, accentKey, accentValue, contrast, inkOn, readableIn, adjustedIn,- customAccentVars, accentPair, applyAccent, THEMES,+ customAccentVars, accentPair, applyAccent, THEMES, isGrey, inkOnBoth, mix, GREY_TEXT, GREY_GAP,} from './accent.js'import { mergeStates } from './sync-merge.js'@@ -66,11 +66,46 @@ describe('contrast and the text on the accent', () => {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)', () => {+ it('leaves every dark preset shade as it is, and darkens the light ones under 3:1', () => {for (const c of darkPresets) expect(adjustedIn(c, 'dark'), c).toBe(false)- for (const c of lightPresets) expect(adjustedIn(c, 'light'), c).toBe(false)+ // the presets draw their own index.css shades; as an own colour, Apple's light green,+ // orange and teal (about 2:1 on the light page) are taken a step darker+ for (const c of lightPresets) {+ const r = readableIn(c, 'light')+ for (const bg of THEMES.light.bgs) expect(contrast(r, bg), c).toBeGreaterThanOrEqual(3)+ }+ expect(adjustedIn('#007aff', 'light')).toBe(false)expect(adjustedIn('#ffcc00', 'light')).toBe(true)})+ it('an own colour reaches 3:1 on both fills of either theme', () => {+ for (let i = 0; i < 600; i++) {+ const hex = '#' + Math.floor((i * 2654435761) % 0xffffff).toString(16).padStart(6, '0')+ for (const theme of ['dark', 'light'])+ for (const bg of THEMES[theme].bgs) expect(contrast(readableIn(hex, theme), bg), hex + ' ' + theme).toBeGreaterThanOrEqual(3)+ }+ })+ it('bright yellow in light mode turns a dark gold, not olive', () => {+ const y = readableIn('#ffff00', 'light')+ const [r, g, b] = [1, 3, 5].map(i => parseInt(y.slice(i, i + 2), 16))+ expect(r).toBeGreaterThan(g) // towards orange: red leads green+ expect(b).toBeLessThan(20)+ })+ it('a grey never ends up near the secondary label colour', () => {+ // white in light mode and black in dark mode, a mid grey, near-whites and near-blacks+ const greys = ['#ffffff', '#000000', '#808080', '#f5f5f5', '#fafafa', '#0a0a0a', '#1c1c1e', '#9a9a9a', '#707070', '#f0f0f5', '#c8c8c8']+ for (const g of greys) {+ expect(isGrey(g), g).toBe(true)+ for (const theme of ['dark', 'light']) {+ const r = readableIn(g, theme)+ for (const bg of THEMES[theme].bgs) expect(contrast(r, bg), g + ' ' + theme).toBeGreaterThanOrEqual(GREY_TEXT)+ for (const l2 of THEMES[theme].label2) expect(contrast(r, l2), g + ' ' + theme).toBeGreaterThanOrEqual(GREY_GAP)+ }+ }+ // a grey that already stands apart is left alone+ expect(readableIn('#333333', 'light')).toBe('#333333')+ expect(readableIn('#e0e0e0', 'dark')).toBe('#e0e0e0')+ expect(isGrey('#ff00aa')).toBe(false)+ })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')@@ -82,11 +117,12 @@ describe('readable on the theme', () => {expect(readableIn('#fff8e1', 'dark')).toBe('#fff8e1')// the extremes still end somewhere readableexpect(contrast(readableIn('#000000', 'dark'), '#1c1c1e')).toBeGreaterThanOrEqual(3)- expect(contrast(readableIn('#ffffff', 'light'), '#f2f2f7')).toBeGreaterThanOrEqual(1.8)+ expect(contrast(readableIn('#ffffff', 'light'), '#f2f2f7')).toBeGreaterThanOrEqual(4.5)})- it('a colour is never adjusted for both themes', () => {+ it('a colour with a hue 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')+ if (isGrey(hex)) continueexpect(adjustedIn(hex, 'dark') && adjustedIn(hex, 'light'), hex).toBe(false)}})@@ -94,11 +130,36 @@ describe('readable on the theme', () => {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' })+ expect(customAccentVars('#0a84ff', 'dark')).toEqual({ '--acc': '#0a84ff', '--acc-2': '#0863bf', '--on-acc': '#000000', '--knob-ring': 'transparent' })const v = customAccentVars('#000033', 'dark')expect(v['--acc']).toBe(readableIn('#000033', 'dark'))expect(v['--on-acc']).toBe(inkOn(v['--acc']))})+ it('the button text reads on the pressed shade too, not only at rest', () => {+ // #eb0037 in dark mode: black reads on it at rest but only 2.9:1 on its pressed shade+ const red = customAccentVars('#eb0037', 'dark')+ expect(red['--on-acc']).toBe('#ffffff')+ expect(contrast(red['--acc-2'], red['--on-acc'])).toBeGreaterThanOrEqual(3)+ let restMin = 99+ for (let r = 0; r < 256; r += 15) for (let g = 0; g < 256; g += 15) for (let b = 0; b < 256; b += 15) {+ const hex = '#' + [r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')+ for (const theme of ['dark', 'light']) {+ const v = customAccentVars(hex, theme)+ expect(contrast(v['--acc-2'], v['--on-acc']), hex + ' ' + theme).toBeGreaterThanOrEqual(3)+ restMin = Math.min(restMin, contrast(v['--acc'], v['--on-acc']))+ }+ }+ expect(restMin).toBeGreaterThanOrEqual(4.3)+ // the ink keeps inkOn's pick whenever that one holds on the pressed shade+ expect(inkOnBoth('#30d158', mix('#30d158', '#000000', 0.25))).toBe('#000000')+ })+ it('rings the switch knob on an accent nearly as light as it', () => {+ expect(customAccentVars('#ffffff', 'dark')['--knob-ring']).not.toBe('transparent')+ expect(customAccentVars('#fff6c2', 'dark')['--knob-ring']).not.toBe('transparent')+ expect(customAccentVars('#ffff00', 'dark')['--knob-ring']).not.toBe('transparent')+ expect(customAccentVars('#ffffff', 'light')['--knob-ring']).toBe('transparent')+ expect(customAccentVars('#0a84ff', 'dark')['--knob-ring']).toBe('transparent')+ })it('gives nothing for a value that is not a colour', () => {expect(customAccentVars('red}body{', 'dark')).toBe(null)expect(customAccentVars('lime', 'dark')).toBe(null)@@ -112,6 +173,7 @@ describe('CSS for the own colour', () => {applyAccent(el, 'sky', 'light')expect(el.dataset.accent).toBe('sky')expect(el.style.getPropertyValue('--acc')).toBe('')+ expect(el.style.getPropertyValue('--knob-ring')).toBe('')applyAccent(el, 'url(x)', 'dark')expect(el.dataset.accent).toBe('lime')})diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 3e9f76389..c6fe5f850 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -1985,5 +1985,7 @@ export default {'Change your own color': 'غيّر لونك الخاص','A touch lighter in dark mode, so you can still read it.': 'أفتح قليلًا في الوضع الداكن حتى تبقى قراءته سهلة.','A touch darker in light mode, so you can still read it.': 'أغمق قليلًا في الوضع الفاتح حتى تبقى قراءته سهلة.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'تظهر الألوان الرمادية أفتح في الوضع الداكن، حتى لا تبدو الأزرار مُعطّلة.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'تظهر الألوان الرمادية أغمق في الوضع الفاتح، حتى لا تبدو الأزرار مُعطّلة.','custom color picker': 'لون خاص مخصص منتقي الألوان',}diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 972d7aeb0..db970f184 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -1952,5 +1952,7 @@ export default {'Change your own color': 'Eigene Farbe ändern','A touch lighter in dark mode, so you can still read it.': 'Im dunklen Modus etwas heller, damit du sie noch lesen kannst.','A touch darker in light mode, so you can still read it.': 'Im hellen Modus etwas dunkler, damit du sie noch lesen kannst.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Grautöne werden im dunklen Modus heller, damit Buttons nicht ausgeschaltet wirken.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'Grautöne werden im hellen Modus dunkler, damit Buttons nicht ausgeschaltet wirken.','custom color picker': 'eigene Farbe benutzerdefiniert Farbwähler Farbauswahl',}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 18d06dbc9..91c9c96ef 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -1932,5 +1932,7 @@ export default {'Change your own color': 'Cambia tu propio color','A touch lighter in dark mode, so you can still read it.': 'Un pelín más claro en modo oscuro, para que se siga leyendo.','A touch darker in light mode, so you can still read it.': 'Un pelín más oscuro en modo claro, para que se siga leyendo.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Los grises se ven más claros en modo oscuro, para que los botones no parezcan apagados.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'Los grises se ven más oscuros en modo claro, para que los botones no parezcan apagados.','custom color picker': 'color propio personalizado selector de color',}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex b4b9341ca..2d3b3b9ca 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -1932,5 +1932,7 @@ export default {'Change your own color': 'Change ta propre couleur','A touch lighter in dark mode, so you can still read it.': 'Un poil plus claire en mode sombre, pour rester lisible.','A touch darker in light mode, so you can still read it.': 'Un poil plus foncée en mode clair, pour rester lisible.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Les gris s’éclaircissent en mode sombre, pour que les boutons n’aient pas l’air éteints.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'Les gris foncent en mode clair, pour que les boutons n’aient pas l’air éteints.','custom color picker': 'couleur perso personnalisée sélecteur nuancier',}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 5d08178b4..245ccd7e3 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -1932,5 +1932,7 @@ export default {'Change your own color': 'अपना रंग बदलें','A touch lighter in dark mode, so you can still read it.': 'डार्क मोड में थोड़ा हल्का, ताकि पढ़ने में आए।','A touch darker in light mode, so you can still read it.': 'लाइट मोड में थोड़ा गहरा, ताकि पढ़ने में आए।',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'डार्क मोड में ग्रे रंग हल्के दिखते हैं, ताकि बटन बंद जैसे न लगें।',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'लाइट मोड में ग्रे रंग गहरे दिखते हैं, ताकि बटन बंद जैसे न लगें।','custom color picker': 'अपना रंग कस्टम रंग चुनने वाला',}diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 23f52e503..f3270a60d 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1935,5 +1935,7 @@ export default {'Change your own color': 'Saját szín módosítása','A touch lighter in dark mode, so you can still read it.': 'Sötét módban kicsit világosabb, hogy olvasható maradjon.','A touch darker in light mode, so you can still read it.': 'Világos módban kicsit sötétebb, hogy olvasható maradjon.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'A szürkék sötét módban világosabbak, hogy a gombok ne tűnjenek kikapcsoltnak.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'A szürkék világos módban sötétebbek, hogy a gombok ne tűnjenek kikapcsoltnak.','custom color picker': 'saját szín egyéni színválasztó',}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex cd67d80a2..125fc9180 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -1932,5 +1932,7 @@ export default {'Change your own color': 'Cambia il tuo colore','A touch lighter in dark mode, so you can still read it.': 'Un filo più chiaro in modalità scura, così resta leggibile.','A touch darker in light mode, so you can still read it.': 'Un filo più scuro in modalità chiara, così resta leggibile.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'I grigi diventano più chiari in modalità scura, così i pulsanti non sembrano spenti.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'I grigi diventano più scuri in modalità chiara, così i pulsanti non sembrano spenti.','custom color picker': 'colore personalizzato proprio selettore colore',}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex f9174ab3a..c32038c27 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -1932,5 +1932,7 @@ export default {'Change your own color': '나만의 색상 바꾸기','A touch lighter in dark mode, so you can still read it.': '다크 모드에서는 잘 보이도록 살짝 밝게 표시돼요.','A touch darker in light mode, so you can still read it.': '라이트 모드에서는 잘 보이도록 살짝 어둡게 표시돼요.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': '다크 모드에서는 버튼이 꺼진 것처럼 보이지 않게 회색을 밝게 표시해요.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': '라이트 모드에서는 버튼이 꺼진 것처럼 보이지 않게 회색을 어둡게 표시해요.','custom color picker': '나만의 색상 사용자 지정 색상 선택기',}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 31b0d698a..59962d605 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -1932,5 +1932,7 @@ export default {'Change your own color': 'Zmień własny kolor','A touch lighter in dark mode, so you can still read it.': 'Odrobinę jaśniejszy w trybie ciemnym, żeby dało się go przeczytać.','A touch darker in light mode, so you can still read it.': 'Odrobinę ciemniejszy w trybie jasnym, żeby dało się go przeczytać.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Szarości są jaśniejsze w trybie ciemnym, żeby przyciski nie wyglądały na wyłączone.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'Szarości są ciemniejsze w trybie jasnym, żeby przyciski nie wyglądały na wyłączone.','custom color picker': 'własny kolor niestandardowy próbnik wybór koloru',}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 840e29c05..3b8d27277 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -1197,6 +1197,8 @@ export const PT_BR_OVERRIDES = {'Change your own color': 'Mude sua própria cor','A touch lighter in dark mode, so you can still read it.': 'Um pouco mais clara no modo escuro, para você continuar lendo.','A touch darker in light mode, so you can still read it.': 'Um pouco mais escura no modo claro, para você continuar lendo.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Os cinzas ficam mais claros no modo escuro, para os botões não parecerem desligados.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'Os cinzas ficam mais escuros no modo claro, para os botões não parecerem desligados.',}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 6f23fdd90..529c40dfb 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -1932,5 +1932,7 @@ export default {'Change your own color': 'Muda a tua própria cor','A touch lighter in dark mode, so you can still read it.': 'Um pouco mais clara no modo escuro, para continuares a ler.','A touch darker in light mode, so you can still read it.': 'Um pouco mais escura no modo claro, para continuares a ler.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Os cinzentos ficam mais claros no modo escuro, para os botões não parecerem desligados.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'Os cinzentos ficam mais escuros no modo claro, para os botões não parecerem desligados.','custom color picker': 'cor própria personalizada seletor de cor',}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 6cb163a37..f26a9e6ae 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -1936,5 +1936,7 @@ export default {'Change your own color': 'Изменить свой цвет','A touch lighter in dark mode, so you can still read it.': 'В тёмной теме чуть светлее, чтобы его было видно.','A touch darker in light mode, so you can still read it.': 'В светлой теме чуть темнее, чтобы его было видно.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Серые оттенки в тёмной теме светлее, чтобы кнопки не казались выключенными.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'Серые оттенки в светлой теме темнее, чтобы кнопки не казались выключенными.','custom color picker': 'свой цвет пользовательский палитра выбор цвета',}diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 8b1908931..e184220d0 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1943,5 +1943,7 @@ export default {'Change your own color': 'เปลี่ยนสีของคุณเอง','A touch lighter in dark mode, so you can still read it.': 'ในโหมดมืดจะสว่างขึ้นนิดหน่อย จะได้ยังอ่านออก','A touch darker in light mode, so you can still read it.': 'ในโหมดสว่างจะเข้มขึ้นนิดหน่อย จะได้ยังอ่านออก',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'สีเทาจะสว่างขึ้นในโหมดมืด ปุ่มจะได้ไม่ดูเหมือนถูกปิดอยู่',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'สีเทาจะเข้มขึ้นในโหมดสว่าง ปุ่มจะได้ไม่ดูเหมือนถูกปิดอยู่','custom color picker': 'สีเอง กำหนดเอง ตัวเลือกสี',}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 0be26e57e..d31551a44 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -1932,5 +1932,7 @@ export default {'Change your own color': 'Kendi rengini değiştir','A touch lighter in dark mode, so you can still read it.': 'Karanlık modda biraz daha açık, hâlâ okunabilsin diye.','A touch darker in light mode, so you can still read it.': 'Aydınlık modda biraz daha koyu, hâlâ okunabilsin diye.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Griler karanlık modda daha açık görünür, düğmeler kapalıymış gibi durmasın diye.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'Griler aydınlık modda daha koyu görünür, düğmeler kapalıymış gibi durmasın diye.','custom color picker': 'kendi renk özel renk seçici',}diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 85b23c7d3..d96b58337 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -1929,5 +1929,7 @@ export default {'Change your own color': 'Змінити свій колір','A touch lighter in dark mode, so you can still read it.': 'У темній темі трохи світліший, щоб його було видно.','A touch darker in light mode, so you can still read it.': 'У світлій темі трохи темніший, щоб його було видно.',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': 'Сірі відтінки в темній темі світліші, щоб кнопки не здавалися вимкненими.',+ 'Greys show darker in light mode, so buttons don’t look switched off.': 'Сірі відтінки у світлій темі темніші, щоб кнопки не здавалися вимкненими.','custom color picker': 'свій колір власний палітра вибір кольору',}diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex e5b69fc2a..5e268a5b7 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -1925,5 +1925,7 @@ export default {'Change your own color': '更改你自己的顏色','A touch lighter in dark mode, so you can still read it.': '深色模式下會稍微調亮一點,讓你看得清楚。','A touch darker in light mode, so you can still read it.': '淺色模式下會稍微調暗一點,讓你看得清楚。',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': '深色模式下灰色會調亮一些,免得按鈕看起來像被停用了。',+ 'Greys show darker in light mode, so buttons don’t look switched off.': '淺色模式下灰色會調暗一些,免得按鈕看起來像被停用了。','custom color picker': '自訂顏色 自己的顏色 取色器 調色盤',}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 77a8c9573..c7055b10a 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -1932,5 +1932,7 @@ export default {'Change your own color': '更改你自己的颜色','A touch lighter in dark mode, so you can still read it.': '深色模式下会稍微调亮一点,好让你看得清。','A touch darker in light mode, so you can still read it.': '浅色模式下会稍微调暗一点,好让你看得清。',+ 'Greys show lighter in dark mode, so buttons don’t look switched off.': '深色模式下灰色会调亮一些,免得按钮看起来像被停用了。',+ 'Greys show darker in light mode, so buttons don’t look switched off.': '浅色模式下灰色会调暗一些,免得按钮看起来像被停用了。','custom color picker': '自定义颜色 自己的颜色 取色器 调色板',}diff --git a/frontend/src/views/Settings.accent.test.jsx b/frontend/src/views/Settings.accent.test.jsxindex 3f0ff6d4c..cadb04574 100644--- a/frontend/src/views/Settings.accent.test.jsx+++ b/frontend/src/views/Settings.accent.test.jsx@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import Settings from './Settings.jsx'import { searchSettings } from './settings-pages.js'import { setRestAccent } from '../lib/rest-alert.js'+import { readableIn } from '../lib/accent.js'globalThis.IS_REACT_ACT_ENVIRONMENT = true@@ -68,12 +69,15 @@ afterEach(() => {const mount = () => act(() => root.render(<Settings page="look" />))const own = () => host.querySelector('.swatch-own')const picker = () => host.querySelector('.swatch-own input[type="color"]')-// React listens for 'input' on a colour field; set the value the way the browser does.-const pick = value => act(() => {+// A drag step: the browser sets the value and fires 'input' (React's onChange).+const drag = value => act(() => {const input = picker()Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set.call(input, value)input.dispatchEvent(new Event('input', { bubbles: true }))})+// The picker closing: 'change'.+const release = () => act(() => { picker().dispatchEvent(new Event('change', { bubbles: true })) })+const pick = value => { drag(value); release() }describe('Settings: your own accent colour', () => {it('starts as a rainbow swatch that opens the colour picker', () => {@@ -95,6 +99,43 @@ describe('Settings: your own accent colour', () => {expect(own().style.background).toContain('#ff00aa')})+ it('dragging only repaints; the colour is saved once, when the picker lets go', () => {+ mount()+ const before = mocks.S+ drag('#ff0000'); drag('#00ff00'); drag('#0000ff')+ expect(mocks.S).toBe(before) // no store write per drag step+ expect(setRestAccent).not.toHaveBeenCalled() // no native call per drag step+ expect(document.documentElement.dataset.accent).toBe('custom')+ expect(document.documentElement.style.getPropertyValue('--acc')).toBe(readableIn('#0000ff', 'dark'))+ release()+ expect(mocks.S.accentCustom).toBe('#0000ff')+ expect(setRestAccent).toHaveBeenCalledTimes(1)+ expect(setRestAccent).toHaveBeenCalledWith('#0000ff')+ mount() // the store re-renders the row+ release() // a second change with nothing new: no second save+ expect(setRestAccent).toHaveBeenCalledTimes(1)+ })++ it('saves after the picker rests, for a browser that sends no change', () => {+ vi.useFakeTimers()+ try {+ mount()+ drag('#ff8800')+ expect(mocks.S.accentCustom).toBe(undefined)+ act(() => vi.advanceTimersByTime(450))+ expect(mocks.S.accentCustom).toBe('#ff8800')+ expect(setRestAccent).toHaveBeenCalledTimes(1)+ } finally { vi.useRealTimers() }+ })++ it('a colour still being dragged is saved when Settings closes', () => {+ mount()+ drag('#336699')+ act(() => root.unmount())+ expect(mocks.S.accentCustom).toBe('#336699')+ root = createRoot(host)+ })+it('a preset in between keeps the colour, and one tap brings it back', () => {mocks.S.accent = 'custom'; mocks.S.accentCustom = '#123456'mount()@@ -120,6 +161,13 @@ describe('Settings: your own accent colour', () => {expect(host.querySelector('.swatch-note')).toBe(null)})+ it('says so when a grey is drawn darker in light mode', () => {+ mocks.S.accent = 'custom'; mocks.S.accentCustom = '#ffffff'+ mount()+ expect(host.textContent).toContain('Greys show darker in light mode, so buttons don’t look switched off.')+ expect(host.textContent).not.toContain('A touch')+ })+it('ignores a value that is not a colour', () => {mocks.S.accent = 'custom'; mocks.S.accentCustom = 'red;}'mount()diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex f0e235487..a247f547d 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -25,7 +25,7 @@ import { syncMedia, fetchToStore } from '../lib/media-sync.js'import { getMediaStatus, subscribeMediaStatus, pendingRefCount } from '../lib/media-owed.js'import { limitsFrom, fmtMB, MB } from '../lib/media-limits.js'import { setRestAccent } from '../lib/rest-alert.js'-import { CUSTOM, accentKey, adjustedIn, cleanHex, inkOn } from '../lib/accent.js'+import { CUSTOM, accentKey, adjustedIn, applyAccent, cleanHex, inkOn, isGrey } from '../lib/accent.js'import { checkForUpdate, downloadAndInstall } from '../lib/update.js'import { forgetCoach } from '../lib/coach-api.js'import { REST_MAX, REST_PAUSE_MIN, REST_PAUSE_MAX, fmtRest, fmtDuration } from '../lib/duration.js'@@ -1129,6 +1129,10 @@ function accentLabel(S) {* the native <input type="color"> laid over the swatch, so the tap that opens it is the user's* own, which iOS Safari and the Android WebView both want.*/+// How long the colour picker has to rest before a colour is saved, when the browser sends no+// `change` at the end (it should, once the picker closes).+const OWN_COLOR_SETTLE_MS = 400+function AccentSwatches({ S, update }) {const key = accentKey(S)const own = cleanHex(S.accentCustom)@@ -1136,14 +1140,52 @@ function AccentSwatches({ S, update }) {const pickPreset = k => { update(s => { s.accent = k }); setRestAccent(k) }const pickOwn = hex => {const c = cleanHex(hex)- if (!c) return+ if (!c || (onCustom && c === own)) returnupdate(s => { s.accent = CUSTOM; s.accentCustom = c })setRestAccent(c)}+ // The picker sends a colour for every step of a drag (React's onChange is the `input` event).+ // Those only repaint the page; the colour is saved, synced and sent to the native countdown+ // once: on the picker's `change`, after it has rested a moment, or when Settings closes.+ const inputRef = useRef(null)+ const pending = useRef(null)+ const timer = useRef(0)+ const pickOwnRef = useRef(pickOwn)+ pickOwnRef.current = pickOwn+ const commit = () => {+ clearTimeout(timer.current)+ const c = pending.current+ pending.current = null+ if (c) pickOwnRef.current(c)+ }+ const preview = hex => {+ const c = cleanHex(hex)+ if (!c) return+ const de = document.documentElement+ applyAccent(de, c, de.dataset.theme)+ pending.current = c+ clearTimeout(timer.current)+ timer.current = setTimeout(commit, OWN_COLOR_SETTLE_MS)+ }+ const hasInput = !(own && !onCustom)+ useEffect(() => {+ const el = inputRef.current+ if (!el) return+ const onChange = () => { pending.current = cleanHex(el.value) || pending.current; commit() }+ el.addEventListener('change', onChange)+ return () => el.removeEventListener('change', onChange)+ }, [hasInput]) // eslint-disable-line react-hooks/exhaustive-deps+ useEffect(() => commit, []) // eslint-disable-line react-hooks/exhaustive-deps+ // The input is not controlled (React would put the saved colour back after every drag step);+ // a colour changed elsewhere (sync, another tab) is put in by hand.+ useEffect(() => {+ if (!pending.current && inputRef.current) inputRef.current.value = own || '#30d158'+ }, [own])const ownLabel = t('Your own color')+ const grey = own && isGrey(own)const notes = own && onCustom ? [- adjustedIn(own, 'dark') && t('A touch lighter in dark mode, so you can still read it.'),- adjustedIn(own, 'light') && t('A touch darker in light mode, so you can still read it.'),+ adjustedIn(own, 'dark') && (grey ? t('Greys show lighter in dark mode, so buttons don’t look switched off.') : t('A touch lighter in dark mode, so you can still read it.')),+ adjustedIn(own, 'light') && (grey ? t('Greys show darker in light mode, so buttons don’t look switched off.') : t('A touch darker in light mode, so you can still read it.')),].filter(Boolean) : []return <><div className="swatches" style={{ flexBasis: '100%', paddingInlineStart: 41 }}>@@ -1151,12 +1193,12 @@ function AccentSwatches({ S, update }) {<button key={k} className={'swatch' + (key === k ? ' on' : '')}style={{ background: c }} onClick={() => pickPreset(k)} aria-label={t(ACCENT_NAMES[k] || k)} />))}- {own && !onCustom+ {!hasInput? <button className="swatch swatch-own" style={{ background: own }} onClick={() => pickOwn(own)} aria-label={ownLabel} />: <span className={'swatch swatch-own' + (own ? ' on' : ' unset')} style={own ? { background: own, color: inkOn(own) } : undefined}>{own ? <Icon name="pencil" /> : <Icon name="plus" />}- <input type="color" className="swatch-input" value={own || '#30d158'}- onChange={e => pickOwn(e.target.value)}+ <input ref={inputRef} type="color" className="swatch-input" defaultValue={own || '#30d158'}+ onChange={e => preview(e.target.value)}aria-label={own ? t('Change your own color') : t('Pick your own color')} /></span>}</div>