Annotations
Annotations are time ranges with text: a transcript, chapters, markers. An annotation store owns them: your app makes it and gives it to the provider, which shows what the store holds; a row of boxes under the waveform and a text list draw them. The same store and the same components work under WebAudioProvider and MediaElementProvider.
Installation
The components that draw annotations are in a package of their own:
npm install @waveform-playlist/annotations@next
Quick Start
Make an annotation store with useCreateAnnotationStore, pass it to the provider's annotationStore prop, and render AnnotationProvider above the view. <Waveform /> then draws the row of annotation boxes and, below the view, the annotation text list.
import {
WebAudioProvider,
Waveform,
useCreateArrangement,
useCreateAnnotationStore,
} from '@waveform-playlist/browser';
import { AnnotationProvider } from '@waveform-playlist/annotations';
import { audioTrack } from '@waveform-playlist/core';
function AnnotatedPlaylist() {
const arrangement = useCreateArrangement(() => [
audioTrack({ src: '/audio/podcast.mp3', name: 'Podcast' }),
]);
const annotationStore = useCreateAnnotationStore(() => [
{ id: '1', start: 0, end: 5, lines: ['Introduction'] },
{ id: '2', start: 5, end: 15, lines: ['Topic Overview'] },
{ id: '3', start: 15, end: 30, lines: ['Main Discussion'] },
]);
return (
<WebAudioProvider
arrangement={arrangement}
annotationStore={annotationStore}
annotationList={{ editable: true }}
>
<AnnotationProvider>
<Waveform />
</AnnotationProvider>
</WebAudioProvider>
);
}
AnnotationProvider hands the components of @waveform-playlist/annotations to the browser package. It can be above or below the playlist provider. Without it:
- the row of boxes draws nothing, without a warning;
- the text list draws nothing and, in a development build, writes one warning to the console;
- the three checkboxes and the download button (below) still work: they read the playlist provider, not
AnnotationProvider.
The store still holds the annotations and useAnnotations() still returns them.
start and end must be finite numbers (seconds), and no two annotations may have the same id. The store checks every annotation it is given, in every build, and throws a TypeError for a list that breaks either rule (see What the store refuses). Convert Aeneas fragments with parseAeneas first.
Keep the list in time order, without overlaps: see What a List Must Be.
Annotation Structure
interface AnnotationData {
id: string; // Unique identifier
start: number; // Start time in seconds
end: number; // End time in seconds
lines: string[]; // Text content as array of lines
language?: string; // Optional language code (e.g., 'en', 'es')
startTick?: number; // Optional musical position (ticks)
endTick?: number;
}
What a List Must Be
| Rule | Checked by the store |
|---|---|
Every start and end is a finite number (seconds). | Yes: a TypeError (see What the Store Refuses) |
No two annotations have the same id. | Yes: a TypeError |
| No annotation ends before it starts (a start equal to its end is allowed). | No |
The annotations are in time order, by start. | No |
No two annotations overlap. They may touch: one's end equal to the next one's start. | No |
An edge drag and the boundary keys take an annotation's neighbours from its place in the list, so a list that breaks one of the last three rules gets edits that stop at or move the wrong annotation, or leave one ending before it starts. Sort the list before you give it to the store, and keep it sorted when you insert. An annotation may be shorter than the 0.1 s minimum of an edge drag (loaded that way).
The Annotation Store
The store is the one place the annotations are kept. The provider, the boxes, the list, the keyboard shortcuts and your own components all read it, and every change, yours or the library's, is a call to one of its methods. Nothing keeps a copy that it writes back, so two changes made in the same tick both land, whoever makes them.
interface AnnotationStore {
/** The current annotations. The same array until a change. Never write to it. */
getAnnotations(): readonly AnnotationData[];
/** Be told after every change; `change.renamed` lists the ids `rename` changed. */
subscribe(listener: (change?: AnnotationStoreChange) => void): () => void;
/** Replace the annotations. */
set(annotations: readonly AnnotationData[]): void;
/** Change the annotations: `fn` gets the current array and returns the next. */
update(fn: (current: readonly AnnotationData[]) => readonly AnnotationData[]): void;
/** Give an annotation a new id, and say it was a rename (the selection follows it). */
rename?(from: string, to: string): void;
}
interface AnnotationStoreChange {
/** Old id to new id, for each annotation `rename` gave a new id; empty for `set` and `update`. */
readonly renamed: ReadonlyMap<string, string>;
}
Rename an annotation with rename(from, to), not with set or update: a new id in a list is a removal and an add to everything that follows an annotation by its id, and the selection is cleared. The stores made by useCreateAnnotationStore and createAnnotationStore have rename; a store of your own may leave it out.
The type is exported by @waveform-playlist/core.
Making One
In a React component, useCreateAnnotationStore(init?, options?) from @waveform-playlist/browser makes one store per component instance and returns the same store on every render. init is read once, on the first render; a list it returns that the store refuses throws out of the render, to the nearest error boundary above the component. The store holds what init returns, or nothing when there is no init.
Outside React, or for a store that lives in a module of your own, createAnnotationStore(initial?, options?) from @waveform-playlist/core does the same; it throws a TypeError for an initial list it refuses.
Reading It
useStoredAnnotations(store) returns the store's list and re-renders the component when it changes. It takes the store as its argument, so it works above the provider as well as below it. Below the provider, useAnnotations().annotations is the same list.
import { useStoredAnnotations } from '@waveform-playlist/browser';
import type { AnnotationStore } from '@waveform-playlist/core';
function AnnotationCount({ store }: { store: AnnotationStore }) {
const annotations = useStoredAnnotations(store);
return <span>{annotations.length} annotations</span>;
}
The list is the same array until the annotations change. Never write to it: it is typed readonly AnnotationData[], and in a development build the array, each annotation and each annotation's lines are frozen. A development build here is one where process.env.NODE_ENV is anything but 'production' (what a bundler's dev server gives; an unset NODE_ENV counts too); a page that loads the module with no bundler and no process freezes nothing. On a frozen list annotations.sort(…) or .push(…) throws a TypeError in any code, and an assignment (annotation.end = 4) throws in strict code, which includes every module (in sloppy-mode script it is silently ignored). In a production build nothing is frozen, and such a write changes the list every reader shares. Copy first: [...annotations].sort((a, b) => a.start - b.start).
Changing It
set(list) replaces the annotations; update(fn) calls fn with the current list and stores what it returns; rename(from, to) gives one annotation a new id (see above). All three apply before they return: the next getAnnotations(), and the current of the next update, already hold the change. An update whose fn returns current itself changes nothing and tells nobody.
// Load a file
annotationStore.set(fragments.map(parseAeneas));
// Add one at the end
annotationStore.update((current) => [
...current,
{ id: crypto.randomUUID(), start: 12, end: 14, lines: ['New annotation'] },
]);
// Remove one
annotationStore.update((current) => current.filter((a) => a.id !== id));
Below the provider, usePlaybackControls().annotationStore is the store passed to the provider (undefined without one), for a component deep in the tree:
import { usePlaybackControls, usePlaybackRefs } from '@waveform-playlist/browser';
function AddAtCursorButton() {
const { annotationStore } = usePlaybackControls();
const { currentTimeRef } = usePlaybackRefs();
return (
<button
type="button"
disabled={!annotationStore}
onClick={() => {
const start = currentTimeRef.current;
annotationStore?.update((current) => [
...current,
{ id: crypto.randomUUID(), start, end: start + 2, lines: [''] },
]);
}}
>
Add annotation
</button>
);
}
Saving the Annotations
The store tells its subscribers after every change. To save the annotations, subscribe to it, or read it with useStoredAnnotations and save from an effect:
const annotations = useStoredAnnotations(annotationStore);
useEffect(() => {
localStorage.setItem('annotations', JSON.stringify(annotations));
}, [annotations]);
// or, outside a component
const unsubscribe = annotationStore.subscribe(() => {
save(annotationStore.getAnnotations());
});
A subscriber that throws is reported with a console warning; the other subscribers are still told.
Your Rules for Every Change: beforeChange
beforeChange(next, current) is called for every set, update and rename, the library's included (an edge release, a boundary key, a text or action-button edit in the list, and its id edit, which is a rename). A rule that refuses a rename refuses it whole; one that returns a list without the new id in place of the old is not reported as a rename: the selection is cleared if the list no longer holds the old id, and stays if it does. It gets the proposed list and the current one, and returns the list to store:
nextstores the change;currentrefuses it: nothing changes and no subscriber is told;- another list adjusts it: that list is stored (and checked as any other list).
It is not called for the initial list, nor when the proposed list is the current array itself (an update that returns current). Nor is it called for a list that fails the store's checks: those run first and throw (see What the Store Refuses), so a rule cannot repair an invalid list.
// Refuse an edit that leaves an annotation without text
const annotationStore = useCreateAnnotationStore(() => initialAnnotations, {
beforeChange: (next, current) =>
next.some((a) => a.lines.join('').trim() === '') ? current : next,
});
// Keep every annotation inside the first 60 seconds
const LIMIT = 60;
const annotationStore = useCreateAnnotationStore(() => initialAnnotations, {
beforeChange: (next) =>
next.some((a) => a.end > LIMIT)
? next.map((a) =>
a.end > LIMIT ? { ...a, start: Math.min(a.start, LIMIT - 0.1), end: LIMIT } : a
)
: next,
});
What the user sees when a change is refused or adjusted: an edge released where the rule refuses it goes back to where the store has it, a refused boundary key does nothing, and a text or id field whose edit was not stored shows the stored value again. With the built-in boxes (which use the provider's preview) the boxes show a dragged edge where the pointer is, and the rule applies once, on release. A row of boxes of your own that calls useAnnotationDragHandlers without preview writes every move with update, so the rule applies to each move.
useCreateAnnotationStore follows beforeChange: the store calls the function passed on the most recent committed render, so a rule that reads your component's state sees its current value. createAnnotationStore keeps the function it was given.
Return current to refuse; do not throw. A throw from beforeChange reaches the caller of set or update, and the store keeps its value.
What the Store Refuses
Every list the store is given (the initial list, set, what update's function returns, what beforeChange returns) is checked: each annotation has a finite numeric start and end, and no two annotations have the same id. A list that fails either check throws a TypeError from the call, and the store keeps its value. The store does not check the order of the list, overlaps, or that no annotation ends before it starts (see What a List Must Be):
[waveform-playlist] Invalid annotations: annotation "f001" needs numeric start and end (got string and string). Parse text formats first, e.g. parseAeneas() from @waveform-playlist/annotations.
[waveform-playlist] Invalid annotations: two annotations have the id "3".
The id field of the annotation list writes nothing for a duplicate id and shows the stored id again (see AnnotationList).
Changes During an Edge Drag
While an edge is dragged, the boxes and the list show the store's current list with the drag's moves on top. A change made elsewhere during the drag (a live feed that adds annotations, a text edit, a set) is drawn at once, and each move of the pointer is worked out over that current list: a neighbour your app moved during the drag stops the edge, or is carried by it, from where it is now, and with linkEndpoints on an edge dragged into a neighbour still carries it along (see Linked Endpoints).
The drag keeps the start and end of every annotation it has touched, the dragged one and each neighbour it moved, also one moved back to where it was. On release it writes those bounds, found by id in the store's list as it is then; nothing else is written, so an annotation added during the drag stays, and so does any other edit made elsewhere, except to the start and end of an annotation the drag has touched: those are the drag's.
The drag ends and writes nothing more, its preview cleared, when the dragged annotation is removed from the store (a "clear all" included), when the provider is given another store, or when the component that drags unmounts. Without preview the moves already written stay.
Provider Configuration
annotationStore Prop
Both providers take the same prop, an AnnotationStore. The provider publishes what the store holds (useAnnotations()) and writes nothing back. Without it there are no annotations: useAnnotations().annotations is [], the boxes and the list draw nothing, and the drag, the boundary keys and the list's edits have nothing to write to.
annotationList Prop
Both providers take the same prop (type AnnotationListProp), which holds the three annotation options. The annotations are not here: they are the store's.
interface AnnotationListProp {
editable?: boolean; // Annotations can be edited (text, ids, edges). Default: false
linkEndpoints?: boolean; // A dragged edge takes the edge it touches along. Default: false
isContinuousPlay?: boolean; // Playback runs on past the end of an annotation. Default: false
}
The three options are provider state that follows the prop. Each starts from its field (a field left out is false). When the value of a field changes, the option takes the new value. Between two changes of the prop, a setter or one of the checkboxes changes the option; the prop is not told, and its next change wins for the field that changed. So you can do either of these:
- keep the options in your own state and pass them in
annotationList; - pass starting values (or nothing) and let the user change the options with the checkboxes.
Reading and Setting the Options
import { useAnnotationOptions, usePlaybackControls } from '@waveform-playlist/browser';
const { editable, linkEndpoints, continuousPlay } = useAnnotationOptions();
const { setAnnotationsEditable, setLinkEndpoints, setContinuousPlay } = usePlaybackControls();
Both hooks work under both providers. useAnnotations() returns { annotations }, the store's list (read-only), and useActiveAnnotation() returns { activeAnnotationId, playingAnnotationId } (see The Selected Annotation and the Playing One).
What each option does:
| Option | On |
|---|---|
editable | The boxes show a handle on each edge, and an edge can be dragged. In the list, the text and the id of a row can be edited in place, and the actions buttons are shown. |
linkEndpoints | See Linked Endpoints for the edge drag. The boundary shortcuts read it too, and follow the same rules as a drag (their upper limit is the end of the audio): with it on, a nudged edge moves the touching edge of the neighbour with it, and stops at a neighbour it does not touch. It is also handed to list actions. |
continuousPlay | A clicked annotation plays from its start and playback runs on. Off: playback ends where the annotation ends. The option is about a play of an annotation only (a click on its box or row, Enter, playAnnotation): a play started any other way is never cut at an annotation's end. |
The Selected Annotation and the Playing One
These are two values, read with useActiveAnnotation() under either provider:
import { useActiveAnnotation } from '@waveform-playlist/browser';
const { activeAnnotationId, playingAnnotationId } = useActiveAnnotation();
activeAnnotationIdis the selection. The user writes it (a click on a box or a list row, the selection keys) and so does your code (setActiveAnnotationId(id)fromusePlaybackControls()). Playback never changes it. Stop, the end of the audio or the timeline,seekToandsetSelectionleave it as it is. UnderMediaElementProvider, new audio (anothersourceorwaveformData) sets it tonull. It always names an annotation the store holds: it becomesnullwhen that annotation leaves the store, follows it through the store'srename, and an id given tosetActiveAnnotationIdthat the store does not hold (judged when the provider renders, so the same batch as thesetthat adds it is fine) is ignored, as if the call had not been made.playingAnnotationIdis the annotation the playhead is in while playing (start <= time < end; with annotations that overlap, the first one in list order). It isnullin a gap between annotations, it is kept on pause, and it isnullonce playback stops (Stop, playback ending by itself, and underWebAudioProvidera start that throws or an engine that cannot be rebuilt during playback). Only playback writes it: there is no setter. The frames of a running play work it out, so a seek while paused does not move it until playback runs again. UnderMediaElementProvider, a player replaced for the same audio (the track renamed, for example) stops playback and leaves it as a pause does.
The boxes and the list draw both. The selected box and row have the active look. The playing box and row have aria-current="true" and, when they are not also the selected ones, a lighter look of their own; a box or row that is both shows the selected look. The colours are theme keys, see Styling Annotations.
With continuous play off, a play ends at an annotation's end only when it is a play of that annotation: a click on its box or row, Enter with <KeyboardShortcuts annotations />, or playAnnotation(annotation). The Play button, Space, play(), play(start) and play(start, duration) are not cut at an annotation's end, whether or not an annotation is selected. A play of an annotation that is paused and resumed from the cursor (the Play button, Space, play()) is still that play: with continuous play off it ends at the annotation's end, and the cursor returns to where the play of the annotation began. A play from another position (play(start)) or with a length of its own (play(start, duration)) is a plain play, and so is a resume made with continuous play on. With a range highlighted (and looping off) the Play button and Space play the range instead, which is a plain play.
A Stop, a seekTo or a setSelection (and setCurrentTime from useEditorControls(), which moves the cursor) ends the play of the annotation, also while it is paused: what plays after it is a plain play. Continuous play switched on while the play is running takes the annotation's end away for the rest of that play, also when the annotation was moved or removed meanwhile, and switching it off again does not bring the end back. Under WebAudioProvider there are two cases where the end stays: an annotation that starts inside the highlighted selection and ends where the selection ends is played as the selection, which continuous play does not affect, and a switch made while the engine is being rebuilt reschedules nothing.
The Two Components
The ready-made views (<Waveform />, <WaveformEditor />, <MediaElementWaveform />) take className only. They draw the boxes and the list with their defaults: a box is labelled with the annotation's id, the row is 30 px high, the list is at most 200 px high and has no action buttons. To give either one an option, compose the view from its parts:
import {
WaveformRoot,
WaveformTimescale,
WaveformLoopRegion,
WaveformTrackControls,
WaveformTracks,
WaveformAnnotationBoxes,
WaveformSelection,
WaveformPlayhead,
AnnotationList,
} from '@waveform-playlist/browser';
import type { AnnotationData } from '@waveform-playlist/core';
// Defined outside the component: a new function renders every box.
const boxLabel = (annotation: AnnotationData, index: number) => String(index + 1);
<WaveformRoot>
<WaveformTimescale />
<WaveformLoopRegion />
<WaveformTrackControls />
<WaveformTracks />
<WaveformAnnotationBoxes getLabel={boxLabel} height={30} />
<WaveformSelection />
<WaveformPlayhead />
</WaveformRoot>
<AnnotationList height={300} actions={annotationActions} />
Under MediaElementProvider the root is <MediaElementWaveformRoot> and its parts are <WaveformTimescale />, <WaveformTracks />, <WaveformAnnotationBoxes />, <WaveformSelection /> and <WaveformPlayhead />. See Composing the View.
WaveformAnnotationBoxes
The row of annotation boxes. It is a part of the view: a child of WaveformRoot or MediaElementWaveformRoot.
| Prop | Type | Default | Description |
|---|---|---|---|
getLabel | (annotation: AnnotationData, index: number) => string | the annotation's id | The label of a box. Pass a function that keeps its identity (defined outside the component, or memoized): a new one renders every box. |
height | number | 30 | Height of the row in pixels. |
A click on a box selects its annotation and plays it from its start. The box of the selected annotation has the active look; the box the playhead is in while playing has aria-current="true" and, when it is not the selected one, a lighter look.
The part wires the drag of the edges itself: it has its own DragDropProvider around the row. While the editable option is on, an edge can be dragged. The boxes and the list follow the drag as it moves, and the store is written once, on release (see Changes During an Edge Drag). Escape cancels the drag and puts back every annotation it moved. An edge can be dragged as far as the timeline is drawn, which can be past the end of the audio (an empty timeline is drawn 60 seconds long; a recording and a view that fills its container draw past the audio too), so annotations can mark what is not recorded yet. You do not call useAnnotationDragHandlers for it, and a DragDropProvider of your own around the view does not receive the drag of an annotation edge.
By default the drag starts after the pointer has moved 1 px. With <ClipInteractionOptions touchOptimized> (or <ClipInteractionProvider touchOptimized>) above the view, a touch must be held 250 ms first, so a swipe can scroll the page:
import { ClipInteractionOptions } from '@waveform-playlist/browser';
<ClipInteractionOptions touchOptimized>
<Waveform />
</ClipInteractionOptions>
The keyboard does not move an edge handle. Under WebAudioProvider, the keyboard shortcuts move the edges of the selected annotation.
AnnotationList
The annotation text list. Render it anywhere under the provider: below the view, in a sidebar, more than once. It is not a part of the root.
| Prop | Type | Default | Description |
|---|---|---|---|
height | number | - | Height of the list in pixels. Without it the list is at most 200 px high. |
actions | AnnotationAction[] | - | Buttons shown on each row while the editable option is on. Pass an array that keeps its identity: a new one renders every row. |
scrollActivePosition | 'center' | 'start' | 'end' | 'nearest' | 'none' | 'center' | Where a row is put when the list scrolls to it: the selected row when the selection changes, the playing row when playback moves to it. 'none': the list follows neither. |
scrollActiveContainer | 'nearest' | 'all' | 'nearest' | Which containers scroll: only the list, or the page too. |
children | (item: RenderAnnotationItemProps) => ReactNode | - | Draws a row, in place of the default one. |
The list draws nothing while there are no annotations.
A click on a row selects the annotation and plays it from its start, as a click on its box does. The row of the playing annotation has aria-current="true". In the default row, a click in a field that is being edited places the caret, and a click on an action button runs the action; neither plays the annotation.
While editable is on, the text and the id of a default row can be edited in place. The edit is written to the store when the field loses focus; Enter leaves the field. A field that loses focus with its text unchanged writes nothing, and no subscriber is told. The row's annotation is found by its id in the store's list as it is then, so an annotation added or removed elsewhere in the meantime does not send the edit to another row. An empty id, and an id another annotation already has, are not accepted: nothing is written and the field shows the stored id again. A field whose edit the store did not keep (refused by beforeChange) shows the stored value again.
Action Buttons
An action is called with the annotation, its index, the annotations, and the provider's { linkEndpoints, continuousPlay }. The array and the annotations it holds (with their lines) are copies of the store's list as it is when the button is pressed, so the action changes them in place; the list then writes the result to the store. index is the annotation's position in that list. Annotations the action did not change keep their objects.
import type { AnnotationAction } from '@waveform-playlist/core';
// Outside the component, so the array keeps its identity.
const annotationActions: AnnotationAction[] = [
{
text: '+',
title: 'Move the end 10 ms later',
action: (annotation, index, annotations, opts) => {
annotation.end += 0.01;
const next = annotations[index + 1];
if (opts.linkEndpoints && next) next.start += 0.01;
},
},
{
text: '🗑',
title: 'Delete annotation',
action: (annotation, index, annotations) => {
annotations.splice(index, 1);
},
},
];
<AnnotationList actions={annotationActions} />
An action has a title and either a text or a class (the class names of an icon, written with dots: 'fas.fa-trash'). The types AnnotationAction and RenderAnnotationItemProps are exported by @waveform-playlist/core, which the browser package depends on.
Custom Rows
Pass a function as the child to draw the rows yourself. It is called with { annotation, index, isActive, isPlaying, onClick, formatTime }. isActive: the annotation is the selected one. isPlaying: the playhead is in it while playing (kept on pause). onClick plays the annotation. The list wraps what the function returns in a <div> that has aria-current="true" for the playing annotation. Define the function outside the component (or memoize it): one written inline is a new function on every render of your component and renders every row.
import type { RenderAnnotationItemProps } from '@waveform-playlist/core';
const rowBackground = (isActive: boolean, isPlaying: boolean) =>
isActive ? '#ffe0b2' : isPlaying ? '#fff3e0' : 'transparent';
const renderRow = ({
annotation,
isActive,
isPlaying,
onClick,
formatTime,
}: RenderAnnotationItemProps) => (
<div onClick={onClick} style={{ background: rowBackground(isActive, isPlaying) }}>
<strong>
{formatTime(annotation.start)} - {formatTime(annotation.end)}
</strong>
<p>{annotation.lines.join(' ')}</p>
</div>
);
<AnnotationList height={200}>{renderRow}</AnnotationList>
A custom row has no editable fields and no action buttons: those belong to the default row.
Option Checkboxes
Three checkboxes show and set the provider's options, and a button downloads the annotations. Import them from @waveform-playlist/annotations. They work under both providers and need only the playlist provider above them, not AnnotationProvider; without a playlist provider they throw.
import {
ContinuousPlayCheckbox,
LinkEndpointsCheckbox,
EditableCheckbox,
DownloadAnnotationsButton,
} from '@waveform-playlist/annotations';
<ContinuousPlayCheckbox />
<LinkEndpointsCheckbox />
<EditableCheckbox />
<DownloadAnnotationsButton filename="annotations.json" />
The checkboxes take disabled and two more props: children, the label (default "Continuous Play", "Link Endpoints" and "Editable Annotations"), and className, on the element that wraps the input and its label. Their props type is AnnotationCheckboxProps.
The download button writes the provider's annotations as Aeneas JSON. Its props: filename (default annotations.json), children, the label (default "Download JSON"), title, disabled and className. It is also disabled while there are no annotations. title is the tooltip: left out, it is "No annotations to download" while there are none and "Download the annotations as JSON" otherwise; given, it is used in both cases. Every string the four controls draw can so be supplied by your app: children on all four, title on the button.
<EditableCheckbox>Allow editing</EditableCheckbox>
<DownloadAnnotationsButton filename="chapters.json" disabled={saving}>
Save chapters
</DownloadAnnotationsButton>
Linked Endpoints
With linkEndpoints on:
- An edge that is within 10 ms of its neighbour's edge moves that edge with it, so the two annotations stay joined. It stops where the neighbour reaches 0.1 s; the neighbour is never covered, and the annotations after it do not move.
- An edge that is further from its neighbour stops when it reaches the neighbour. From there the two edges touch, and a drag that goes on carries the neighbour's edge along.
With linkEndpoints off:
- An edge stops at its neighbour's edge; the neighbour does not move. Between two annotations that touch, the shared edge can only move away from the neighbour: turn
linkEndpointson to move both. - A gap under 10 ms is not closed for you; an edge can be dragged up to its neighbour.
In both cases an annotation cannot be made shorter than 0.1 s by dragging one of its own edges.
Keyboard Shortcuts
WebAudioProvider only. <KeyboardShortcuts annotations /> turns on the annotation shortcuts; it reads the annotations and the options from the provider.
import { KeyboardShortcuts } from '@waveform-playlist/browser';
<KeyboardShortcuts playback annotations />
| Key | Action |
|---|---|
↑ / ← | Select the previous annotation |
↓ / → | Select the next annotation |
Home / End | Select the first / last annotation |
Escape | Deselect the annotation. With playback on, Escape stops instead while playing (the annotation stays selected; the next Escape deselects it), and with nothing selected |
Enter | Play the selected annotation, as a click on it does (playAnnotation): with continuous play off, playback ends where the annotation ends |
[ / ] | Move the start of the selected annotation 10 ms earlier / later |
Shift+[ / Shift+] | Move the end of the selected annotation 10 ms earlier / later |
A shortcut of your own in additionalShortcuts on one of these keys runs in place of the annotation key. To give an action another key, pass annotationShortcuts, one binding per action: <KeyboardShortcuts annotations annotationShortcuts={{ moveStartEarlier: { key: ',' } }} /> (the actions are selectPrevious, selectNext, selectFirst, selectLast, clearSelection, moveStartEarlier, moveStartLater, moveEndEarlier, moveEndLater, playActive). A layout that types [ with Option or AltGr may need that: a key press that reports Alt as held does not match a binding without it (not run on a real layout). The selection wraps around at both ends of the list. The last three rows need a selected annotation. The boundary keys work whether or not editable is on. A boundary key that cannot move the edge (a start at 0, an end at the end of the audio, an annotation already at its shortest) changes nothing and tells no subscriber.
useAnnotationKeyboardControls
The hook behind <KeyboardShortcuts annotations />, for a component of your own. Calling it installs the shortcuts above.
import { useAnnotationKeyboardControls } from '@waveform-playlist/browser';
const {
moveStartBoundary, // (delta: number) => void
moveEndBoundary, // (delta: number) => void
selectPrevious, // () => void
selectNext, // () => void
selectFirst, // () => void
selectLast, // () => void
clearSelection, // () => void
scrollToAnnotation, // (annotationId: string) => void
playActiveAnnotation, // () => void
shortcuts, // KeyboardShortcut[]: the annotation keys that apply now, for a list of your own (with `enabled: false`)
} = useAnnotationKeyboardControls({
store, // AnnotationStore | undefined (usePlaybackControls().annotationStore)
activeAnnotationId, // string | null
onActiveAnnotationChange, // (id: string | null) => void (optional; without it the selection keys are off)
duration, // number
linkEndpoints, // boolean
continuousPlay, // boolean (optional, default false)
enabled, // boolean (optional, default true)
reservedBindings, // readonly KeyBinding[] (optional): combinations of your own shortcuts; an annotation key leaves a matching key press alone
shortcuts, // AnnotationShortcutMap | null (optional): another key per action
scrollContainerRef, // RefObject<HTMLDivElement | null> (optional)
onPlay, // (startTime, duration?) => void (optional)
samplesPerPixel, // number (optional; default: the provider's)
sampleRate, // number (optional; default: the provider's)
});
The hook reads the annotations from store. Enter calls onPlay(start, duration) with the selected annotation's start, and its length when continuousPlay is off; <KeyboardShortcuts annotations /> passes an onPlay that calls playAnnotation for the selected annotation instead. A boundary key finds the selected annotation by its id in the store's list when the key is pressed and changes it there. Without a store there is nothing to select or move.
With scrollContainerRef, a navigation key (an arrow key, Home, End) centres the annotation it selects, as far as the scroll range allows, when that annotation is not fully in view. The returned selectPrevious, selectNext, selectFirst and selectLast do the same when your code calls them, also with enabled off. Nothing else scrolls: not playback moving on to the next annotation, not a click on a box or a row, not a boundary key, a change to the store or a zoom. scrollToAnnotation(id) scrolls the same way when you call it.
A Row of Boxes of Your Own
<WaveformAnnotationBoxes> needs none of this. To draw the boxes yourself and keep the edge drag, use the two hooks the part uses.
import { DragDropProvider } from '@dnd-kit/react';
import { RestrictToHorizontalAxis } from '@dnd-kit/abstract/modifiers';
import {
useAnnotations,
useAnnotationOptions,
usePlaybackControls,
useAudioSettings,
useZoom,
useAnnotationDragHandlers,
useAnnotationsWithPreview,
} from '@waveform-playlist/browser';
const HORIZONTAL_ONLY = [RestrictToHorizontalAxis];
function MyAnnotationBoxes({ duration }: { duration: number }) {
const { annotations } = useAnnotations();
const { linkEndpoints } = useAnnotationOptions();
const { annotationStore, annotationPreview } = usePlaybackControls();
const { sampleRate } = useAudioSettings();
const { samplesPerPixel } = useZoom();
const { onDragStart, onDragMove, onDragEnd } = useAnnotationDragHandlers({
store: annotationStore, // written once, on release, when `preview` is passed
preview: annotationPreview, // shows the drag without writing to the store per move
samplesPerPixel,
sampleRate, // default 48000; pass the provider's
duration, // seconds; an edge does not go past it
linkEndpoints,
});
// The annotations as the drag in progress would leave them.
const shown = useAnnotationsWithPreview(annotations, annotationPreview);
return (
<DragDropProvider
onDragStart={onDragStart}
onDragMove={onDragMove}
onDragEnd={onDragEnd}
modifiers={HORIZONTAL_ONLY}
>
{/* your boxes, drawn from `shown` */}
</DragDropProvider>
);
}
With preview, the release writes the bounds of every annotation the drag touched, by id (see Changes During an Edge Drag). Without preview, every pointer move writes all the touched bounds to the store. Escape cancels the drag and restores every annotation it touched: with preview nothing was written; without it each touched annotation's bounds from the start of the drag are written back. A drag that ends because its annotation was removed, the store changed or the component unmounted writes nothing more (without preview, the moves already written stay). Without a store the handlers do nothing.
The handlers act on a draggable whose data is { annotationId, annotationIndex, edge: 'start' | 'end' }; a drag with other data is ignored. The AnnotationBox of the annotations package registers its two edge handles that way.
For the click on one of your boxes, call playAnnotation(annotation) from usePlaybackControls(). It is what the built-in boxes and list rows call: the annotation becomes the selected one and plays from its start, and with continuous play off playback ends where the annotation ends (a play started with play() does not end there). The function never changes under WebAudioProvider; under MediaElementProvider it changes with the sample rate of the track's waveform data. So it can be a prop of memoized boxes.
Annotation Package Components
@waveform-playlist/annotations exports the components the two browser components are built from. Use them for an annotation UI that does not go through the provider. They take everything as props and read no playlist context (the checkboxes and the download button, below, are the exception).
AnnotationText
The scrollable list that <AnnotationList> renders.
import { useCreateAnnotationStore, useStoredAnnotations } from '@waveform-playlist/browser';
import { AnnotationText } from '@waveform-playlist/annotations';
import type { AnnotationData } from '@waveform-playlist/core';
function Transcript({
initialAnnotations,
activeId,
playingId,
seekTo,
}: {
initialAnnotations: AnnotationData[];
activeId?: string;
playingId?: string;
seekTo: (time: number) => void;
}) {
const store = useCreateAnnotationStore(() => initialAnnotations);
const annotations = useStoredAnnotations(store);
return (
<AnnotationText
annotations={annotations}
store={store}
activeAnnotationId={activeId}
playingAnnotationId={playingId}
shouldScrollToActive
editable
height={200}
onAnnotationClick={(annotation) => seekTo(annotation.start)}
/>
);
}
annotations is what the list draws; store is where its edits are written. A text edit, an id edit and an action button call store.update and find their annotation by id in the store's list as it is then, as under the provider. Without store the list is read-only: no field can be edited and no action button is drawn, whatever editable says. Without React state of your own, createAnnotationStore from @waveform-playlist/core makes the store.
activeAnnotationId is the selected annotation and playingAnnotationId the one the playhead is in while playing; the playing row has aria-current="true". With shouldScrollToActive, the list scrolls the selected row into view when activeAnnotationId changes and the playing row when playingAnnotationId changes. onAnnotationClick is called for a click on a row. Its other props are controls (the action buttons; drawn whenever given, with a store), annotationListConfig (the fourth argument of an action), scrollActivePosition, scrollActiveContainer and renderAnnotationItem (the function that draws a row).
AnnotationBox
One annotation box; with editable, a handle on each edge.
import { AnnotationBox } from '@waveform-playlist/annotations';
<AnnotationBox
annotationId={annotation.id}
annotationIndex={index}
startPosition={startPixels}
endPosition={endPixels}
label={annotation.id}
color="#ff9800"
isActive={annotation.id === activeId}
isPlaying={annotation.id === playingId}
editable
onClick={() => selectAnnotation(annotation)}
/>
color is the border of a box that is not active. isActive gives the box the selected look. isPlaying sets aria-current="true" on it and, when the box is not active, gives it the playing background. editable defaults to false and decides whether the two handles are drawn. The handles are dnd-kit draggables: to move an edge, render the boxes inside a DragDropProvider with the handlers of useAnnotationDragHandlers (above).
AnnotationBoxesWrapper
The positioned container for a row of boxes. Props: height (default 30), width, className.
import { AnnotationBoxesWrapper, AnnotationBox } from '@waveform-playlist/annotations';
<AnnotationBoxesWrapper height={30} width={timelineWidth}>
{annotations.map((annotation, index) => (
<AnnotationBox
key={annotation.id}
annotationId={annotation.id}
annotationIndex={index}
startPosition={annotation.start * pixelsPerSecond}
endPosition={annotation.end * pixelsPerSecond}
label={annotation.id}
/>
))}
</AnnotationBoxesWrapper>
Checkboxes and Download Button
ContinuousPlayCheckbox, LinkEndpointsCheckbox, EditableCheckbox and DownloadAnnotationsButton are described under Option Checkboxes. They read the playlist provider and have no controlled form (no checked, onChange or annotations props). For a checkbox with a state of your own, build one from BaseCheckboxWrapper, BaseCheckbox and BaseCheckboxLabel of @waveform-playlist/ui-components. To save annotations without a provider, serialize them yourself: annotations.map(serializeAeneas) (Aeneas Format).
Styling Annotations
The annotation colours are theme keys. Pass the ones you want to change in the provider's theme:
const theme = {
// Annotation boxes
annotationBoxBackground: 'rgba(255, 255, 255, 0.85)',
annotationBoxActiveBackground: 'rgba(255, 255, 255, 0.95)', // the selected box
annotationBoxHoverBackground: 'rgba(255, 255, 255, 0.98)',
annotationBoxBorder: '#ff9800', // border of a box that is not active, glow of the active one
annotationBoxActiveBorder: '#d67600', // border of the active box, and of a hovered one
annotationLabelColor: '#2a2a2a',
// Edge handles
annotationResizeHandleColor: 'rgba(0, 0, 0, 0.4)',
annotationResizeHandleActiveColor: 'rgba(0, 0, 0, 0.8)',
// Text list
annotationTextItemHoverBackground: 'rgba(0, 0, 0, 0.03)',
annotationTextItemActiveColor: '#ff9800', // the active row (edge, tint, glow) and the list's focus rings
};
<WebAudioProvider arrangement={arrangement} theme={theme}>
<AnnotationProvider>
<Waveform />
</AnnotationProvider>
</WebAudioProvider>
The values shown are the defaults of the light theme. See Theming.
"Active" in a key's name is the selected annotation. The box and the row the playhead is in while playing, when they are not the selected ones, have two optional keys of their own, which no theme sets:
const theme = {
// Without it: the box's border colour mixed 30% into annotationBoxBackground
annotationBoxPlayingBackground: 'rgba(255, 224, 178, 0.9)',
// Without it: annotationTextItemActiveColor at 8%
annotationTextItemPlayingBackground: 'rgba(255, 152, 0, 0.08)',
};
A playing box keeps its border; a playing row also gets a lighter left edge (annotationTextItemActiveColor at 45%). A box or a row that is both selected and playing shows the selected look.
Import/Export
Aeneas Format
parseAeneas converts one Aeneas fragment (begin and end are strings) to one annotation; serializeAeneas converts one annotation back. Map over an array:
import { parseAeneas, serializeAeneas } from '@waveform-playlist/annotations';
const fragments = [
{ id: 'f000001', begin: '0.000', end: '2.680', lines: ['First line'], language: 'en' },
{ id: 'f000002', begin: '2.680', end: '5.880', lines: ['Second line'], language: 'en' },
];
const annotations = fragments.map(parseAeneas);
// [{ id: 'f000001', start: 0, end: 2.68, lines: ['First line'], language: 'en' }, …]
const exported = annotations.map(serializeAeneas);
// begin and end as strings with three decimals; language 'en' when the annotation has none
Download Button
<DownloadAnnotationsButton filename="annotations.json" /> from @waveform-playlist/annotations downloads the provider's annotations as an array of Aeneas fragments.
Custom Export
function ExportAnnotations({ annotations }) {
const handleExport = () => {
const json = JSON.stringify(annotations, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'annotations.json';
a.click();
URL.revokeObjectURL(url);
};
return <button onClick={handleExport}>Export Annotations</button>;
}
Import from JSON
function ImportAnnotations({ onImport }) {
const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (e) => {
const json = e.target?.result as string;
const imported = JSON.parse(json);
onImport(imported);
};
reader.readAsText(file);
};
return <input type="file" accept=".json" onChange={handleImport} />;
}
A file written by the download button holds Aeneas fragments: pass imported.map(parseAeneas) to onImport, and store them with annotationStore.set(…). A list with an annotation whose start or end is not a number, or with two annotations of one id, makes set throw: catch it to tell the user the file was not loaded.
Complete Example
The options start from annotationList and are changed with the checkboxes. The annotations are the store's.
import {
WebAudioProvider,
WaveformRoot,
WaveformTimescale,
WaveformLoopRegion,
WaveformTrackControls,
WaveformTracks,
WaveformAnnotationBoxes,
WaveformSelection,
WaveformPlayhead,
WaveformViewOptions,
AnnotationList,
PlayButton,
PauseButton,
StopButton,
KeyboardShortcuts,
useCreateArrangement,
useCreateAnnotationStore,
} from '@waveform-playlist/browser';
import {
AnnotationProvider,
ContinuousPlayCheckbox,
LinkEndpointsCheckbox,
EditableCheckbox,
DownloadAnnotationsButton,
} from '@waveform-playlist/annotations';
import { audioTrack, type AnnotationData, type AnnotationAction } from '@waveform-playlist/core';
const annotationActions: AnnotationAction[] = [
{
text: '🗑',
title: 'Delete annotation',
action: (annotation, index, annotations) => {
annotations.splice(index, 1);
},
},
];
const boxLabel = (annotation: AnnotationData, index: number) => String(index + 1);
function AnnotationsExample() {
const arrangement = useCreateArrangement(() => [
audioTrack({ src: '/audio/podcast.mp3', name: 'Podcast Episode' }),
]);
const annotationStore = useCreateAnnotationStore(() => [
{ id: '1', start: 0, end: 10, lines: ['Introduction'] },
{ id: '2', start: 10, end: 30, lines: ['Main Topic'] },
{ id: '3', start: 30, end: 45, lines: ['Conclusion'] },
]);
return (
<WebAudioProvider
arrangement={arrangement}
samplesPerPixel={1024}
annotationStore={annotationStore}
annotationList={{ editable: true, linkEndpoints: true }}
>
<AnnotationProvider>
<KeyboardShortcuts playback annotations />
<div style={{ display: 'flex', gap: '0.5rem', marginBottom: '1rem' }}>
<PlayButton />
<PauseButton />
<StopButton />
</div>
<div style={{ display: 'flex', gap: '1rem', marginBottom: '1rem' }}>
<ContinuousPlayCheckbox />
<LinkEndpointsCheckbox />
<EditableCheckbox />
<DownloadAnnotationsButton />
</div>
<WaveformViewOptions waveHeight={100}>
<WaveformRoot>
<WaveformTimescale />
<WaveformLoopRegion />
<WaveformTrackControls />
<WaveformTracks />
<WaveformAnnotationBoxes getLabel={boxLabel} />
<WaveformSelection />
<WaveformPlayhead />
</WaveformRoot>
</WaveformViewOptions>
<AnnotationList height={200} actions={annotationActions} />
</AnnotationProvider>
</WebAudioProvider>
);
}
export default AnnotationsExample;
To drive an option from your own state instead, put it in the prop: annotationList={{ editable, linkEndpoints, isContinuousPlay }}. The provider's option takes each new value.
Use Cases
Podcast Chapters
Mark sections of a podcast for easy navigation:
const chapters = [
{ id: '1', start: 0, end: 120, lines: ['Intro & Sponsors'] },
{ id: '2', start: 120, end: 600, lines: ['Guest Interview'] },
{ id: '3', start: 600, end: 900, lines: ['Q&A Session'] },
{ id: '4', start: 900, end: 960, lines: ['Outro'] },
];
Transcription Segments
Break down audio into transcribed segments:
const transcription = [
{ id: '1', start: 0, end: 3.5, lines: ['Welcome to the show.'] },
{ id: '2', start: 3.5, end: 7, lines: ["Today we're discussing..."] },
// ...
];
Music Markers
Mark sections in music:
const musicSections = [
{ id: 'v1', start: 0, end: 16, lines: ['Verse 1'] },
{ id: 'c1', start: 16, end: 32, lines: ['Chorus'] },
{ id: 'v2', start: 32, end: 48, lines: ['Verse 2'] },
{ id: 'c2', start: 48, end: 64, lines: ['Chorus'] },
{ id: 'br', start: 64, end: 80, lines: ['Bridge'] },
{ id: 'c3', start: 80, end: 96, lines: ['Final Chorus'] },
];
Multi-line Annotations
Annotations support multiple lines of text:
const detailedAnnotations = [
{
id: '1',
start: 0,
end: 30,
lines: [
'Speaker: John Smith',
'Topic: Introduction to the project',
'Key points: overview, timeline, goals',
],
},
];
Live Example
See the Annotations Example for a full working demo.