@waveform-playlist/core 12.6.0 → 12.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -476,6 +476,10 @@ interface AnnotationData {
476
476
  end: number;
477
477
  lines: string[];
478
478
  language?: string;
479
+ /** Musical position (ticks). Authoritative when BOTH tick fields are set —
480
+ * start/end seconds are then a derived cache (clip startTick pattern). */
481
+ startTick?: number;
482
+ endTick?: number;
479
483
  }
480
484
  /**
481
485
  * Annotation format definition for parsing/serializing
@@ -723,7 +727,8 @@ type SnapTo = 'bar' | 'beat' | '1/2' | '1/4' | '1/8' | '1/16' | '1/32' | '1/2T'
723
727
  * Straight subdivisions (1/2, 1/4, 1/8, 1/16, 1/32) are always expressed as
724
728
  * fractions of a quarter note (ppqn), independent of the time signature
725
729
  * denominator. Triplet subdivisions use × 2/3 of the corresponding straight
726
- * value. 'bar' and 'beat' depend on the first meter entry's time signature.
730
+ * value. 'bar' and 'beat' depend on the `timeSignature` argument (the
731
+ * caller passes the meter entry active at the position).
727
732
  * 'off' returns 0.
728
733
  */
729
734
  declare function snapToTicks(snapTo: SnapTo, timeSignature: [number, number], ppqn?: number): number;
@@ -775,11 +780,36 @@ declare const MIN_PIXELS_PER_UNIT = 8;
775
780
  * correct across meter changes.
776
781
  */
777
782
  declare function computeMusicalTicks(params: MusicalTickParams): MusicalTickData;
783
+ /**
784
+ * Convert an absolute tick to a 1-based bar.beat position, honoring meter
785
+ * changes. Bars/beats are counted per meter segment (the same walk
786
+ * `computeMusicalTicks` uses to build its `barOffset` accumulator). Beat is
787
+ * the integer beat the tick falls WITHIN (floor, 1-based) — a tick exactly on
788
+ * a bar line is beat 1.
789
+ *
790
+ * Guards: empty `meterEntries` → treat as 4/4 from tick 0. `ppqn <= 0` →
791
+ * returns `{ bar: 1, beat: 1 }` (division-by-zero guard, matches
792
+ * `computeMusicalTicks`'s ppqn guard).
793
+ */
794
+ declare function ticksToBarBeat(tick: number, meterEntries: MeterEntry[], ppqn: number): {
795
+ bar: number;
796
+ beat: number;
797
+ };
778
798
  /**
779
799
  * Snaps a tick position to the nearest grid boundary defined by `snapTo`.
780
800
  *
781
- * Finds the meter entry active at the tick position and snaps relative to
782
- * that meter's segment start.
801
+ * Finds the meter entry active at the tick position, then the BAR containing
802
+ * the tick, and snaps relative to that bar's start: grid lines restart at
803
+ * each bar line (the same rule as `@dawcore/transport`'s `quantizeTick` and
804
+ * the drawn ruler grid), so odd meters stay aligned — in 7/8 at 960 PPQN a
805
+ * quarter-note grid is 0, 960, 1920, 2880 and then the bar line at 3360,
806
+ * never 3840. A subdivision longer than the bar leaves only the bar lines.
807
+ * An exact tie snaps up; a tick already on a line stays put. Unlike
808
+ * `quantizeTick`, the result is not rounded (a fractional grid size at an
809
+ * unusual PPQN gives a fractional tick), triplet steps use the rounded
810
+ * `snapToTicks` value, negative ticks are accepted (the lattice extends
811
+ * backwards) and meter entries need not sit on bar boundaries of the
812
+ * preceding meter (the next line is capped at the following entry).
783
813
  *
784
814
  * Returns the original tick unchanged when `snapTo` is 'off'.
785
815
  */
@@ -1025,6 +1055,13 @@ interface KeyboardShortcut {
1025
1055
  description?: string;
1026
1056
  preventDefault?: boolean;
1027
1057
  }
1058
+ /** A key + modifier combination, without an action. Used for remapping maps. */
1059
+ type KeyBinding = Pick<KeyboardShortcut, 'key' | 'ctrlKey' | 'shiftKey' | 'metaKey' | 'altKey'>;
1060
+ /**
1061
+ * Does a keyboard event match a key binding?
1062
+ * `undefined` modifier = match any state; `false` = must NOT be pressed.
1063
+ */
1064
+ declare function matchesKeyBinding(event: KeyboardEvent, binding: KeyBinding): boolean;
1028
1065
  /**
1029
1066
  * Handle a keyboard event against a list of shortcuts.
1030
1067
  * Pure function, no framework dependency.
@@ -1114,4 +1151,57 @@ declare function enumerateMicrophones(mediaDevices?: MediaDevices): Promise<Micr
1114
1151
  */
1115
1152
  declare function watchMicrophoneDevices(listener: (enumeration: MicrophoneEnumeration) => void, mediaDevices?: MediaDevices): () => void;
1116
1153
 
