npm package: @kaliber/use-react-player
Description: A React hook for controlling video playback and tracking user interactions with the HTMLVideoElement.
Latest version: 1.2.7

# `@kaliber/use-react-player`

A React hook that provides a comprehensive solution for controlling video playback and tracking user interactions with the `HTMLVideoElement`. This library is designed to work with any React-based video player that exposes the underlying `HTMLVideoElement`.

## Features

- **Playback Control**: Play, pause, and seek functionality.
- **Time and Progress**: Get the current time, duration, and progress of the video.
- **Subtitles**: Enable and list available text tracks.
- **Tracking**: Track user interactions such as play, pause, and progress, and send them to a data layer.
- **Autoplay and Autopause**: Automatically pause the video when it goes out of the viewport and resume when it comes back into view.

## Installation

```bash
yarn add @kaliber/use-react-player
```

## Usage

The `useReactPlayer` hook is the primary hook for most video playback control. The other hooks provide more advanced functionality for tracking and managing the video's play state.

```jsx
import { useReactPlayer } from '@kaliber/use-react-player'

function VideoPlayer({ src, subtitles }) {
  const { ref, play, pause, seekTo } = useReactPlayer()

  return (
    <div>
      <video ref={ref}>
        <source src={src} type="video/mp4" />
        {subtitles.map(({ lang, label, src }) => (
          <track key={lang} kind="subtitles" srcLang={lang} src={src} label={label} />
        ))}
      </video>
      <button onClick={play}>Play</button>
      <button onClick={pause}>Pause</button>
      <button onClick={() => seekTo(30, 'seconds')}>Seek to 30s</button>
    </div>
  )
}
```

## Hooks

### `useReactPlayer()`

This hook provides the primary interface for controlling the video player.

**Return Value**

An object with the following properties:

- `ref: React.RefObject<HTMLVideoElement>`: A ref to be attached to your `<video>` element.
- `setVideoRef: (ref: HTMLVideoElement) => void`: A function to set the video ref.
- `play(): Promise<void>`: Plays the video.
- `pause(): void`: Pauses the video.
- `seekTo(value: number, type: 'seconds' | 'fraction'): void`: Seeks the video to a specific time.
- `getDuration(): number`: Returns the total duration of the video in seconds.
- `getCurrentTime(): number`: Returns the current playback time in seconds.
- `getProgress(): number`: Returns the current playback progress as a percentage (0-100).
- `enableTextTrack(languageCode: string, kind?: TextTrackKind): boolean`: Enables a text track for a given language.
- `getAvailableTextTracks(kind?: TextTrackKind): TextTrackInfo[]`: Returns an array of available text tracks.

### `useVideoPlayState()`

This hook manages the play state of the video, especially in relation to its visibility in the viewport.

**Arguments**

- `videoRef: React.RefObject<HTMLVideoElement>`: A ref to the video element.
- `isInViewport: boolean`: A boolean indicating if the video is in the viewport.
- `onAutoPause?: () => void`: Callback for when the video is auto-paused.
- `onAutoResume?: () => void`: Callback for when the video is auto-resumed.
- `onUserPlay?: () => void`: Callback for when the user manually plays the video.
- `onUserPause?: () => void`: Callback for when the user manually pauses the video.

**Return Value**

An object with the following properties:

- `isPlaying: boolean`: Whether the video is currently playing.
- `wasAutoPaused: boolean`: Whether the video was last paused automatically.
- `handleUserPlay: () => void`: A function to be called when the user initiates playback.
- `handleUserPause: () => void`: A function to be called when the user initiates a pause.
- `setIsPlaying: (isPlaying: boolean) => void`: A function to manually set the playing state.

### `useVideoEventHandlers()`

This hook provides a set of event handlers for tracking video events.

**Arguments**

- `title: string`: The title of the video.
- `playerRef: React.RefObject<HTMLVideoElement>`: A ref to the video element.
- `isInViewport: boolean`: A boolean indicating if the video is in the viewport.
- `pushToDataLayer: (data: InteractionEventMetadata) => void`: A function to send tracking data to a data layer.

**Return Value**

A function that takes your own event handlers and returns a new set of event handlers that include tracking functionality.

### `useProgressTracker()`

This hook tracks the progress of the video and calls a callback at specific progress marks.

**Arguments**

- `onProgressMarkChange: (mark: ProgressMark) => void`: A callback function that is called when the video playback reaches a progress mark (25, 50, 75, 90, 100).

**Return Value**

A function that should be called with the current playback progress (a value between 0 and 1).

## Disclaimer

This library is intended for internal use, we provide **no** support, use at your own risk. It does not import React, but expects it to be provided, which [@kaliber/build](https://kaliberjs.github.io/build/) can handle for you.

This library is not transpiled.