From 5030afefbcda1bbec4975cc2b10ed55cb775ac1b Mon Sep 17 00:00:00 2001 From: amtins Date: Tue, 26 Mar 2024 11:52:38 +0100 Subject: [PATCH] feat(player): add seekableRanges helper function Adds a `seekableRanges` function which is particularly useful to get an array of ranges representing the portions of media that the user agent is able to seek to. `seekableRanges` uses the `seekable` function native to `HTMLMediaElement`. - add seekableRanges function to the player - add test coverage --- src/components/player.js | 20 ++++++++++++++++++++ test/components/player.spec.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/src/components/player.js b/src/components/player.js index 545814e..ac6199a 100644 --- a/src/components/player.js +++ b/src/components/player.js @@ -92,6 +92,26 @@ class Player extends vjsPlayer { return ranges; } + /** + * Calculates an array of ranges based on the `seekable()` data. + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/seekable + * + * @returns {Array<{start: number, end: number}>} An array of objects representing start and end points of seekable ranges. + */ + seekableRanges() { + const ranges = []; + + for (let i = 0; i < this.seekable().length; i++) { + const start = this.seekable().start(i); + const end = this.seekable().end(i); + + ranges.push({ start, end }); + } + + return ranges; + } + /** * A getter/setter for the media's text track. * Activates the text track according to the language and kind properties. diff --git a/test/components/player.spec.js b/test/components/player.spec.js index a727af4..52ad091 100644 --- a/test/components/player.spec.js +++ b/test/components/player.spec.js @@ -95,6 +95,37 @@ describe('Player', () => { }); }); + describe('seekableRanges', () => { + it('should return an empty array if there are no seekable ranges', () => { + const player = new Player(videoEl); + + player.seekable = jest.fn().mockImplementation(() => { + return pillarbox.time.createTimeRanges(); + }); + + expect(player.seekableRanges()).toHaveLength(0); + }); + + it('should return an array containing two entries', () => { + const player = new Player(videoEl); + + player.seekable = jest.fn().mockImplementation(() => { + return pillarbox.time.createTimeRanges([ + [0, 10], + [11, 69] + ]); + }); + + expect(player.seekableRanges()).toHaveLength(2); + expect(player.seekableRanges()).toEqual( + expect.arrayContaining([ + { 'end': 10, 'start': 0 }, + { 'end': 69, 'start': 11 } + ]) + ); + }); + }); + describe('textTrack', () => { const player = new Player(videoEl);