Media time

Format a position, clamp a seek target and read the buffered end of a media element.

Reach for it for the time labels and seek bar of a player; MediaController uses the same arithmetic. The helpers are pure: no DOM at import time or in the call path, so they run on the server and in tests. Each result below is computed when the page is built, by running the call shown.

Import

import { formatMediaTime, clampSeek, bufferedEnd } from '@ecopages/radiant-ui/helpers';

Format

formatMediaTime(seconds, { hours }) returns m:ss, or h:mm:ss when hours are shown. hours is 'auto' (default, from one hour on), true or false. NaN, Infinity and negative values, which a media element reports before metadata and for a live stream, format as zero. Pass hours: duration >= 3600 to a position and its duration so they keep the same width.

CallResult
formatMediaTime(75)"1:15"
formatMediaTime(3725)"1:02:05"
formatMediaTime(75, { hours: true })"0:01:15"
formatMediaTime(3725, { hours: false })"62:05"
formatMediaTime(NaN)"0:00"
formatMediaTime(Infinity)"0:00"
formatMediaTime(-5)"0:00"

Clamp a seek

clampSeek(position, duration) clamps to [0, duration]. A duration that is not finite clamps at 0 only. The result is always finite, because currentTime throws for a non-finite value.

CallResult
clampSeek(-3, 60)0
clampSeek(90, 60)60
clampSeek(90, NaN)90
clampSeek(90, Infinity)90
clampSeek(NaN, 60)0

Buffered end

bufferedEnd(ranges, position) takes anything shaped like TimeRanges, such as media.buffered, and returns the end of the range that contains the position, or 0. With ranges at 0 to 10 and 30 to 50:

CallResult
bufferedEnd(ranges, 5)10
bufferedEnd(ranges, 10)10
bufferedEnd(ranges, 20)0
bufferedEnd(ranges, 35)50