1117
- export { type AnnotationAction, type AnnotationActionOptions, type AnnotationData, type AnnotationEventMap, type AnnotationFormat, type AnnotationListOptions, type AudioBuffer$1 as AudioBuffer, type AudioClip, type Bits, type ClipTrack, type ColorMapEntry, type ColorMapName, type ColorMapValue, type CreateClipOptions, type CreateClipOptionsSeconds, type CreateClipOptionsTicks, type CreateTrackOptions, DEFAULT_SPECTROGRAM_COLOR_MAP, type FFTSize, type Fade, type FadeConfig, type FadeType, type Gap, InteractionState, type KeyboardShortcut, MAX_CANVAS_WIDTH, MIN_PIXELS_PER_UNIT, type MeterEntry, type MicrophoneDeviceInfo, type MicrophoneEnumeration, type MidiNoteData, type MusicalTick, type MusicalTickData, type MusicalTickParams, PPQN, type PeakData, type Peaks, type PlaylistConfig, type PlayoutState, type RangeSupport, type RenderAnnotationItemProps, type RenderMode, SPECTROGRAM_DEFAULTS, type SnapTo, type SpectrogramCanvasIdParts, type SpectrogramComputeConfig, type SpectrogramConfig, type SpectrogramData, type SpectrogramDisplayConfig, type TickType, type TimeSelection, type Timeline, type Track, type TrackEffectsFunction, type TrackSpectrogramOverrides, type WaveformConfig, type WaveformDataObject, type ZoomLevel, appendPeaks, appendToAudioBuffer, applyFadeIn, applyFadeOut, audibleLatencySamples, buildSpectrogramCanvasId, calculateDuration, carveClipRange, clipDurationTime, clipEndTime, clipOffsetTime, clipPixelWidth, clipStartTime, clipsOverlap, computeMusicalTicks, concatenateAudioData, createAudioBuffer, createClip, createClipFromSeconds, createClipFromTicks, createTimeline, createTrack, dBToNormalized, detectMeterChanges, enumerateMicrophones, exponentialCurve, findGaps, gainToDb, gainToNormalized, generateCurve, generatePeaks, getClipsAtSample, getClipsInRange, getShortcutLabel, handleKeyboardEvent, linearCurve, logarithmicCurve, normalizedToDb, parseSpectrogramCanvasId, pixelsToSamples, pixelsToSeconds, probeRangeSupport, resolveRecordingOffsetSamples, sCurveCurve, samplesToPixels, samplesToSeconds, samplesToTicks, secondsToPixels, secondsToSamples, snapTickToGrid, snapToGrid, snapToTicks, sortClipsByTime, ticksPerBar, ticksPerBeat, ticksToSamples, trackChannelCount, watchMicrophoneDevices };
1154
+ /** Edges within this distance (seconds) are considered "linked". */
1155
+ declare const LINK_THRESHOLD = 0.01;
1156
+ /** Minimum annotation duration (seconds) enforced by boundary edits. */
1157
+ declare const MIN_ANNOTATION_DURATION = 0.1;
1158
+ /** Link threshold for INTEGER TICK positions — closer than half a tick means equal. */
1159
+ declare const ANNOTATION_LINK_THRESHOLD_TICKS = 0.5;
1160
+ /** Minimum tick-annotation duration: a 128th note, floored at 1 tick. */
1161
+ declare function annotationMinDurationTicks(ppqn: number): number;
1162
+ /** Unit constants for a boundary-math run. Defaults are the seconds-domain values. */
1163
+ interface AnnotationBoundaryOptions {
1164
+ linkThreshold?: number;
1165
+ minDuration?: number;
1166
+ }
1167
+ interface AnnotationBoundaryUpdate {
1168
+ annotationIndex: number;
1169
+ newTime: number;
1170
+ isDraggingStart: boolean;
1171
+ annotations: AnnotationData[];
1172
+ duration: number;
1173
+ linkEndpoints: boolean;
1174
+ }
1175
+ /**
1176
+ * Pure boundary-update logic shared by the React annotations package and the
1177
+ * dawcore annotation web components. Handles linked endpoints (moving one edge
1178
+ * drags the linked neighbor edge, with cascade) and collision push-back.
1179
+ * Returns a NEW array; never mutates inputs.
1180
+ */
1181
+ declare function updateAnnotationBoundaries(params: AnnotationBoundaryUpdate, options?: AnnotationBoundaryOptions): AnnotationData[];
1182
+
1183
+ type AnnotationShortcutAction = 'selectPrevious' | 'selectNext' | 'selectFirst' | 'selectLast' | 'clearSelection' | 'moveStartEarlier' | 'moveStartLater' | 'moveEndEarlier' | 'moveEndLater' | 'playActive';
1184
+ /** Key remapping map — null on the consumer means "use defaults". */
1185
+ interface AnnotationShortcutMap {
1186
+ selectPrevious?: KeyBinding;
1187
+ selectNext?: KeyBinding;
1188
+ selectFirst?: KeyBinding;
1189
+ selectLast?: KeyBinding;
1190
+ clearSelection?: KeyBinding;
1191
+ moveStartEarlier?: KeyBinding;
1192
+ moveStartLater?: KeyBinding;
1193
+ moveEndEarlier?: KeyBinding;
1194
+ moveEndLater?: KeyBinding;
1195
+ playActive?: KeyBinding;
1196
+ }
1197
+ declare const DEFAULT_ANNOTATION_SHORTCUTS: Record<AnnotationShortcutAction, KeyBinding[]>;
1198
+ /**
1199
+ * Flatten defaults + remap into a matchable list. A remapped action replaces
1200
+ * ALL of its default bindings with the single provided binding.
1201
+ */
1202
+ declare function resolveAnnotationShortcuts(remap: AnnotationShortcutMap | null): Array<{
1203
+ action: AnnotationShortcutAction;
1204
+ binding: KeyBinding;
1205
+ }>;
1206
+
1207
+ export { ANNOTATION_LINK_THRESHOLD_TICKS, type AnnotationAction, type AnnotationActionOptions, type AnnotationBoundaryOptions, type AnnotationBoundaryUpdate, type AnnotationData, type AnnotationEventMap, type AnnotationFormat, type AnnotationListOptions, type AnnotationShortcutAction, type AnnotationShortcutMap, type AudioBuffer$1 as AudioBuffer, type AudioClip, type Bits, type ClipTrack, type ColorMapEntry, type ColorMapName, type ColorMapValue, type CreateClipOptions, type CreateClipOptionsSeconds, type CreateClipOptionsTicks, type CreateTrackOptions, DEFAULT_ANNOTATION_SHORTCUTS, DEFAULT_SPECTROGRAM_COLOR_MAP, type FFTSize, type Fade, type FadeConfig, type FadeType, type Gap, InteractionState, type KeyBinding, type KeyboardShortcut, LINK_THRESHOLD, MAX_CANVAS_WIDTH, MIN_ANNOTATION_DURATION, MIN_PIXELS_PER_UNIT, type MeterEntry, type MicrophoneDeviceInfo, type MicrophoneEnumeration, type MidiNoteData, type MusicalTick, type MusicalTickData, type MusicalTickParams, PPQN, type PeakData, type Peaks, type PlaylistConfig, type PlayoutState, type RangeSupport, type RenderAnnotationItemProps, type RenderMode, SPECTROGRAM_DEFAULTS, type SnapTo, type SpectrogramCanvasIdParts, type SpectrogramComputeConfig, type SpectrogramConfig, type SpectrogramData, type SpectrogramDisplayConfig, type TickType, type TimeSelection, type Timeline, type Track, type TrackEffectsFunction, type TrackSpectrogramOverrides, type WaveformConfig, type WaveformDataObject, type ZoomLevel, annotationMinDurationTicks, appendPeaks, appendToAudioBuffer, applyFadeIn, applyFadeOut, audibleLatencySamples, buildSpectrogramCanvasId, calculateDuration, carveClipRange, clipDurationTime, clipEndTime, clipOffsetTime, clipPixelWidth, clipStartTime, clipsOverlap, computeMusicalTicks, concatenateAudioData, createAudioBuffer, createClip, createClipFromSeconds, createClipFromTicks, createTimeline, createTrack, dBToNormalized, detectMeterChanges, enumerateMicrophones, exponentialCurve, findGaps, gainToDb, gainToNormalized, generateCurve, generatePeaks, getClipsAtSample, getClipsInRange, getShortcutLabel, handleKeyboardEvent, linearCurve, logarithmicCurve, matchesKeyBinding, normalizedToDb, parseSpectrogramCanvasId, pixelsToSamples, pixelsToSeconds, probeRangeSupport, resolveAnnotationShortcuts, resolveRecordingOffsetSamples, sCurveCurve, samplesToPixels, samplesToSeconds, samplesToTicks, secondsToPixels, secondsToSamples, snapTickToGrid, snapToGrid, snapToTicks, sortClipsByTime, ticksPerBar, ticksPerBeat, ticksToBarBeat, ticksToSamples, trackChannelCount, updateAnnotationBoundaries, watchMicrophoneDevices };
package/dist/index.d.ts CHANGED
@@ -476,6 +476,10 @@ interface AnnotationData {
476
476
  end: number;
477
477
  lines: string[];
478
478
  language?: string;
479
+ /** Musical position (ticks). Authoritative when BOTH tick fields are set —
480
+ * start/end seconds are then a derived cache (clip startTick pattern). */
481
+ startTick?: number;
482
+ endTick?: number;
479
483
  }
