npm package: @interactify-live/khanoumi-player
Description: A React component library for creating interactive video players with product integration, social features, and Persian/Farsi language support. Built specifically for e-commerce and social commerce applications.
Latest version: 1.0.7

# @interactify-live/khanoumi-player

A React component library for creating interactive video players with product integration, social features, and Persian/Farsi language support. Built specifically for e-commerce and social commerce applications.

## 🚀 Features

- 🎥 **Interactive Video Player** - Built on top of @interactify-live/player-react
- 🛍️ **Product Integration** - Display products with pricing, discounts, and add-to-cart functionality
- 🎨 **Customizable Product Cards** - Use your own product card component or the default one
- 💬 **Social Features** - Like, comment, and share functionality with real-time messaging
- 🇮🇷 **Persian/Farsi Support** - RTL layout and Persian number conversion
- 📱 **Mobile-First Design** - Optimized for mobile and touch interactions
- 🎨 **Customizable UI** - Modular components with customizable styling
- 🔧 **TypeScript Support** - Full TypeScript definitions included
- 🔗 **Real-time Communication** - MQTT-based chat and interaction system
- 🎯 **Interaction Tracking** - Built-in analytics and event tracking
- 📝 **Caption Support** - Expandable captions with Persian text support
- ⏱️ **Persian Time Formatting** - Relative time display in Persian

## 📦 Installation

```bash
npm install @interactify-live/khanoumi-player
```

### Peer Dependencies

This library requires the following peer dependencies:

```json
{
  "react": "^18.2.0",
  "react-dom": "^18.2.0"
}
```

## 🚀 Quick Start

```tsx
import { InteractifyKhanoumiPlayer } from "@interactify-live/khanoumi-player";

function App() {
  const mediaItem = {
    id: "video-1",
    type: "video" as const,
    url: "https://example.com/video.mp4",
    thumbnail: "https://example.com/thumbnail.jpg",
  };

  const products = [
    {
      productDescription: "رژ لب مات نارس",
      brandName: "NARS",
      originalPrice: "450000",
      discountedPrice: "350000",
      discountPercentage: "22%",
      productImages: ["https://example.com/product1.jpg"],
    },
  ];

  const connectionOptions = {
    user_id: "user123",
    token: "your-token",
    scope: "short" as const,
    space_slug: "my-space",
    slug: "my-content",
    session: "session123",
    display_name: "User Display Name",
  };

  const handleInteraction = (elementId: string) => {
    // handle interaction here
  };

  return (
    <InteractifyKhanoumiPlayer
      title="محصولات آرایشی"
      caption="این یک ویدیوی نمایشی از محصولات آرایشی است"
      mediaItem={mediaItem}
      products={products}
      slug="my-content-slug"
      onInteractionClick={handleInteraction}
      connectionOptions={connectionOptions}
      isLiked={false}
      likeCount={157}
    />
  );
}
```

## 📚 API Reference

### InteractifyKhanoumiPlayer

The main component that renders the interactive video player with all features.

#### Props

| Prop                 | Type                          | Required | Description                          |
| -------------------- | ----------------------------- | -------- | ------------------------------------ |
| `title`              | `string`                      | ✅       | Title displayed in the header        |
| `caption`            | `string`                      | ❌       | Optional caption text below video    |
| `mediaItem`          | `MediaItem`                   | ✅       | Video or image to display            |
| `products`           | `Product[]`                   | ✅       | Array of products to display         |
| `slug`               | `string`                      | ✅       | Content slug for comments API        |
| `ProductCard`        | `React.FC<Product>`           | ❌       | Custom product card component        |
| `onInteractionClick` | `(elementId: string) => void` | ❌       | Callback for interaction events      |
| `isLiked`            | `boolean`                     | ❌       | Whether the content is liked         |
| `likeCount`          | `number`                      | ❌       | Number of likes                      |
| `onNewMessage`       | `(message: Comment) => void`  | ❌       | Callback for new messages            |
| `connectionOptions`  | `ConnectionOptions`           | ❌       | Interactify connection configuration |
| `shareUrl`           | `string`                      | ❌       | URL for share functionality          |
| `shareTitle`         | `string`                      | ❌       | Title for share functionality        |
| `shareText`          | `string`                      | ❌       | Text for share functionality         |

