1.1.0 • Published 1 year ago

@nishansanjuka/react-yt-framer v1.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

React YouTube Player with Seekbar

npm version License: MIT

A fully-typed React component for embedding YouTube videos in Next.js applications with advanced playback controls and a customizable seekbar.

šŸ“‹ Table of Contents

✨ Features

  • šŸŽÆ Full TypeScript Support: Built with TypeScript for excellent type safety and IntelliSense
  • šŸŽ® Advanced Controls: Play, pause, seek, and reset functionality
  • ⚔ Performance Optimized: Minimal re-renders and efficient state management
  • šŸŽØ Customizable: Easily style and extend components
  • šŸ“± Responsive: Works across all device sizes
  • šŸ”„ State Management: Built-in context for managing player state
  • šŸŽ¬ YouTube API Integration: Seamless integration with YouTube's IFrame API

šŸš€ Installation

# Using npm
npm install @nishansanjuka/react-yt-framer

# Using yarn
yarn add @nishansanjuka/react-yt-framer

# Using pnpm
pnpm add @nishansanjuka/react-yt-framer

šŸŽÆ Quick Start

import {
  YoutubePlayerProvider,
  YoutubePlayerWithSeekbar,
} from "@nishansanjuka/react-yt-framer";

function App() {
  return (
    <YoutubePlayerProvider>
      <YoutubePlayerWithSeekbar
        videoId="dQw4w9WgXcQ"
        className="aspect-video w-full"
      />
    </YoutubePlayerProvider>
  );
}

šŸ“– API Reference

YoutubePlayer Provider

The provider component that manages the YouTube player state and context.

import { YoutubePlayerProvider } from "@nishansanjuka/react-yt-framer";

function App() {
  return <YoutubePlayerProvider>{/* Your components */}</YoutubePlayerProvider>;
}

YoutubePlayer With Seekbar

The main component that renders the YouTube player.

interface YoutubePlayerWithSeekbarProps {
  videoId: string;
  className?: string;
}

Props

PropTypeDescription
videoIdstringYouTube video ID
classNamestring?Optional CSS classes

useYoutubePlayer Hook

A custom hook for accessing player controls and state.

const {
  duration,
  currentTime,
  isPlaying,
  isAPIReady,
  play,
  pause,
  seek,
  reset,
  setIsPlaying,
} = useYoutubePlayer();

Return Values

ValueTypeDescription
durationnumberTotal video duration in seconds
currentTimenumberCurrent playback position in seconds
isPlayingbooleanWhether video is currently playing
isAPIReadybooleanWhether YouTube API is loaded
play() => voidFunction to play video
pause() => voidFunction to pause video
seek(time: number) => voidFunction to seek to specific time
reset() => voidFunction to reset video to start
setIsPlaying(playing: boolean) => voidFunction to set playing state

šŸŽØ Advanced Usage

Custom Controls Example

import { useYoutubePlayer } from "@nishansanjuka/react-yt-framer";

function CustomControls() {
  const { play, pause, isPlaying, currentTime, duration, seek } =
    useYoutubePlayer();

  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    seek(Number(e.target.value));
  };

  return (
    <div className="flex gap-2 items-center">
      <button onClick={isPlaying ? pause : play}>
        {isPlaying ? "Pause" : "Play"}
      </button>
      <input
        type="range"
        min={0}
        max={duration}
        value={currentTime}
        onChange={handleSeek}
      />
      <span>
        {Math.floor(currentTime)} / {Math.floor(duration)}s
      </span>
    </div>
  );
}

Multiple Players

function VideoGallery() {
  return (
    <div className="grid grid-cols-2 gap-4">
      <YoutubePlayerProvider>
        <YoutubePlayerWithSeekbar videoId="video1" />
      </YoutubePlayerProvider>
      <YoutubePlayerProvider>
        <YoutubePlayerWithSeekbar videoId="video2" />
      </YoutubePlayerProvider>
    </div>
  );
}

šŸ” TypeScript Support

The package includes comprehensive TypeScript definitions. Here are some key types:

interface YouTubePlayer {
  playVideo(): void;
  pauseVideo(): void;
  seekTo(seconds: number, allowSeekAhead?: boolean): void;
  stopVideo(): void;
  getCurrentTime(): number;
  getDuration(): number;
  getPlayerState(): number;
}

interface YoutubePlayerContextType {
  duration: number;
  currentTime: number;
  isPlaying: boolean;
  isAPIReady: boolean;
  registerPlayer: (player: YouTubePlayer) => void;
  seek: (time: number) => void;
  play: () => void;
  pause: () => void;
  reset: () => void;
  setIsPlaying: (playing: boolean) => void;
}

šŸ’” Examples

Basic Player

function BasicPlayer() {
  return (
    <YoutubePlayerProvider>
      <YoutubePlayerWithSeekbar
        videoId="dQw4w9WgXcQ"
        className="w-full aspect-video rounded-lg shadow-lg"
      />
    </YoutubePlayerProvider>
  );
}

Player with Custom Controls and Progress Bar

function CustomPlayer() {
  const { currentTime, duration, seek, isPlaying, play, pause } =
    useYoutubePlayer();

  const progress = (currentTime / duration) * 100;

  return (
    <div className="space-y-4">
      <YoutubePlayerWithSeekbar videoId="dQw4w9WgXcQ" />

      <div className="flex items-center gap-4">
        <button
          onClick={isPlaying ? pause : play}
          className="px-4 py-2 bg-blue-500 text-white rounded"
        >
          {isPlaying ? "Pause" : "Play"}
        </button>

        <div className="flex-1 bg-gray-200 h-2 rounded">
          <div
            className="bg-blue-500 h-full rounded"
            style={{ width: `${progress}%` }}
          />
        </div>

        <span className="text-sm">
          {Math.floor(currentTime)}s / {Math.floor(duration)}s
        </span>
      </div>
    </div>
  );
}

šŸ¤ Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

šŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


šŸŽÆ Troubleshooting

Common Issues

  1. YouTube API Not Loading
// Make sure you're using the Provider
<YoutubePlayerProvider>
  <YourComponent />
</YoutubePlayerProvider>
  1. Type Errors
// Import types directly
import type { YoutubePlayerContextType } from "@nishansanjuka/react-yt-framer";
  1. Player Not Mounting
// Ensure videoId is valid
<YoutubePlayerWithSeekbar videoId="valid-youtube-id" />

šŸ“¦ Package Structure

@nishansanjuka/react-yt-framer/
ā”œā”€ā”€ dist/
│   ā”œā”€ā”€ cjs/           # CommonJS bundle
│   ā”œā”€ā”€ esm/           # ES Modules bundle
│   └── index.d.ts     # TypeScript declarations
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ components/    # React components
│   └── types/        # TypeScript types
└── package.json

šŸ”„ Updates and Versioning

We follow Semantic Versioning. Here's a summary of what each number means:

  • Major version when making incompatible API changes
  • Minor version when adding functionality in a backwards compatible manner
  • Patch version when making backwards compatible bug fixes

Check the CHANGELOG.md for detailed release notes.


Made with ā¤ļø by Nipuna Nishan

1.1.0

1 year ago

1.0.0

1 year ago