CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-video-js

An HTML5 video player that supports HLS and DASH with a common API and skin.

Pending
Overview
Eval results
Files

utilities.mddocs/

Utility Functions

Video.js provides comprehensive utility modules for DOM manipulation, time handling, browser detection, string processing, and more, organized into logical namespaces.

Capabilities

DOM Utilities

Comprehensive DOM manipulation utilities for cross-browser compatibility.

/**
 * DOM manipulation utilities namespace
 */
videojs.dom: {
  /**
   * Check if value is a DOM element
   * @param value - Value to check
   * @returns True if DOM element
   */
  isEl(value: any): boolean;
  
  /**
   * Check if value is a text node
   * @param value - Value to check
   * @returns True if text node
   */
  isTextNode(value: any): boolean;
  
  /**
   * Create DOM element with properties
   * @param tagName - Element tag name
   * @param properties - Element properties and attributes
   * @param attributes - Element attributes
   * @param content - Element content
   * @returns Created element
   */
  createEl(tagName: string, properties?: object, attributes?: object, content?: string): Element;
  
  /**
   * Find element by CSS selector
   * @param selector - CSS selector
   * @param context - Search context (default: document)
   * @returns Found element or null
   */
  $(selector: string, context?: Element): Element | null;
  
  /**
   * Find all elements by CSS selector
   * @param selector - CSS selector
   * @param context - Search context (default: document)
   * @returns NodeList of found elements
   */
  $$(selector: string, context?: Element): NodeList;
}

Usage Examples:

// Element creation
const button = videojs.dom.createEl('button', {
  className: 'vjs-custom-button',
  textContent: 'Click Me'
}, {
  'data-id': 'custom-btn',
  'aria-label': 'Custom Button'
});

// Element queries
const player = videojs.dom.$('.video-js');
const controls = videojs.dom.$$('.vjs-control', player);

// Element checks
if (videojs.dom.isEl(button)) {
  console.log('Is a DOM element');
}

CSS Class Management

Cross-browser CSS class manipulation utilities.

/**
 * Add CSS class to element
 * @param element - Target element
 * @param className - Class name to add
 */
addClass(element: Element, className: string): void;

/**
 * Remove CSS class from element
 * @param element - Target element
 * @param className - Class name to remove
 */
removeClass(element: Element, className: string): void;

/**
 * Toggle CSS class on element
 * @param element - Target element
 * @param className - Class name to toggle
 * @param predicate - Force add (true) or remove (false)
 */
toggleClass(element: Element, className: string, predicate?: boolean): void;

/**
 * Check if element has CSS class
 * @param element - Target element
 * @param className - Class name to check
 * @returns True if class exists
 */
hasClass(element: Element, className: string): boolean;

Usage Examples:

const element = videojs.dom.$('.video-js');

// Class manipulation
videojs.dom.addClass(element, 'vjs-custom-theme');
videojs.dom.removeClass(element, 'vjs-default-skin');
videojs.dom.toggleClass(element, 'vjs-fullscreen');

// Class checking
if (videojs.dom.hasClass(element, 'vjs-playing')) {
  console.log('Player is playing');
}

Element Attributes

Utilities for managing element attributes and properties.

/**
 * Set multiple attributes on element
 * @param element - Target element
 * @param attributes - Object with attribute key-value pairs
 */
setAttributes(element: Element, attributes: object): void;

/**
 * Get element attributes as object
 * @param element - Target element
 * @returns Object with attribute key-value pairs
 */
getAttributes(element: Element): object;

/**
 * Get computed styles for element
 * @param element - Target element
 * @param property - Specific property to get
 * @returns Computed style value or CSSStyleDeclaration
 */
computedStyle(element: Element, property?: string): string | CSSStyleDeclaration;

Usage Examples:

const element = videojs.dom.$('.video-js');

// Set attributes
videojs.dom.setAttributes(element, {
  'data-setup': '{}',
  'controls': true,
  'preload': 'metadata'
});

// Get attributes
const attrs = videojs.dom.getAttributes(element);
console.log('Element attributes:', attrs);

// Get computed styles
const width = videojs.dom.computedStyle(element, 'width');
console.log('Element width:', width);

Element Content Management

Utilities for managing element content and structure.

/**
 * Empty element of all content
 * @param element - Target element
 */
emptyEl(element: Element): void;

/**
 * Append content to element
 * @param element - Target element
 * @param content - Content to append (string, Element, or array)
 */
appendContent(element: Element, content: string | Element | Array<string | Element>): void;

/**
 * Insert content into element
 * @param element - Target element
 * @param content - Content to insert
 * @param position - Insert position
 */
insertContent(element: Element, content: string | Element, position?: number): void;

Time Utilities

Comprehensive time and TimeRanges utilities for media handling.