480
484
  /**
481
485
  * Annotation format definition for parsing/serializing
@@ -723,7 +727,8 @@ type SnapTo = 'bar' | 'beat' | '1/2' | '1/4' | '1/8' | '1/16' | '1/32' | '1/2T'
723
727
  * Straight subdivisions (1/2, 1/4, 1/8, 1/16, 1/32) are always expressed as
724
728
  * fractions of a quarter note (ppqn), independent of the time signature
725
729
  * denominator. Triplet subdivisions use × 2/3 of the corresponding straight
726
- * value. 'bar' and 'beat' depend on the first meter entry's time signature.
730
+ * value. 'bar' and 'beat' depend on the `timeSignature` argument (the
731
+ * caller passes the meter entry active at the position).
727
732
  * 'off' returns 0.
728
733
  */
729
734
  declare function snapToTicks(snapTo: SnapTo, timeSignature: [number, number], ppqn?: number): number;
@@ -775,11 +780,36 @@ declare const MIN_PIXELS_PER_UNIT = 8;
775
780
  * correct across meter changes.
776
781
  */
777
782
  declare function computeMusicalTicks(params: MusicalTickParams): MusicalTickData;
783
+ /**
784
+ * Convert an absolute tick to a 1-based bar.beat position, honoring meter
785
+ * changes. Bars/beats are counted per meter segment (the same walk
786
+ * `computeMusicalTicks` uses to build its `barOffset` accumulator). Beat is
787
+ * the integer beat the tick falls WITHIN (floor, 1-based) — a tick exactly on
788
+ * a bar line is beat 1.
789
+ *
790
+ * Guards: empty `meterEntries` → treat as 4/4 from tick 0. `ppqn <= 0` →
791
+ * returns `{ bar: 1, beat: 1 }` (division-by-zero guard, matches
792
+ * `computeMusicalTicks`'s ppqn guard).
793
+ */
794
+ declare function ticksToBarBeat(tick: number, meterEntries: MeterEntry[], ppqn: number): {
795
+ bar: number;
796
+ beat: number;
797
+ };
778
798
  /**
779
799
  * Snaps a tick position to the nearest grid boundary defined by `snapTo`.
780
800
  *
781
- * Finds the meter entry active at the tick position and snaps relative to
782
- * that meter's segment start.
801
+ * Finds the meter entry active at the tick position, then the BAR containing
802
+ * the tick, and snaps relative to that bar's start: grid lines restart at
803
+ * each bar line (the same rule as `@dawcore/transport`'s `quantizeTick` and
804
+ * the drawn ruler grid), so odd meters stay aligned — in 7/8 at 960 PPQN a
805
+ * quarter-note grid is 0, 960, 1920, 2880 and then the bar line at 3360,
806
+ * never 3840. A subdivision longer than the bar leaves only the bar lines.
807
+ * An exact tie snaps up; a tick already on a line stays put. Unlike
808
+ * `quantizeTick`, the result is not rounded (a fractional grid size at an
809
+ * unusual PPQN gives a fractional tick), triplet steps use the rounded
810
+ * `snapToTicks` value, negative ticks are accepted (the lattice extends
811
+ * backwards) and meter entries need not sit on bar boundaries of the
812
+ * preceding meter (the next line is capped at the following entry).
783
813
  *
784
814
  * Returns the original tick unchanged when `snapTo` is 'off'.
785
815
  */
