diff --git a/frontend/src/components/MuscleExplorer.jsx b/frontend/src/components/MuscleExplorer.jsx index 9916377..d48eede 100644 --- a/frontend/src/components/MuscleExplorer.jsx +++ b/frontend/src/components/MuscleExplorer.jsx @@ -1,6 +1,6 @@ import { useMemo, useState } from 'react' import { useStore } from '../store/useStore.js' -import { BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js' +import { BODYPARTS, allExercises, equipmentOf, searchExercises } from '../lib/exercises.js' import { activeProfile, exAvailable } from '../lib/equipment.js' import { bestWeightFor } from '../lib/history.js' import { fmtNum } from '../lib/format.js' @@ -35,7 +35,7 @@ export default function MuscleExplorer({ onPick, onDetail, onPlan }) { ])), [catalog]) const pick = muscle => { setSelected(muscle === selected ? null : muscle); setEq(''); setShown(40) } const targeted = selected ? catalog.filter(e => musclesOf(e)[selected]) : [] - const base = targeted.filter(e => (!bp || e.bp === bp) && matchExercise(e, q)) + const base = searchExercises(targeted.filter(e => !bp || e.bp === bp), q) const eqOpts = equipmentOf(base) const eqOn = eqOpts.includes(eq) ? eq : '' // Favourites float to the top of whatever the filters left (issue #6), the rest keeps its order. diff --git a/frontend/src/lib/exercises.js b/frontend/src/lib/exercises.js index de64d69..3523d66 100644 --- a/frontend/src/lib/exercises.js +++ b/frontend/src/lib/exercises.js @@ -172,28 +172,38 @@ export const normalizeStr = s => (s || '') // is the i18n version (bumped by every setLang), so switching language rebuilds the translated // terms. Custom exercises are re-cached automatically — the store clones state on update, so an // edited exercise arrives as a new object the WeakMap has never seen. +// +// Each entry keeps the full corpus for substring matching and, separately, the words of the +// name (English and localized) that the typo tolerance below is allowed to compare against. const corpusCache = new WeakMap() function corpusOf(e) { const v = getVersion() const hit = corpusCache.get(e) - if (hit && hit.v === v) return hit.s + if (hit && hit.v === v) return hit const sm = Array.isArray(e?.sm) ? e.sm : [] + const name = normalizeStr(exerciseNameSearchText(e)) const s = normalizeStr([ - exerciseNameSearchText(e), + name, e?.tg || '', t(e?.tg || ''), e?.eq || '', t(e?.eq || ''), e?.bp || '', t(e?.bp || ''), ...sm, ...sm.map(m => t(m)), e?.desc || '' ].join(' ')) - corpusCache.set(e, { v, s }) - return s + const entry = { v, s, nameWords: name.split(/\s+/).filter(Boolean) } + corpusCache.set(e, entry) + return entry } // Allow one missing, extra or substituted character, or an adjacent transposition, in long // query tokens. Short tokens stay exact/substring-only: words such as "row" and "curl" are too // common for fuzzy matching to be useful. +// +// Only the exercise's own name words are ever compared this way. Body part, target and +// equipment words are shared by a whole slice of the catalogue, so one accidental neighbour +// ("wrist" ~ "waist", "power" ~ "lower arms", "drucken" ~ "rucken") would list hundreds of +// unrelated exercises ahead of the real hits (QA C26). function nearWord(a, b) { if (a.length < 5 || Math.abs(a.length - b.length) > 1) return false let i = 0 @@ -206,12 +216,33 @@ function nearWord(a, b) { return a.length > b.length ? a.slice(i + 1) === b.slice(i) : a.slice(i) === b.slice(i + 1) } +const queryTokens = query => normalizeStr(query || '').split(/\s+/).filter(Boolean) + +// Every token has to appear in the corpus; a token listed in `fuzzy` may instead be one edit +// away from a name word. +const matchTokens = (e, tokens, fuzzy) => { + const { s, nameWords } = corpusOf(e) + return tokens.every(tok => s.includes(tok) || (fuzzy.has(tok) && nameWords.some(word => nearWord(tok, word)))) +} + +// Single-exercise check, used where the list is filtered one option at a time (the exercise +// progress picker). Every token may fall back to the typo tolerance; lists go through +// searchExercises below, which knows whether a token needs it at all. export function matchExercise(e, query) { - if (!query) return true - const tokens = normalizeStr(query).split(/\s+/).filter(Boolean) + const tokens = queryTokens(query) if (!tokens.length) return true if (!e || typeof e !== 'object') return false - const corpus = corpusOf(e) - const words = corpus.split(/\s+/) - return tokens.every(tok => corpus.includes(tok) || words.some(word => nearWord(tok, word))) + return matchTokens(e, tokens, new Set(tokens)) +} + +// Search a list, exact hits first: a token that appears literally in at least one exercise is +// taken at its word for the whole list, and only a token with no exact hit anywhere ("bnech", +// "dumbell", "wirst") is allowed the typo tolerance. Otherwise a correctly spelled query such +// as "squat" or "clean" would also drag in "squad" and "lean", and since the callers keep +// catalogue order those strays would land ahead of the real matches (QA C26). +export function searchExercises(list, query) { + const tokens = queryTokens(query) + if (!tokens.length) return list + const fuzzy = new Set(tokens.filter(tok => !list.some(e => corpusOf(e).s.includes(tok)))) + return list.filter(e => matchTokens(e, tokens, fuzzy)) } diff --git a/frontend/src/lib/search-typo.test.js b/frontend/src/lib/search-typo.test.js index 8182599..18838c4 100644 --- a/frontend/src/lib/search-typo.test.js +++ b/frontend/src/lib/search-typo.test.js @@ -1,5 +1,5 @@ import { expect, it } from 'vitest' -import { matchExercise } from './exercises.js' +import { EXDB, matchExercise, normalizeStr, searchExercises } from './exercises.js' const benchPress = { n: 'dumbbell bench press', bp: 'chest', tg: 'pectorals', eq: 'dumbbell', @@ -24,3 +24,47 @@ it('keeps existing exact substring and all-token behavior', () => { expect(matchExercise(benchPress, 'press bench')).toBe(true) expect(matchExercise(benchPress, 'bench squat')).toBe(false) }) + +// QA C26: a correctly spelled word one edit away from a body part / target / equipment word +// used to pull in that whole body part ("wrist" ~ "waist" listed every abs exercise first). +it('never fuzzy-matches body part, target, equipment or description words', () => { + const sitUp = { n: '3/4 sit-up', bp: 'waist', tg: 'abs', eq: 'body weight', sm: [], desc: 'Keep the lower back flat.' } + for (const query of ['wrist', 'power', 'bodz weight']) { + expect(matchExercise(sitUp, query), query).toBe(false) + } + // The exact substring path still covers those fields. + expect(matchExercise(sitUp, 'waist')).toBe(true) + expect(matchExercise(sitUp, 'lower')).toBe(true) +}) + +it('searchExercises takes a word literally when it hits anything exactly, and only then falls back to typos', () => { + const list = [ + { n: 'band wrist curl', bp: 'lower arms', eq: 'band' }, + { n: 'waist twist', bp: 'waist', eq: 'body weight' }, + { n: 'all fours squad stretch', bp: 'upper legs', eq: 'body weight' }, + { n: 'barbell squat', bp: 'upper legs', eq: 'barbell' }, + { n: 'side plank', bp: 'waist', eq: 'body weight' }, + { n: 'slide lunge', bp: 'upper legs', eq: 'body weight' }, + benchPress, + ] + const names = q => searchExercises(list, q).map(e => e.n) + expect(names('wrist')).toEqual(['band wrist curl']) + expect(names('squat')).toEqual(['barbell squat']) + expect(names('slide')).toEqual(['slide lunge']) + // No exact hit anywhere: the typo-tolerant path finds the exercise, name words only. + expect(names('wirst')).toEqual(['band wrist curl']) + expect(names('bnech press')).toEqual(['dumbbell bench press']) + expect(names('dumbell bench')).toEqual(['dumbbell bench press']) + expect(names('sqat')).toEqual([]) + expect(searchExercises(list, ' ')).toBe(list) +}) + +it('searchExercises over the real catalogue returns only exact hits for correctly spelled words', () => { + const plain = (e, q) => normalizeStr([e.n, e.tg, e.eq, e.bp, ...(e.sm || [])].join(' ')).includes(q) + for (const q of ['wrist', 'power', 'slide', 'thigh', 'squat', 'clean']) { + const got = searchExercises(EXDB, q) + expect(got.length, q).toBe(EXDB.filter(e => plain(e, q)).length) + expect(got.every(e => plain(e, q)), q).toBe(true) + } + expect(searchExercises(EXDB, 'wrist')[0].n).toBe('band reverse wrist curl') +}) diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 019bd88..b93b303 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -1,7 +1,7 @@ import { useEffect, useMemo, useRef, useState } from 'react' import { useStore } from './store/useStore.js' import { useUI } from './store/useUI.js' -import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, matchExercise, exOr } from './lib/exercises.js' +import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, searchExercises, exOr } from './lib/exercises.js' import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js' import { fmtDate, fmtNum, capWords, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js' import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js' @@ -887,7 +887,7 @@ function ExercisePicker({ onPick, close }) { const all = allExercises(st) const profile = activeProfile(st) const inScope = e => bp === '★' ? usage[e.id] : bp === '☆' ? isFav(st, e.id) : (!bp || e.bp === bp) - let base = all.filter(e => inScope(e) && matchExercise(e, q)) + let base = searchExercises(all.filter(inScope), q) if (bp === '★') base = [...base].sort((a, b) => (usage[b.id] - usage[a.id]) || exerciseNameFor(a).localeCompare(exerciseNameFor(b))) const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(st, e)) : base const eqOpts = equipmentOf(eqFiltered) diff --git a/frontend/src/views/Library.jsx b/frontend/src/views/Library.jsx index f02836d..84ffd7d 100644 --- a/frontend/src/views/Library.jsx +++ b/frontend/src/views/Library.jsx @@ -1,7 +1,7 @@ import { useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' import { useStore } from '../store/useStore.js' -import { EXDB, BODYPARTS, allExercises, equipmentOf, matchExercise } from '../lib/exercises.js' +import { EXDB, BODYPARTS, allExercises, equipmentOf, searchExercises } from '../lib/exercises.js' import { MUSCLE_NAME } from '../lib/muscles.js' import { activeProfile, exAvailable } from '../lib/equipment.js' import { bestWeightFor } from '../lib/history.js' @@ -24,7 +24,7 @@ export default function Library() { const [shown, setShown] = useState(40) const bpStrip = useRef(null), eqStrip = useRef(null) const profile = activeProfile(S) - const base = allExercises(S).filter(e => (!bp || e.bp === bp) && matchExercise(e, q)) + const base = searchExercises(allExercises(S).filter(e => !bp || e.bp === bp), q) const eqFiltered = (profile && !showAll) ? base.filter(e => exAvailable(S, e)) : base const eqOpts = equipmentOf(eqFiltered) // Drop the equipment filter if the search narrowed it away, so you never hit a dead end.