#### Types

```typescript
interface MediaItem {
  id: string;
  type: "image" | "video";
  url: string;
  thumbnail?: string;
}

interface Product {
  productDescription: string;
  brandName: string;
  originalPrice: string;
  discountedPrice: string;
  discountPercentage: string;
  productImages: string[];
}

interface Comment {
  avatar: string;
  created_at: string;
  display_name: string;
  reply_to?: {
    avatar: string;
    created_at: string;
    display_name: string;
    short_slug: string;
    slug: string;
    space_slug: string;
    text: string;
    user_id: string;
    visible: boolean;
  } | null;
  short_slug: string;
  slug: string;
  space_slug: string;
  text: string;
  user_id: string;
  visible: boolean;
  like_count?: number;
  replies?: Comment[];
}

interface ConnectionOptions {
  user_id: string;
  token: string;
  scope: "short" | "live";
  space_slug: string;
  slug: string;
  session: string;
  display_name: string;
  brokerUrl?: string;
}
```

## 🧩 Components

### Core Components

- **InteractifyKhanoumiPlayer** - Main player component
- **MediaPlayer** - Video/image player with mute controls
- **ActionButtons** - Like, share, and comment buttons
- **ProductCardDetailed** - Default product display card
- **CommentsModal** - Comments and chat interface

### UI Components

- **ActionButton** - Reusable action button
- **Modal** - Modal dialog component
- **ChatInput** - Chat input component
- **PaginationDots** - Pagination indicator
- **VideoProgress** - Video progress bar
- **VideoProgressBar** - Progress bar component
- **CartBadge** - Shopping cart badge
- **ProductCard** - Basic product card

### Icons

- **HeartIcon** / **HeartIconFilled** - Like buttons
- **ShareIcon** - Share functionality
- **ChatIcon** - Comments/chat
- **BackIcon** - Navigation
- **MuteIcon** / **UnmuteIcon** - Audio controls
- **CurrencyIcon** / **CurrencyIconDetailed** - Price display
- **CloseIcon** - Modal close
- **ArrowLeftIcon** - Navigation
- **StarIcon** - Rating
- **TickIcon** - Success indicator
- **SendIcon** - Message send
- **BasketIcon** / **BasketIconWithBadge** - Shopping cart
- **NotificationIcon** - Notifications
- **CommentsIcon** - Comments indicator

## 🎣 Hooks

### useInteractifyKhanoumiPlayer

Custom hook for managing player state and interactions.

```typescript
import { useInteractifyKhanoumiPlayer } from "@interactify-live/khanoumi-player";

const {
  product,
  cartCount,
  isLiked,
  currentMediaIndex,
  handleMediaIndexChange,
} = useInteractifyKhanoumiPlayer(initialProduct);
```

## 🛠️ Utilities

### toFa

Convert English numbers to Persian/Farsi numbers with proper formatting.

```typescript
import { toFa } from "@interactify-live/khanoumi-player";

toFa(123); // Returns "۱۲۳"
toFa("456"); // Returns "۴۵۶"
toFa(1234567); // Returns "۱،۲۳۴،۵۶۷"
```

### formatPersianTime

Format timestamps to Persian relative time.

```typescript
import { formatPersianTime } from "@interactify-live/khanoumi-player";

formatPersianTime("2024-01-01T10:00:00Z"); // Returns "۲ ساعت پیش"
formatPersianTime(new Date()); // Returns "الان"
```

## 💬 Chat Messaging

The khanoumi-player supports sending chat messages through the MQTT connection using the `sendMessage` method.

### Using sendMessage Programmatically

```tsx
import { useRef } from "react";
import { InteractifyKhanoumiPlayer } from "@interactify-live/khanoumi-player";

const MyComponent = () => {
  const playerRef = useRef(null);

  const sendMessage = () => {
    if (playerRef.current?.sendMessage) {
      playerRef.current.sendMessage({
        text: "Hello, this is a test message!",
        displayName: "User123",
        avatar: "https://example.com/avatar.jpg",
        visible: true,
      });
    }
  };

  return (
    <InteractifyKhanoumiPlayer
      ref={playerRef}
      title="Demo Video"
      mediaItem={mediaItem}
      products={products}
      slug="demo-slug"
      connectionOptions={connectionOptions}
    />
  );
};
```

