17 KiB
BeatHound Software Documentation
This document describes how BeatHound works inside. It is for people who want to read, change, or test the code. Short explanations are used for technical ideas.
For instructions on using the app, see the user and development guide.
1. System overview
BeatHound is a single-page web app. It runs in the user's browser. React draws the page and keeps the current loop state. The Web Audio API creates the sound.
The app has no backend service. It does not send loop data to an API or save it in browser storage. Reloading the page starts a new empty loop.
Main tools:
- React builds the interface and manages state.
- TypeScript checks types before the app is built.
- Ionic React provides page and control components.
- Ionicons provides the control icons.
- Vite runs the local development server and builds the static site.
- Vitest runs the tests.
- Web Audio API creates the sounds in the browser.
2. Start-up and data flow
Start-up flow
index.htmldefines the page, metadata, and arootelement.src/main.tsxloads Ionic CSS andsrc/styles.css, sets up Ionic, and mounts React.src/App.tsxcreates the shared page shell, callsuseBeatStudio(), and keeps the active view.AppHeaderlets the user choose the Beat studio or About view from the top-right menu.StudioViewdisplays the sequencer.AboutViewdisplays general app information.useBeatStudio()combines the sequencer hook and sound palette hook.- Components receive values and callback functions as props. They display state and report user actions back to the hooks.
Most components do not own the loop data. The sequencer hook owns that data and passes the parts each component needs. The hook stays mounted in App while the user switches views, so the loop is still present when the user returns to the studio. Playback is stopped when the user opens the About view.
Add a sound flow
InstrumentSelectorshows categories fromINSTRUMENT_CATEGORIESinsrc/domain/instruments.tsin an Ionic select.- The user chooses a category and presses the plus button. A popover then shows only that category's instruments.
- Choosing an instrument calls
useBeatStudio.addSound(). It activates the instrument color and callsuseBeatSequencer.addBeat(). addBeat()creates a unique ID and asksgetNextAvailableStep()for an unused whole-number step.- The
beat-addedaction updates reducer state. The new point becomes selected, and its sound ring becomes focused. - React renders the new point and updates the legend. If the instrument supports pitch, the toolbar also shows its pitch control.
getNextAvailableStep() checks whole steps from the start of the current loop. If all whole steps are occupied, it returns step zero. This does not prevent two points from sharing a step.
Template flow
BeatTemplateSelectorreads the menu entries fromBEAT_TEMPLATES.- Selecting an entry calls
useBeatStudio.applyTemplate(). useBeatSequencer.loadTemplate()creates fresh IDs for its points and dispatchestemplate-loadedwith the points, tempo, and meter.- Playback position is reset. The palette activates each sound used by the template.
Templates replace the loop; they do not add points to the current loop. The Empty template loads no points and restores its own tempo and meter.
3. Core data and state
Sound point
The BeatPoint interface in src/domain/sequencer.ts is the data for one point:
| Field | Type | Meaning |
|---|---|---|
id |
string |
Unique ID for this point. |
soundId |
InstrumentId |
Instrument type, such as kick, piano, or shaker. |
step |
number |
Position in the loop. It can be a whole or fractional number. |
pitchSemitones |
number? |
Optional pitch offset for instruments that support pitch. |
The instrument ID type comes from the keys in src/domain/instruments.ts. Adding an instrument definition updates the TypeScript type and instrument catalog. src/domain/sounds.ts re-exports the older names for compatibility.
Sequencer state
SequencerState in src/domain/sequencerReducer.ts contains:
| Field | Meaning |
|---|---|
beats |
All sound points in the current loop. |
selectedBeatId |
ID of the point selected for moving or deleting, or null. |
focusedSoundId |
Sound ring currently selected, or null. |
tempoBpm |
Playback speed in beats per minute. |
beatsPerBar |
Number of beats in the loop. |
Playback status and the play marker are kept separately by useBeatPlayback. Sound colors are kept by useSoundPalette. This separates musical data from playback and display details.
Reducer actions
sequencerReducer() is a pure state update function. It receives the current state and one named action, then returns the next state. Actions cover adding, moving, pitching, selecting, and removing points; selecting an instrument; changing tempo and meter; and loading a template.
Important state rules:
- Selecting a point also focuses that point's sound ring.
- Selecting a ring clears the selected point.
- Removing a selected point removes only that point.
- Removing a focused ring removes every point of that sound type.
- Tempo changes are rounded and clamped to 60–180 BPM.
- Pitch changes are rounded and clamped to two octaves around the instrument's base note. Pitch is stored on the individual beat point.
- A shorter meter hides points beyond its loop length; the points remain in state and can become visible if the meter is lengthened again.
- Loading a template replaces the point list and sets the template tempo and meter.
assertNever() in the reducer makes TypeScript report an error if a new action type is added but not handled by the switch statement.
4. Loop and timing model
The constants and calculations are in src/domain/sequencer.ts:
| Rule | Value |
|---|---|
| Main steps per beat | 4 |
| Playback subdivisions per main step | 4 |
| Default meter | 4/4 |
| Default tempo | 112 BPM |
| Allowed tempo | 60–180 BPM |
| Allowed beats per bar | 2, 3, 4, 5, 6, 7, or 8 |
| Pitch range for supported instruments | ±24 semitones around the instrument's base note |
For a meter with N beats, the loop has N × 4 main steps. A 4/4 loop has 16 main steps. Playback subdivides every main step into four ticks, so a 4/4 loop has 64 playback ticks.
step values are continuous while a point is dragged. Playback rounds the point to the nearest subdivision by multiplying its step by four and rounding. A fractional position such as 2.25 is a supported tick; a position such as 2.1 is played at the nearest supported tick.
Tempo and tick duration
getPlaybackTickDurationMs(tempoBpm) returns:
60,000 milliseconds ÷ BPM ÷ 4 main steps per beat ÷ 4 ticks per main step
At 120 BPM, one playback tick is 31.25 milliseconds. Playback uses window.setInterval() with this duration.
Circular drawing
src/domain/timeline.ts contains math for converting positions:
getPointForStep()converts a step to an(x, y)point in the SVG. Step zero is at the top; later steps move clockwise.getStepFromPosition()converts pointer coordinates back to a step.wrapStepPosition()keeps keyboard movement inside the loop.getSoundOrbitRadius()gives each sound its own circle.getStackedPosition()moves same-sound points that land on the same playback tick a little apart on screen, so both can be seen. This visual offset does not change their stored or played step.
The SVG uses a 600 by 600 view box. Pointer coordinates are scaled from the displayed size to that view box before the step is calculated.
5. Playback and audio
Playback hook
useBeatPlayback() owns these playback values:
isPlaying: whether the timer is running.isStarting: whether the browser audio context is starting.currentStep: the position shown by the play marker. It is-1when stopped.audioError: a message to show when browser audio cannot start.
The hook keeps the latest beats and loop length in refs. The timer callback can then read current data without restarting only because the beat list changed.
When playback starts, the hook advances once immediately, then starts an interval. Each tick updates the play marker and plays every point whose rounded playback tick matches the current tick. The audio engine also receives that point's pitch offset. When playback stops, the current tick returns to the start. If there are no visible points, playback stops. Changing the meter wraps the current tick into the new loop length.
Audio engine
src/audio/AudioEngine.ts owns one AudioContext:
start()checks for the browser's standard or WebKit audio context.- It creates the context if needed and resumes it.
play(instrumentId, pitchSemitones)looks up the instrument's function inINSTRUMENT_VOICESand calls it only when the context is running.dispose()closes the context when the hook is removed.
Audio starts after the user presses Play. This supports browser rules that require a user action before audio can play.
Sound functions
src/audio/instruments.ts contains the Web Audio graphs for the catalog instruments. Drums and percussion use oscillators, filtered noise, or both. Bass, Keys, Strings, Winds, and Synth use pitched oscillator voices. Pitch-capable voices convert semitones to frequency with baseFrequency × 2^(semitones / 12).
The INSTRUMENT_VOICES object in src/audio/soundVoices.ts maps each InstrumentId to its function. AudioEngine does not need an instrument-specific conditional. An instrument's supportsPitch value controls whether the toolbar displays the pitch slider.
Timing limits
The app uses a JavaScript interval to decide when to play sounds. Browser scheduling can be delayed by a busy page, background tabs, or the device. The Web Audio API makes each sound itself, but this version does not schedule all future notes on the audio clock. For more precise timing, the playback scheduler would need to schedule audio events ahead of time with AudioContext.currentTime.
6. UI component and hook responsibilities
Components
| Component | Responsibility |
|---|---|
App |
Creates the shared app shell, owns studio state, and selects the active view. |
AppHeader |
Shows the brand and opens the view menu with the Ionic ellipsisVertical icon. |
StudioView |
Displays the beat loop and template controls. |
AboutView |
Displays project version, license, technology stack, repository, and issue tracker links. |
BeatLoopPanel |
Connects timeline, meter, tempo, sound ring, selection hint, and delete action. |
InstrumentSelector |
Selects a category; its plus button opens a menu of that category's instruments. |
PitchControl |
Changes pitch for a selected point when its instrument supports pitch. |
CircularTimeline |
Draws rings, ticks, points, and play marker; handles pointer and keyboard input. |
TransportBar |
Starts/stops playback and holds the instrument selector and pitch control. |
BeatTemplateSelector |
Displays and selects templates. |
TempoControl |
Displays and changes tempo using an Ionic range. |
TimeSignatureSelector |
Displays and changes beats per bar. |
SoundRingSelector |
Selects one of the sound rings. |
BeatSelectionHint |
Shows the selected point position or selected sound ring. |
Hooks
| Hook | Responsibility |
|---|---|
useBeatStudio |
Joins sequencer actions with sound palette activation. |
useBeatSequencer |
Owns reducer state and exposes typed sequencer operations to components. |
useBeatPlayback |
Owns audio startup, tick timer, play marker, and playback errors. |
useSoundPalette |
Assigns one stable color to each sound type activated in the current page session. |
usePopoverDisclosure |
Tracks the open/closed state used for accessible popover labels. |
Components are mostly presentational: they receive state and callbacks through props. State updates happen in hooks and the reducer.
AppView in src/views/viewTypes.ts is the union of the supported view names: studio and about. The header reports a requested view to App; it does not render view content itself. App chooses the matching view component. This keeps navigation, the studio, and app information in separate modules.
AboutView reads its version, license URL, repository URL, and issue URL from src/config/projectInfo.ts. The version comes from package.json, so it stays in sync with the app package metadata. Project links are kept in one file so they can be updated without changing the view layout.
7. Input and accessibility behavior
CircularTimeline uses SVG groups and circles with button roles and accessible labels.
- Pointer-down on a sound point selects it and captures the pointer. Pointer movement changes its step. Pointer-up or pointer-cancel ends the drag.
- Arrow keys move a focused point by one playback subdivision:
1 / PLAYBACK_SUBSTEPS_PER_STEPof a main step. - Shift plus an arrow key moves by one full main step.
- Arrow movement wraps from the end of the loop to its start, and from the start to its end.
- Enter or Space on a sound orbit selects that sound ring.
- Ionic controls provide labeled buttons, popovers, and range input for other settings.
The selection state is used by the trash button to decide whether to delete one point or all points on the focused ring.
8. Extend the software
Add an instrument
- Add its ID, label, description, category, and
supportsPitchvalue insrc/domain/instruments.ts. - Add its ID to the matching entry in
INSTRUMENT_CATEGORIESin the same file. - Add a function that accepts an
AudioContextand pitch value insrc/audio/instruments.ts. - Add an entry for the new ID in
INSTRUMENT_VOICESinsrc/audio/soundVoices.ts. - Add or update tests for catalog membership, pitch behavior, or new sound behavior.
The catalog drives the toolbar dropdown. TypeScript requires the voice map to include every InstrumentId. Sound colors are assigned by the palette hook. Avoid adding instrument-specific branches to the timeline or sequencer hook unless an instrument needs different behavior.
Add a template
- Add a new ID to
BeatTemplateIdinsrc/domain/beatTemplates.ts. - Add a template to
BEAT_TEMPLATESwith label, description, meter, tempo, and points. - Make sure every point has an instrument ID from
InstrumentIdand a step from zero up to, but not including,beatsPerBar × STEPS_PER_BEAT. - Keep the template test passing or add a test for any special rule.
The selector reads its options from BEAT_TEMPLATES, so no separate menu option is needed.
Change timing rules
Timing constants are in src/domain/sequencer.ts; circle conversion is in src/domain/timeline.ts; playback tick matching is in src/hooks/useBeatPlayback.ts. These parts must agree about subdivisions. If the number of playback subdivisions changes, review keyboard movement, point rounding, tick duration, tick drawing, and tests together.
9. Tests, configuration, and build output
src/sequencer.test.ts uses Vitest in the Node test environment. It covers:
- Converting between loop steps and circle coordinates.
- Fractional steps, wrapping, and playback tick duration.
- Finding a step for a new point.
- Unique colors.
- Reducer behavior for templates, deletion, meter changes, and tempo limits.
- Template tempo and point bounds.
Run all project checks from the repository root:
npm run lint
npm run build
npm test
The scripts are defined in package.json. npm run build first runs TypeScript with no output, then Vite writes the app's static production site to dist/. The React plugin and Vitest environment are set in vite.config.ts. TypeScript strict options are in tsconfig.json; ESLint rules are in eslint.config.js.
The documentation site uses VitePress. Run npm run docs:dev to work on it locally, npm run docs:build to create its static files in docs/.vitepress/dist/, and npm run docs:preview to view that build. The pages are Markdown files under docs/; navigation and local search are set in docs/.vitepress/config.mts.
The project includes a web manifest and home-screen icons in public/, but it does not include a service worker, offline caching, persistence, a native mobile wrapper, or a server deployment configuration.
10. Main implementation limits
- A loop exists only in page memory. There is no save, load, or export feature.
- The instrument catalog has 16 built-in synthesized instruments in seven categories.
- Pitch controls are available only for instruments marked
supportsPitch. - Playback timing uses a browser interval and may drift under load.
- Points are rounded to one of four playback subdivisions per main step when they play.
- The app makes audio with browser-generated oscillators and noise. It does not load user audio files.
- The repository builds a static web app; native app packaging is not configured here.