/**
 * Time utilities namespace
 */
videojs.time: {
  /**
   * Create TimeRanges object
   * @param start - Start time or array of ranges
   * @param end - End time
   * @returns TimeRanges object
   */
  createTimeRanges(start: number | Array<[number, number]>, end?: number): TimeRanges;
  
  /**
   * Format time in seconds to readable string
   * @param seconds - Time in seconds
   * @param guide - Guide time for formatting decisions
   * @returns Formatted time string (e.g., "1:23" or "1:23:45")
   */
  formatTime(seconds: number, guide?: number): string;
  
  /**
   * Set custom time formatting function
   * @param customFormatter - Custom formatting function
   */
  setFormatTime(customFormatter: (seconds: number, guide?: number) => string): void;
  
  /**
   * Reset time formatting to default
   */
  resetFormatTime(): void;
}

Usage Examples:

// Create time ranges
const buffered = videojs.time.createTimeRanges([[0, 30], [60, 90]]);
console.log('Buffered ranges:', buffered.length);

// Format time display
const currentTime = 125.5;
const duration = 3600;
console.log('Time:', videojs.time.formatTime(currentTime, duration)); // "2:05"

// Custom time formatter
videojs.time.setFormatTime((seconds) => {
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}m ${secs}s`;
});

console.log(videojs.time.formatTime(125)); // "2m 5s"

// Reset to default
videojs.time.resetFormatTime();

Browser Detection

Comprehensive browser and platform detection utilities.

/**
 * Browser detection utilities namespace
 */
videojs.browser: {
  // Browser detection flags
  IS_CHROME: boolean;
  IS_FIREFOX: boolean;
  IS_SAFARI: boolean;
  IS_EDGE: boolean;
  IS_IE: boolean;
  
  // Platform detection flags  
  IS_IOS: boolean;
  IS_ANDROID: boolean;
  IS_WINDOWS: boolean;
  IS_MAC: boolean;
  
  // Device type flags
  IS_MOBILE: boolean;
  IS_TABLET: boolean;
  IS_DESKTOP: boolean;
  IS_SMART_TV: boolean;
  
  // Feature detection
  TOUCH_ENABLED: boolean;
  BACKGROUND_SIZE_SUPPORTED: boolean;
  
  // Version information
  CHROME_VERSION: number;
  FIREFOX_VERSION: number;
  SAFARI_VERSION: number;
  IOS_VERSION: number;
  ANDROID_VERSION: number;
}

Usage Examples:

// Browser-specific behavior
if (videojs.browser.IS_SAFARI) {
  console.log('Safari-specific optimizations');
}

if (videojs.browser.IS_MOBILE) {
  console.log('Mobile interface adjustments');
  player.addClass('vjs-mobile');
}

// Version-based features
if (videojs.browser.CHROME_VERSION >= 70) {
  console.log('Modern Chrome features available');
}

// Feature detection
if (videojs.browser.TOUCH_ENABLED) {
  player.addClass('vjs-touch-enabled');
}

Object Utilities

Utilities for object manipulation and property management.

/**
 * Object utilities namespace
 */
videojs.obj: {
  /**
   * Deep merge objects
   * @param target - Target object
   * @param sources - Source objects to merge
   * @returns Merged object
   */
  merge(target: object, ...sources: object[]): object;
  
  /**
   * Define lazy property that's computed on first access
   * @param object - Target object
   * @param key - Property key
   * @param getValue - Function to compute value
   * @param setValue - Function to set value (optional)
   */
  defineLazyProperty(object: object, key: string, getValue: () => any, setValue?: (value: any) => void): void;
  
  /**
   * Check if value is a plain object
   * @param value - Value to check
   * @returns True if plain object
   */
  isObject(value: any): boolean;
}

Usage Examples:

// Merge configuration objects
const defaultOptions = { controls: true, autoplay: false };
const userOptions = { autoplay: true, volume: 0.8 };
const finalOptions = videojs.obj.merge({}, defaultOptions, userOptions);
// Result: { controls: true, autoplay: true, volume: 0.8 }

// Lazy properties for expensive computations
const obj = {};
videojs.obj.defineLazyProperty(obj, 'expensiveValue', () => {
  console.log('Computing expensive value...');
  return performExpensiveOperation();
});

// Value computed only when first accessed
console.log(obj.expensiveValue);

String Utilities

String processing utilities for text manipulation.

/**
 * String utilities namespace
 */
videojs.str: {
  /**
   * Convert string to title case
   * @param str - Input string
   * @returns Title case string
   */
  toTitleCase(str: string): string;
  
  /**
   * Convert string to lower case
   * @param str - Input string
   * @returns Lower case string
   */
  toLowerCase(str: string): string;
  
  /**
   * Compare strings in title case
   * @param str1 - First string
   * @param str2 - Second string
   * @returns True if equal in title case
   */
  titleCaseEquals(str1: string, str2: string): boolean;
}

Number Utilities

Number processing and validation utilities.

/**
 * Number utilities namespace
 */
videojs.num: {
  /**
   * Clamp number between min and max values
   * @param number - Input number
   * @param min - Minimum value
   * @param max - Maximum value
   * @returns Clamped number
   */
  clamp(number: number, min: number, max: number): number;
}

URL Utilities

URL parsing and manipulation utilities.

/**
 * URL utilities namespace
 */
videojs.url: {
  /**
   * Parse URL into components
   * @param url - URL string to parse
   * @returns Parsed URL components
   */
  parseUrl(url: string): UrlComponents;
  
  /**
   * Check if URL is cross-origin
   * @param url - URL to check
   * @param winLoc - Window location (optional)
   * @returns True if cross-origin
   */
  isCrossOrigin(url: string, winLoc?: Location): boolean;
  
  /**
   * Get absolute URL from relative URL
   * @param url - Relative URL
   * @returns Absolute URL
   */
  getAbsoluteURL(url: string): string;
}

Function Utilities

Function-related utilities for binding and manipulation.

/**
 * Function utilities namespace
 */
videojs.fn: {
  /**
   * Bind function to context (deprecated - use native bind)
   * @param context - Context to bind to
   * @param fn - Function to bind
   * @param uid - Unique identifier
   * @returns Bound function
   */
  bind_(context: any, fn: Function, uid?: number): Function;
  
  /**
   * Create GUID/UUID
   * @returns Unique identifier string
   */
  newGUID(): string;
}

Logging Utilities

Comprehensive logging system with levels and namespaces.

/**
 * Main logging function
 * @param messages - Messages to log
 */
videojs.log(...messages: any[]): void;

/**
 * Create named logger
 * @param name - Logger name
 * @returns Logger function
 */
videojs.createLogger(name: string): LoggerFunction;

// Logging levels
videojs.log.level: LogLevel;
videojs.log.debug: LoggerFunction;
videojs.log.info: LoggerFunction;
videojs.log.warn: LoggerFunction;
videojs.log.error: LoggerFunction;

Usage Examples:

// Basic logging
videojs.log('Player initialized');

// Create named logger
const pluginLogger = videojs.createLogger('MyPlugin');
pluginLogger('Plugin action performed');

// Set log level
videojs.log.level('warn'); // Only show warnings and errors

// Different log levels
videojs.log.debug('Debug information');
videojs.log.info('Informational message');
videojs.log.warn('Warning message');
videojs.log.error('Error message');

Deprecated Utilities

Legacy utility methods maintained for backward compatibility.

// Deprecated DOM methods (use videojs.dom.* instead)
videojs.isEl(element): boolean; // Use videojs.dom.isEl
videojs.createEl(tagName, props): Element; // Use videojs.dom.createEl
videojs.addClass(element, className): void; // Use videojs.dom.addClass

// Deprecated time methods (use videojs.time.* instead)
videojs.createTimeRange(start, end): TimeRanges; // Use videojs.time.createTimeRanges
videojs.formatTime(seconds): string; // Use videojs.time.formatTime

// Deprecated object methods (use videojs.obj.* instead)
videojs.mergeOptions(obj1, obj2): object; // Use videojs.obj.merge

Types

interface UrlComponents {
  protocol: string;
  hostname: string;
  port: string;
  pathname: string;
  search: string;
  hash: string;
  host: string;
}

interface LoggerFunction {
  (...messages: any[]): void;
  level?: LogLevel;
}

type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'off';

interface TimeRanges {
  readonly length: number;
  start(index: number): number;
  end(index: number): number;
}

// Utility namespaces
interface DomUtils {
  isEl(value: any): boolean;
  createEl(tagName: string, properties?: object): Element;
  addClass(element: Element, className: string): void;
  removeClass(element: Element, className: string): void;
  hasClass(element: Element, className: string): boolean;
  $(selector: string, context?: Element): Element | null;
  $$(selector: string, context?: Element): NodeList;
}

interface TimeUtils {
  createTimeRanges(start: number | Array<[number, number]>, end?: number): TimeRanges;
  formatTime(seconds: number, guide?: number): string;
  setFormatTime(formatter: (seconds: number, guide?: number) => string): void;
  resetFormatTime(): void;
}

interface ObjectUtils {
  merge(target: object, ...sources: object[]): object;
  defineLazyProperty(object: object, key: string, getValue: () => any): void;
  isObject(value: any): boolean;
}

Install with Tessl CLI

npx tessl i tessl/npm-video-js

docs

components.md

events.md

index.md

player.md

plugins.md

tech.md

tracks.md

utilities.md

tile.json