### Message Object Type

```typescript
interface MessageObject {
  text: string; // Required: The message text
  avatar?: string; // Optional: User avatar URL
  displayName?: string; // Optional: User display name
  visible?: boolean; // Optional: Whether message is visible (default: true)
  replyTo?: {
    // Optional: Reply to another message
    text: string;
    userID: string;
    displayName: string;
  };
}
```

## 📝 Examples

### Basic Usage

```tsx
import { InteractifyKhanoumiPlayer } from "@interactify-live/khanoumi-player";

const MyVideoPlayer = () => {
  const mediaItem = {
    id: "my-video",
    type: "video" as const,
    url: "https://example.com/video.mp4",
  };

  const products = [
    {
      productDescription: "رژ لب مات",
      brandName: "MAC",
      originalPrice: "500000",
      discountedPrice: "400000",
      discountPercentage: "20%",
      productImages: ["https://example.com/lipstick.jpg"],
    },
  ];

  return (
    <div style={{ width: "100vw", height: "100vh" }}>
      <InteractifyKhanoumiPlayer
        title="محصولات آرایشی"
        caption="ویدیوی معرفی محصولات جدید"
        mediaItem={mediaItem}
        products={products}
        slug="my-content"
        onInteractionClick={(elementId) => {
          // handle click here
        }}
      />
    </div>
  );
};
```

### With Connection Options and Real-time Chat

```tsx
const connectionOptions = {
  user_id: "user123",
  token: "your-token",
  scope: "short",
  space_slug: "my-space",
  slug: "my-content",
  session: "session123",
  display_name: "User Display Name",
};

<InteractifyKhanoumiPlayer
  title="Live Stream"
  mediaItem={mediaItem}
  products={products}
  slug="live-content"
  connectionOptions={connectionOptions}
  onNewMessage={(message) => {
    // handle new message here
  }}
/>;
```

### Custom Product Card

```tsx
import { InteractifyKhanoumiPlayer } from "@interactify-live/khanoumi-player";

// Define your custom product card component
const CustomProductCard = ({
  productDescription,
  brandName,
  originalPrice,
  discountedPrice,
  productImages,
}) => {
  return (
    <div
      style={{
        backgroundColor: "#1a1a1a",
        borderRadius: "12px",
        padding: "16px",
        color: "white",
        minWidth: "280px",
      }}
    >
      <img
        src={productImages[0]}
        alt={productDescription}
        style={{
          width: "100%",
          height: "120px",
          objectFit: "cover",
          borderRadius: "8px",
        }}
      />
      <h3 style={{ margin: "8px 0 4px", fontSize: "14px" }}>{brandName}</h3>
      <p style={{ margin: "0 0 8px", fontSize: "12px", opacity: 0.8 }}>
        {productDescription}
      </p>
      <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
        <span style={{ color: "#ff4444", fontWeight: "bold" }}>
          {discountedPrice} تومان
        </span>
        <span
          style={{
            textDecoration: "line-through",
            opacity: 0.6,
            fontSize: "12px",
          }}
        >
          {originalPrice}
        </span>
      </div>
    </div>
  );
};

const App = () => {
  return (
    <InteractifyKhanoumiPlayer
      title="محصولات آرایشی"
      mediaItem={mediaItem}
      products={products}
      slug="custom-products"
      ProductCard={CustomProductCard} // Use your custom component
      onInteractionClick={handleInteraction}
    />
  );
};
```

### Custom Interaction Handling

```tsx
const handleInteraction = (elementId: string) => {
  switch (elementId) {
    case "heart":
      // Handle like
      break;
    case "share":
      // Handle share
      break;
    case "comments":
      // Handle comment
      break;
    case "back":
      // Handle back navigation
      break;
    default:
      if (elementId.startsWith("product-")) {
        const productIndex = parseInt(elementId.split("-")[1]);
      } else if (elementId.startsWith("add-to-cart-")) {
        const productIndex = parseInt(elementId.split("-")[3]);
      }
  }
};
```