@@ -1025,6 +1055,13 @@ interface KeyboardShortcut {
1025
1055
  description?: string;
1026
1056
  preventDefault?: boolean;
1027
1057
  }
1058
+ /** A key + modifier combination, without an action. Used for remapping maps. */
1059
+ type KeyBinding = Pick<KeyboardShortcut, 'key' | 'ctrlKey' | 'shiftKey' | 'metaKey' | 'altKey'>;
1060
+ /**
1061
+ * Does a keyboard event match a key binding?
1062
+ * `undefined` modifier = match any state; `false` = must NOT be pressed.
1063
+ */
1064
+ declare function matchesKeyBinding(event: KeyboardEvent, binding: KeyBinding): boolean;
1028
1065
  /**
1029
1066
  * Handle a keyboard event against a list of shortcuts.
1030
1067
  * Pure function, no framework dependency.
@@ -1114,4 +1151,57 @@ declare function enumerateMicrophones(mediaDevices?: MediaDevices): Promise<Micr
1114
1151
  */
1115
1152
  declare function watchMicrophoneDevices(listener: (enumeration: MicrophoneEnumeration) => void, mediaDevices?: MediaDevices): () => void;
1116
1153
 
1117
- export { type AnnotationAction, type AnnotationActionOptions, type AnnotationData, type AnnotationEventMap, type AnnotationFormat, type AnnotationListOptions, type AudioBuffer$1 as AudioBuffer, type AudioClip, type Bits, type ClipTrack, type ColorMapEntry, type ColorMapName, type ColorMapValue, type CreateClipOptions, type CreateClipOptionsSeconds, type CreateClipOptionsTicks, type CreateTrackOptions, DEFAULT_SPECTROGRAM_COLOR_MAP, type FFTSize, type Fade, type FadeConfig, type FadeType, type Gap, InteractionState, type KeyboardShortcut, MAX_CANVAS_WIDTH, MIN_PIXELS_PER_UNIT, type MeterEntry, type MicrophoneDeviceInfo, type MicrophoneEnumeration, type MidiNoteData, type MusicalTick, type MusicalTickData, type MusicalTickParams, PPQN, type PeakData, type Peaks, type PlaylistConfig, type PlayoutState, type RangeSupport, type RenderAnnotationItemProps, type RenderMode, SPECTROGRAM_DEFAULTS, type SnapTo, type SpectrogramCanvasIdParts, type SpectrogramComputeConfig, type SpectrogramConfig, type SpectrogramData, type SpectrogramDisplayConfig, type TickType, type TimeSelection, type Timeline, type Track, type TrackEffectsFunction, type TrackSpectrogramOverrides, type WaveformConfig, type WaveformDataObject, type ZoomLevel, appendPeaks, appendToAudioBuffer, applyFadeIn, applyFadeOut, audibleLatencySamples, buildSpectrogramCanvasId, calculateDuration, carveClipRange, clipDurationTime, clipEndTime, clipOffsetTime, clipPixelWidth, clipStartTime, clipsOverlap, computeMusicalTicks, concatenateAudioData, createAudioBuffer, createClip, createClipFromSeconds, createClipFromTicks, createTimeline, createTrack, dBToNormalized, detectMeterChanges, enumerateMicrophones, exponentialCurve, findGaps, gainToDb, gainToNormalized, generateCurve, generatePeaks, getClipsAtSample, getClipsInRange, getShortcutLabel, handleKeyboardEvent, linearCurve, logarithmicCurve, normalizedToDb, parseSpectrogramCanvasId, pixelsToSamples, pixelsToSeconds, probeRangeSupport, resolveRecordingOffsetSamples, sCurveCurve, samplesToPixels, samplesToSeconds, samplesToTicks, secondsToPixels, secondsToSamples, snapTickToGrid, snapToGrid, snapToTicks, sortClipsByTime, ticksPerBar, ticksPerBeat, ticksToSamples, trackChannelCount, watchMicrophoneDevices };
1154
+ /** Edges within this distance (seconds) are considered "linked". */
1155
+ declare const LINK_THRESHOLD = 0.01;
1156
+ /** Minimum annotation duration (seconds) enforced by boundary edits. */
1157
+ declare const MIN_ANNOTATION_DURATION = 0.1;
1158
+ /** Link threshold for INTEGER TICK positions — closer than half a tick means equal. */
1159
+ declare const ANNOTATION_LINK_THRESHOLD_TICKS = 0.5;
1160
+ /** Minimum tick-annotation duration: a 128th note, floored at 1 tick. */
1161
+ declare function annotationMinDurationTicks(ppqn: number): number;
1162
+ /** Unit constants for a boundary-math run. Defaults are the seconds-domain values. */
1163
+ interface AnnotationBoundaryOptions {
1164
+ linkThreshold?: number;
1165
+ minDuration?: number;
1166
+ }
1167
+ interface AnnotationBoundaryUpdate {
1168
+ annotationIndex: number;
1169
+ newTime: number;
1170
+ isDraggingStart: boolean;
1171
+ annotations: AnnotationData[];
1172
+ duration: number;
1173
+ linkEndpoints: boolean;
1174
+ }
1175
+ /**
1176
+ * Pure boundary-update logic shared by the React annotations package and the
1177
+ * dawcore annotation web components. Handles linked endpoints (moving one edge
1178
+ * drags the linked neighbor edge, with cascade) and collision push-back.
1179
+ * Returns a NEW array; never mutates inputs.
1180
+ */
1181
+ declare function updateAnnotationBoundaries(params: AnnotationBoundaryUpdate, options?: AnnotationBoundaryOptions): AnnotationData[];
1182
+
1183
+ type AnnotationShortcutAction = 'selectPrevious' | 'selectNext' | 'selectFirst' | 'selectLast' | 'clearSelection' | 'moveStartEarlier' | 'moveStartLater' | 'moveEndEarlier' | 'moveEndLater' | 'playActive';
1184
+ /** Key remapping map — null on the consumer means "use defaults". */
1185
+ interface AnnotationShortcutMap {
1186
+ selectPrevious?: KeyBinding;
1187
+ selectNext?: KeyBinding;
1188
+ selectFirst?: KeyBinding;
1189
+ selectLast?: KeyBinding;
1190
+ clearSelection?: KeyBinding;
1191
+ moveStartEarlier?: KeyBinding;
1192
+ moveStartLater?: KeyBinding;
1193
+ moveEndEarlier?: KeyBinding;
1194
+ moveEndLater?: KeyBinding;
1195
+ playActive?: KeyBinding;
1196
+ }
1197
+ declare const DEFAULT_ANNOTATION_SHORTCUTS: Record<AnnotationShortcutAction, KeyBinding[]>;
1198
+ /**
1199
+ * Flatten defaults + remap into a matchable list. A remapped action replaces
1200
+ * ALL of its default bindings with the single provided binding.
1201
+ */
1202
+ declare function resolveAnnotationShortcuts(remap: AnnotationShortcutMap | null): Array<{
1203
+ action: AnnotationShortcutAction;
1204
+ binding: KeyBinding;
1205
+ }>;
1206
+
1207
+ export { ANNOTATION_LINK_THRESHOLD_TICKS, type AnnotationAction, type AnnotationActionOptions, type AnnotationBoundaryOptions, type AnnotationBoundaryUpdate, type AnnotationData, type AnnotationEventMap, type AnnotationFormat, type AnnotationListOptions, type AnnotationShortcutAction, type AnnotationShortcutMap, type AudioBuffer$1 as AudioBuffer, type AudioClip, type Bits, type ClipTrack, type ColorMapEntry, type ColorMapName, type ColorMapValue, type CreateClipOptions, type CreateClipOptionsSeconds, type CreateClipOptionsTicks, type CreateTrackOptions, DEFAULT_ANNOTATION_SHORTCUTS, DEFAULT_SPECTROGRAM_COLOR_MAP, type FFTSize, type Fade, type FadeConfig, type FadeType, type Gap, InteractionState, type KeyBinding, type KeyboardShortcut, LINK_THRESHOLD, MAX_CANVAS_WIDTH, MIN_ANNOTATION_DURATION, MIN_PIXELS_PER_UNIT, type MeterEntry, type MicrophoneDeviceInfo, type MicrophoneEnumeration, type MidiNoteData, type MusicalTick, type MusicalTickData, type MusicalTickParams, PPQN, type PeakData, type Peaks, type PlaylistConfig, type PlayoutState, type RangeSupport, type RenderAnnotationItemProps, type RenderMode, SPECTROGRAM_DEFAULTS, type SnapTo, type SpectrogramCanvasIdParts, type SpectrogramComputeConfig, type SpectrogramConfig, type SpectrogramData, type SpectrogramDisplayConfig, type TickType, type TimeSelection, type Timeline, type Track, type TrackEffectsFunction, type TrackSpectrogramOverrides, type WaveformConfig, type WaveformDataObject, type ZoomLevel, annotationMinDurationTicks, appendPeaks, appendToAudioBuffer, applyFadeIn, applyFadeOut, audibleLatencySamples, buildSpectrogramCanvasId, calculateDuration, carveClipRange, clipDurationTime, clipEndTime, clipOffsetTime, clipPixelWidth, clipStartTime, clipsOverlap, computeMusicalTicks, concatenateAudioData, createAudioBuffer, createClip, createClipFromSeconds, createClipFromTicks, createTimeline, createTrack, dBToNormalized, detectMeterChanges, enumerateMicrophones, exponentialCurve, findGaps, gainToDb, gainToNormalized, generateCurve, generatePeaks, getClipsAtSample, getClipsInRange, getShortcutLabel, handleKeyboardEvent, linearCurve, logarithmicCurve, matchesKeyBinding, normalizedToDb, parseSpectrogramCanvasId, pixelsToSamples, pixelsToSeconds, probeRangeSupport, resolveAnnotationShortcuts, resolveRecordingOffsetSamples, sCurveCurve, samplesToPixels, samplesToSeconds, samplesToTicks, secondsToPixels, secondsToSamples, snapTickToGrid, snapToGrid, snapToTicks, sortClipsByTime, ticksPerBar, ticksPerBeat, ticksToBarBeat, ticksToSamples, trackChannelCount, updateAnnotationBoundaries, watchMicrophoneDevices };
package/dist/index.js CHANGED
@@ -20,12 +20,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ ANNOTATION_LINK_THRESHOLD_TICKS: () => ANNOTATION_LINK_THRESHOLD_TICKS,
24
+ DEFAULT_ANNOTATION_SHORTCUTS: () => DEFAULT_ANNOTATION_SHORTCUTS,
23
25
  DEFAULT_SPECTROGRAM_COLOR_MAP: () => DEFAULT_SPECTROGRAM_COLOR_MAP,
