27 lines
588 B
TypeScript
27 lines
588 B
TypeScript
export interface SnapOptions {
|
|
enabled: boolean
|
|
pxPerSec: number
|
|
pixelThreshold: number
|
|
duration: number
|
|
}
|
|
|
|
export function snapToCandidates(
|
|
t: number,
|
|
candidates: readonly number[],
|
|
opts: SnapOptions,
|
|
): number {
|
|
if (!opts.enabled) return t
|
|
if (opts.pxPerSec <= 0) return t
|
|
const thresholdTime = opts.pixelThreshold / opts.pxPerSec
|
|
let best = t
|
|
let bestDist = thresholdTime
|
|
for (const kt of candidates) {
|
|
const d = Math.abs(kt - t)
|
|
if (d <= bestDist) {
|
|
bestDist = d
|
|
best = kt
|
|
}
|
|
}
|
|
return Math.max(0, Math.min(opts.duration, best))
|
|
}
|