### With Comments and Pagination

The component automatically handles comments loading and pagination when `connectionOptions` is provided. Comments are fetched from the API and displayed in the CommentsModal.

```tsx
const connectionOptions = {
  user_id: "user123",
  token: "your-token",
  scope: "short",
  space_slug: "my-space",
  slug: "my-content",
  session: "session123",
};

<InteractifyKhanoumiPlayer
  title="Product Demo"
  mediaItem={mediaItem}
  products={products}
  slug="demo-content"
  connectionOptions={connectionOptions}
  onNewMessage={(message) => {
    // handle new comment here
  }}
/>;
```

## 🎨 Styling

The library uses inline styles for maximum compatibility. All components are designed to work out of the box with a mobile-first approach.

### RTL Support

The library includes built-in RTL (Right-to-Left) support for Persian/Farsi content:

- Text alignment is automatically set to RTL
- Numbers are converted to Persian numerals using the `toFa` utility
- Layout components are optimized for RTL reading
- Product cards and modals support RTL layout

### Customization

While the library uses inline styles, you can override them by wrapping components or using CSS-in-JS solutions:

```tsx
<div
  style={{
    "--player-background": "#000",
    "--primary-color": "#E91E63",
    "--secondary-color": "#FF4081",
  }}
>
  <InteractifyKhanoumiPlayer {...props} />
</div>
```

### Theme Customization

You can customize the appearance by overriding CSS custom properties:

```css
:root {
  --player-background: #000000;
  --primary-color: #e91e63;
  --secondary-color: #ff4081;
  --text-color: #ffffff;
  --border-radius: 8px;
  --font-family: "Vazir", sans-serif;
}
```

## 🌐 Browser Support

- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
- Mobile browsers (iOS Safari, Chrome Mobile)

## 🔧 Development

### Building

```bash
npm run build
```

### Development Mode

```bash
npm run dev
```

### Type Checking

```bash
npm run type-check
```

### Clean Build

```bash
npm run clean
npm run build
```

## 📦 Build Output

The library builds to the following formats:

- **CommonJS**: `dist/index.js`
- **ES Modules**: `dist/index.esm.js`
- **TypeScript Definitions**: `dist/index.d.ts`

## 🔗 Related Packages

- [@interactify-live/player-react](https://www.npmjs.com/package/@interactify-live/player-react) - Core video player component
- [@interactify-live/media-display](https://www.npmjs.com/package/@interactify-live/media-display) - Media display utilities
- [@interactify-live/media-widgets](https://www.npmjs.com/package/@interactify-live/media-widgets) - Media widget components

## 📈 Version History

### v0.2.1

- Added caption support with expandable text
- Enhanced comments modal with reply functionality
- Improved Persian time formatting utility
- Added mention parsing in comments
- Enhanced MQTT message handling
- Improved TypeScript definitions

### v0.2.0

- **BREAKING**: Added required `slug` prop for comments functionality
- **BREAKING**: Updated connection options structure
- Added real-time chat with MQTT integration
- Enhanced comments modal with pagination
- Added Persian time formatting utility
- Improved RTL support and Persian text handling

### v0.1.6

- **BREAKING**: Removed swiper dependency for simplified product navigation
- **BREAKING**: Removed ProductDetailModal component
- Added `ProductCard` prop for custom product card components
- Improved product display flexibility - now renders custom ProductCard if provided, otherwise uses default ProductCardDetailed
- Simplified product interaction handling

### v0.1.4

- Added Persian/Farsi number conversion utility
- Improved RTL support
- Enhanced mobile responsiveness
- Added TypeScript definitions

### v0.1.3

- Added real-time chat functionality
- Improved product modal interactions
- Enhanced accessibility features

### v0.1.2

- Added comments modal with pagination
- Improved action button interactions
- Enhanced error handling

### v0.1.1

- Initial release with core functionality
- Basic video player with product integration
- Social interaction features

---

Made with ❤️ by the Interactify team