24
26
  InteractionState: () => InteractionState,
27
+ LINK_THRESHOLD: () => LINK_THRESHOLD,
25
28
  MAX_CANVAS_WIDTH: () => MAX_CANVAS_WIDTH,
29
+ MIN_ANNOTATION_DURATION: () => MIN_ANNOTATION_DURATION,
26
30
  MIN_PIXELS_PER_UNIT: () => MIN_PIXELS_PER_UNIT,
27
31
  PPQN: () => PPQN,
28
32
  SPECTROGRAM_DEFAULTS: () => SPECTROGRAM_DEFAULTS,
33
+ annotationMinDurationTicks: () => annotationMinDurationTicks,
29
34
  appendPeaks: () => appendPeaks,
30
35
  appendToAudioBuffer: () => appendToAudioBuffer,
31
36
  applyFadeIn: () => applyFadeIn,
@@ -63,11 +68,13 @@ __export(index_exports, {
63
68
  handleKeyboardEvent: () => handleKeyboardEvent,
64
69
  linearCurve: () => linearCurve,
65
70
  logarithmicCurve: () => logarithmicCurve,
71
+ matchesKeyBinding: () => matchesKeyBinding,
66
72
  normalizedToDb: () => normalizedToDb,
67
73
  parseSpectrogramCanvasId: () => parseSpectrogramCanvasId,
68
74
  pixelsToSamples: () => pixelsToSamples,
69
75
  pixelsToSeconds: () => pixelsToSeconds,
70
76
  probeRangeSupport: () => probeRangeSupport,
77
+ resolveAnnotationShortcuts: () => resolveAnnotationShortcuts,
71
78
  resolveRecordingOffsetSamples: () => resolveRecordingOffsetSamples,
72
79
  sCurveCurve: () => sCurveCurve,
73
80
  samplesToPixels: () => samplesToPixels,
@@ -81,8 +88,10 @@ __export(index_exports, {
81
88
  sortClipsByTime: () => sortClipsByTime,
82
89
  ticksPerBar: () => ticksPerBar,
83
90
  ticksPerBeat: () => ticksPerBeat,
91
+ ticksToBarBeat: () => ticksToBarBeat,
84
92
  ticksToSamples: () => ticksToSamples,
85
93
  trackChannelCount: () => trackChannelCount,
94
+ updateAnnotationBoundaries: () => updateAnnotationBoundaries,
86
95
  watchMicrophoneDevices: () => watchMicrophoneDevices
87
96
  });
88
97
  module.exports = __toCommonJS(index_exports);
@@ -507,10 +516,17 @@ function computeMusicalTicks(params) {
507
516
  if (segmentTickStart > segmentTickEnd) {
508
517
  continue;
509
518
  }
519
+ const restartAtBar = zoomLevel !== "coarse";
510
520
  const offsetIntoSegment = segmentTickStart - segmentStartTick;
511
- const firstStepOffset = Math.floor(offsetIntoSegment / stepTicks) * stepTicks;
512
- const firstStepTick = segmentStartTick + firstStepOffset;
513
- for (let tick = firstStepTick; tick <= segmentTickEnd && tick < segmentEndTick; tick += stepTicks) {
521
+ const anchorTick = restartAtBar ? segmentStartTick + Math.floor(offsetIntoSegment / tpBar) * tpBar : segmentStartTick;
522
+ const firstStepTick = anchorTick + Math.floor((segmentTickStart - anchorTick) / stepTicks) * stepTicks;
523
+ const nextGridTick = (tick) => {
524
+ const next = tick + stepTicks;
525
+ if (!restartAtBar) return next;
526
+ const nextBarTick = segmentStartTick + (Math.floor((tick - segmentStartTick) / tpBar) + 1) * tpBar;
527
+ return Math.min(next, nextBarTick);
528
+ };
529
+ for (let tick = firstStepTick; tick <= segmentTickEnd && tick < segmentEndTick; tick = nextGridTick(tick)) {
514
530
  const pixel = tick / ticksPerPixel;
515
531
  if (pixel < startPixel || pixel > endPixel) {
516
532
  continue;
@@ -545,21 +561,60 @@ function computeMusicalTicks(params) {
545
561
  };
546
562
  return result;
547
563
  }
564
+ function ticksToBarBeat(tick, meterEntries, ppqn) {
565
+ if (ppqn <= 0) return { bar: 1, beat: 1 };
566
+ const entries = meterEntries.length > 0 ? meterEntries : [{ tick: 0, numerator: 4, denominator: 4 }];
567
+ let barOffset = 0;
568
+ for (let i = 0; i < entries.length; i++) {
569
+ const meter = entries[i];
570
+ const segmentStart = meter.tick;
571
+ const segmentEnd = i + 1 < entries.length ? entries[i + 1].tick : Number.MAX_SAFE_INTEGER;
572
+ const ts2 = [meter.numerator, meter.denominator];
573
+ const tpBar2 = ticksPerBar(ts2, ppqn);
574
+ const tpBeat2 = ticksPerBeat(ts2, ppqn);
575
+ if (tick >= segmentStart && tick < segmentEnd) {
576
+ const offset2 = tick - segmentStart;
577
+ const barIndexInSegment2 = Math.floor(offset2 / tpBar2);
578
+ const beatInBar2 = Math.floor(offset2 % tpBar2 / tpBeat2);
579
+ return { bar: barOffset + barIndexInSegment2 + 1, beat: beatInBar2 + 1 };
580
+ }
581
+ if (segmentEnd !== Number.MAX_SAFE_INTEGER) {
582
+ const segmentLen = segmentEnd - segmentStart;
583
+ barOffset += Math.floor(segmentLen / tpBar2);
584
+ }
585
+ }
586
+ const first = entries[0];
587
+ const ts = [first.numerator, first.denominator];
588
+ const tpBar = ticksPerBar(ts, ppqn);
589
+ const tpBeat = ticksPerBeat(ts, ppqn);
590
+ const offset = tick - first.tick;
591
+ const barIndexInSegment = Math.floor(offset / tpBar);
592
+ const beatInBar = Math.floor(offset % tpBar / tpBeat);
593
+ return { bar: barIndexInSegment + 1, beat: beatInBar + 1 };
594
+ }
548
595
  function snapTickToGrid(tick, snapTo, meterEntries, ppqn = 960) {
549
596
  if (snapTo === "off") return tick;
550
597
  let meter = meterEntries[0] ?? { tick: 0, numerator: 4, denominator: 4 };
598
+ let nextEntryTick = Infinity;
551
599
  for (const entry of meterEntries) {
552
600
  if (entry.tick <= tick) {
553
601
  meter = entry;
554
602
  } else {
603
+ nextEntryTick = entry.tick;
555
604
  break;
556
605
  }
557
606
  }
558
607
  const ts = [meter.numerator, meter.denominator];
559
608
  const gridSize = snapToTicks(snapTo, ts, ppqn);
560
609
  if (gridSize <= 0) return tick;
561
- const offset = tick - meter.tick;
562
- return meter.tick + Math.round(offset / gridSize) * gridSize;
610
+ const barLength = ticksPerBar(ts, ppqn);
611
+ if (!(barLength > 0)) {
612
+ return meter.tick + Math.round((tick - meter.tick) / gridSize) * gridSize;
613
+ }
614
+ const barStart = meter.tick + Math.floor((tick - meter.tick) / barLength) * barLength;
615
+ const previous = barStart + Math.floor((tick - barStart) / gridSize) * gridSize;
616
+ const next = Math.min(previous + gridSize, barStart + barLength, nextEntryTick);
617
+ return tick - previous < next - tick ? previous : next;
563
618
  }
564
619
 
565
620
  // src/utils/meterDetection.ts
@@ -889,6 +944,14 @@ function applyFadeOut(param, startTime, duration, type = "linear", startValue =
889
944
  }
890
945
 
891
946
  // src/keyboard.ts
947
+ function matchesKeyBinding(event, binding) {
948
+ const keyMatch = event.key.toLowerCase() === binding.key.toLowerCase() || event.key === binding.key;
949
+ const ctrlMatch = binding.ctrlKey === void 0 || event.ctrlKey === binding.ctrlKey;
950
+ const shiftMatch = binding.shiftKey === void 0 || event.shiftKey === binding.shiftKey;
951
+ const metaMatch = binding.metaKey === void 0 || event.metaKey === binding.metaKey;
952
+ const altMatch = binding.altKey === void 0 || event.altKey === binding.altKey;
953
+ return keyMatch && ctrlMatch && shiftMatch && metaMatch && altMatch;
954
+ }
892
955
  function handleKeyboardEvent(event, shortcuts, enabled) {
893
956
  if (!enabled) return;
894
957
  if (event.repeat) return;
@@ -896,14 +959,7 @@ function handleKeyboardEvent(event, shortcuts, enabled) {
896
959
  if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) {
897
960
  return;
898
961
  }
899
- const matchingShortcut = shortcuts.find((shortcut) => {
900
- const keyMatch = event.key.toLowerCase() === shortcut.key.toLowerCase() || event.key === shortcut.key;
901
- const ctrlMatch = shortcut.ctrlKey === void 0 || event.ctrlKey === shortcut.ctrlKey;
902
- const shiftMatch = shortcut.shiftKey === void 0 || event.shiftKey === shortcut.shiftKey;
903
- const metaMatch = shortcut.metaKey === void 0 || event.metaKey === shortcut.metaKey;
904
- const altMatch = shortcut.altKey === void 0 || event.altKey === shortcut.altKey;
905
- return keyMatch && ctrlMatch && shiftMatch && metaMatch && altMatch;
906
- });
962
+ const matchingShortcut = shortcuts.find((shortcut) => matchesKeyBinding(event, shortcut));
907
963
  if (matchingShortcut) {
908
964
  if (matchingShortcut.preventDefault !== false) {
909
965
  event.preventDefault();
@@ -1004,14 +1060,138 @@ function watchMicrophoneDevices(listener, mediaDevices) {
1004
1060
  md.removeEventListener("devicechange", deliver);
1005
1061
  };
1006
1062
  }
1063
+
1064
+ // src/annotations/boundaries.ts
1065
+ var LINK_THRESHOLD = 0.01;
1066
+ var MIN_ANNOTATION_DURATION = 0.1;
1067
+ var ANNOTATION_LINK_THRESHOLD_TICKS = 0.5;
1068
+ function annotationMinDurationTicks(ppqn) {
1069
+ return Math.max(1, Math.round(ppqn / 32));
1070
+ }
1071
+ function updateAnnotationBoundaries(params, options = {}) {
1072
+ const { annotationIndex, newTime, isDraggingStart, annotations, duration, linkEndpoints } = params;
1073
+ const linkThreshold = options.linkThreshold ?? LINK_THRESHOLD;
1074
+ const minDuration = options.minDuration ?? MIN_ANNOTATION_DURATION;
1075
+ const updatedAnnotations = [...annotations];
1076
+ const annotation = annotations[annotationIndex];
1077
+ if (isDraggingStart) {
1078
+ const constrainedStart = Math.min(annotation.end - minDuration, Math.max(0, newTime));
1079
+ const delta = constrainedStart - annotation.start;
1080
+ updatedAnnotations[annotationIndex] = { ...annotation, start: constrainedStart };
1081
+ if (linkEndpoints && annotationIndex > 0) {
1082
+ const prevAnnotation = updatedAnnotations[annotationIndex - 1];
1083
+ if (Math.abs(prevAnnotation.end - annotation.start) < linkThreshold) {
1084
+ updatedAnnotations[annotationIndex - 1] = {
1085
+ ...prevAnnotation,
1086
+ end: Math.max(prevAnnotation.start + minDuration, prevAnnotation.end + delta)
1087
+ };
1088
+ } else if (constrainedStart <= prevAnnotation.end) {
1089
+ updatedAnnotations[annotationIndex] = {
1090
+ ...updatedAnnotations[annotationIndex],
1091
+ start: prevAnnotation.end
1092
+ };
1093
+ }
1094
+ } else if (!linkEndpoints && annotationIndex > 0 && constrainedStart < updatedAnnotations[annotationIndex - 1].end) {
1095
+ updatedAnnotations[annotationIndex - 1] = {
1096
+ ...updatedAnnotations[annotationIndex - 1],
1097
+ end: constrainedStart
1098
+ };
1099
+ }
1100
+ } else {
1101
+ const constrainedEnd = Math.max(annotation.start + minDuration, Math.min(newTime, duration));
1102
+ const delta = constrainedEnd - annotation.end;
1103
+ updatedAnnotations[annotationIndex] = { ...annotation, end: constrainedEnd };
1104
+ if (linkEndpoints && annotationIndex < updatedAnnotations.length - 1) {
1105
+ const nextAnnotation = updatedAnnotations[annotationIndex + 1];
1106
+ if (Math.abs(nextAnnotation.start - annotation.end) < linkThreshold) {
1107
+ const newStart = nextAnnotation.start + delta;
1108
+ updatedAnnotations[annotationIndex + 1] = {
1109
+ ...nextAnnotation,
1110
+ start: Math.min(nextAnnotation.end - minDuration, newStart)
1111
+ };
1112
+ let currentIndex = annotationIndex + 1;
1113
+ while (currentIndex < updatedAnnotations.length - 1) {
1114
+ const current = updatedAnnotations[currentIndex];
1115
+ const next = updatedAnnotations[currentIndex + 1];
1116
+ if (Math.abs(next.start - current.end) < linkThreshold) {
1117
+ const nextDelta = current.end - annotations[currentIndex].end;
1118
+ updatedAnnotations[currentIndex + 1] = {
1119
+ ...next,
1120
+ start: Math.min(next.end - minDuration, next.start + nextDelta)
1121
+ };
1122
+ currentIndex++;
1123
+ } else {
1124
+ break;
1125
+ }
1126
+ }
1127
+ } else if (constrainedEnd >= nextAnnotation.start) {
1128
+ updatedAnnotations[annotationIndex] = {
1129
+ ...updatedAnnotations[annotationIndex],
1130
+ end: nextAnnotation.start
1131
+ };
1132
+ }
1133
+ } else if (!linkEndpoints && annotationIndex < updatedAnnotations.length - 1 && constrainedEnd > updatedAnnotations[annotationIndex + 1].start) {
1134
+ const nextAnnotation = updatedAnnotations[annotationIndex + 1];
1135
+ updatedAnnotations[annotationIndex + 1] = { ...nextAnnotation, start: constrainedEnd };
1136
+ let currentIndex = annotationIndex + 1;
1137
+ while (currentIndex < updatedAnnotations.length - 1) {
1138
+ const current = updatedAnnotations[currentIndex];
1139
+ const next = updatedAnnotations[currentIndex + 1];
1140
+ if (current.end > next.start) {
1141
+ updatedAnnotations[currentIndex + 1] = { ...next, start: current.end };
1142
+ currentIndex++;
1143
+ } else {
1144
+ break;
1145
+ }
1146
+ }
1147
+ }
1148
+ }
1149
+ return updatedAnnotations;
1150
+ }
1151
+
1152
+ // src/annotations/shortcuts.ts
1153
+ var noMods = { ctrlKey: false, metaKey: false };
1154
+ var DEFAULT_ANNOTATION_SHORTCUTS = {
1155
+ selectPrevious: [
1156
+ { key: "ArrowUp", ...noMods },
1157
+ { key: "ArrowLeft", ...noMods }
1158
+ ],
1159
+ selectNext: [
1160
+ { key: "ArrowDown", ...noMods },
1161
+ { key: "ArrowRight", ...noMods }
1162
+ ],
1163
+ selectFirst: [{ key: "Home", ...noMods }],
1164
+ selectLast: [{ key: "End", ...noMods }],
1165
+ clearSelection: [{ key: "Escape", ...noMods }],
1166
+ moveStartEarlier: [{ key: "[", ...noMods }],
1167
+ moveStartLater: [{ key: "]", ...noMods }],
1168
+ // '{' / '}' are what event.key reports for Shift+[ / Shift+] — no explicit
1169
+ // shiftKey needed; the key value itself encodes it.
1170
+ moveEndEarlier: [{ key: "{", ...noMods }],
1171
+ moveEndLater: [{ key: "}", ...noMods }],
1172
+ playActive: [{ key: "Enter", ...noMods }]
1173
+ };
1174
+ var ALL_ACTIONS = Object.keys(DEFAULT_ANNOTATION_SHORTCUTS);
1175
+ function resolveAnnotationShortcuts(remap) {
1176
+ return ALL_ACTIONS.flatMap((action) => {
1177
+ const override = remap?.[action];
1178
+ const bindings = override ? [override] : DEFAULT_ANNOTATION_SHORTCUTS[action];
1179
+ return bindings.map((binding) => ({ action, binding }));
1180
+ });
1181
+ }
1007
1182
  // Annotate the CommonJS export names for ESM import in node:
1008
1183
  0 && (module.exports = {
1184
+ ANNOTATION_LINK_THRESHOLD_TICKS,
1185
+ DEFAULT_ANNOTATION_SHORTCUTS,
1009
1186
  DEFAULT_SPECTROGRAM_COLOR_MAP,
1010
1187
  InteractionState,
1188
+ LINK_THRESHOLD,
1011
1189
  MAX_CANVAS_WIDTH,
1190
+ MIN_ANNOTATION_DURATION,
1012
1191
  MIN_PIXELS_PER_UNIT,
1013
1192
  PPQN,
1014
1193
  SPECTROGRAM_DEFAULTS,
1194
+ annotationMinDurationTicks,
1015
1195
  appendPeaks,
1016
1196
  appendToAudioBuffer,
1017
1197
  applyFadeIn,
@@ -1049,11 +1229,13 @@ function watchMicrophoneDevices(listener, mediaDevices) {
1049
1229
  handleKeyboardEvent,
1050
1230
  linearCurve,
1051
1231
  logarithmicCurve,
1232
+ matchesKeyBinding,
1052
1233
  normalizedToDb,
1053
1234
  parseSpectrogramCanvasId,
1054
1235
  pixelsToSamples,
1055
1236
  pixelsToSeconds,
1056
1237
  probeRangeSupport,
1238
+ resolveAnnotationShortcuts,
1057
1239
  resolveRecordingOffsetSamples,
1058
1240
  sCurveCurve,
1059
1241
  samplesToPixels,
@@ -1067,8 +1249,10 @@ function watchMicrophoneDevices(listener, mediaDevices) {
1067
1249
  sortClipsByTime,
1068
1250
  ticksPerBar,
1069
1251
  ticksPerBeat,
1252
+ ticksToBarBeat,
1070
1253
  ticksToSamples,
1071
1254
  trackChannelCount,
1255
+ updateAnnotationBoundaries,
1072
1256
  watchMicrophoneDevices
1073
1257
  });
1074
1258
  //# sourceMappingURL=index.js.map