CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mediaelement

HTML5 video and audio player with unified cross-browser interface and extensive customization options

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

utility-functions.mddocs/

Utility Functions

MediaElement.js provides a comprehensive set of utility functions for DOM manipulation, media type detection, time formatting, and browser feature detection, accessible through the mejs.Utils namespace.

Capabilities

DOM Utilities

Helper functions for DOM manipulation and element interaction.

/**
 * Check if element has a CSS class
 * @param el - HTML element to check
 * @param className - CSS class name to look for
 * @returns Whether element has the class
 */
function hasClass(el: HTMLElement, className: string): boolean;

/**
 * Add CSS class to element
 * @param el - HTML element to modify
 * @param className - CSS class name to add
 */
function addClass(el: HTMLElement, className: string): void;

/**
 * Remove CSS class from element
 * @param el - HTML element to modify  
 * @param className - CSS class name to remove
 */
function removeClass(el: HTMLElement, className: string): void;

/**
 * Toggle CSS class on element
 * @param el - HTML element to modify
 * @param className - CSS class name to toggle
 */
function toggleClass(el: HTMLElement, className: string): void;

/**
 * Get element's offset position relative to document
 * @param el - HTML element to measure
 * @returns Object with top and left offset values
 */
function offset(el: HTMLElement): { top: number; left: number };

/**
 * Get sibling elements of a given element
 * @param el - Reference element
 * @param filter - Optional filter function
 * @returns Array of sibling elements
 */
function siblings(el: HTMLElement, filter?: (element: HTMLElement) => boolean): HTMLElement[];

/**
 * Check if element is visible
 * @param elem - HTML element to check
 * @returns Whether element is visible
 */
function visible(elem: HTMLElement): boolean;

Usage Examples:

import { mejs } from 'mediaelement';

const playerElement = document.getElementById('player');

// CSS class manipulation
if (!mejs.Utils.hasClass(playerElement, 'active')) {
  mejs.Utils.addClass(playerElement, 'active');
}

mejs.Utils.removeClass(playerElement, 'loading');
mejs.Utils.toggleClass(playerElement, 'playing');

// Element positioning
const position = mejs.Utils.offset(playerElement);
console.log(`Player position: ${position.left}, ${position.top}`);

// Check visibility
if (mejs.Utils.visible(playerElement)) {
  console.log('Player is visible');
}

// Get siblings
const siblingElements = mejs.Utils.siblings(playerElement);
console.log(`Found ${siblingElements.length} siblings`);

Animation Utilities

Functions for smooth element animations.

/**
 * Fade element in with animation
 * @param el - HTML element to fade in
 * @param duration - Animation duration in milliseconds
 * @param callback - Optional callback when animation completes
 */
function fadeIn(el: HTMLElement, duration?: number, callback?: () => void): void;

/**
 * Fade element out with animation
 * @param el - HTML element to fade out
 * @param duration - Animation duration in milliseconds
 * @param callback - Optional callback when animation completes  
 */
function fadeOut(el: HTMLElement, duration?: number, callback?: () => void): void;

Usage Examples:

import { mejs } from 'mediaelement';

const controlsElement = document.querySelector('.mejs__controls');

// Fade controls in over 300ms
mejs.Utils.fadeIn(controlsElement, 300, () => {
  console.log('Controls faded in');
});

// Fade controls out over 500ms
mejs.Utils.fadeOut(controlsElement, 500, () => {
  console.log('Controls faded out');
});

Script Loading Utilities

Dynamic script loading with Promise support.

/**
 * Dynamically load JavaScript file
 * @param url - URL of script to load
 * @returns Promise that resolves when script loads
 */
function loadScript(url: string): Promise<void>;

Usage Examples:

import { mejs } from 'mediaelement';

// Load HLS.js library dynamically
mejs.Utils.loadScript('https://cdn.jsdelivr.net/npm/hls.js@latest/dist/hls.min.js')
  .then(() => {
    console.log('HLS.js loaded successfully');
    // Initialize HLS player
  })
  .catch((error) => {
    console.error('Failed to load HLS.js:', error);
  });

// Load multiple scripts sequentially
async function loadDependencies() {
  try {
    await mejs.Utils.loadScript('/js/hls.min.js');
    await mejs.Utils.loadScript('/js/dash.min.js');
    console.log('All dependencies loaded');
  } catch (error) {
    console.error('Failed to load dependencies:', error);
  }
}

AJAX Utilities

Simple AJAX request functionality.

/**
 * Make AJAX request
 * @param url - Request URL
 * @param dataType - Expected response type ('json', 'text', 'xml')
 * @param success - Success callback function
 * @param error - Error callback function
 */
function ajax(
  url: string, 
  dataType: 'json' | 'text' | 'xml', 
  success: (data: any) => void, 
  error: (xhr: XMLHttpRequest) => void
): void;

Usage Examples:

import { mejs } from 'mediaelement';

// Load player configuration from server
mejs.Utils.ajax(
  '/api/player-config.json',
  'json',
  (config) => {
    console.log('Config loaded:', config);
    // Initialize player with server config
    const player = new MediaElementPlayer('video', config);
  },
  (xhr) => {
    console.error('Failed to load config:', xhr.status);
  }
);

// Load subtitle tracks
mejs.Utils.ajax(
  '/api/subtitles.vtt',
  'text',
  (vttData) => {
    console.log('Subtitles loaded');
    // Add track to player
  },
  (xhr) => {
    console.error('Failed to load subtitles');
  }
);

Media Type Detection

Functions for detecting and working with media types and file extensions.

/**
 * Convert relative URL to absolute URL
 * @param url - Relative or absolute URL
 * @returns Absolute URL
 */
function absolutizeUrl(url: string): string;

/**
 * Format media type string
 * @param url - Media file URL
 * @param type - Optional explicit type
 * @returns Formatted MIME type
 */
function formatType(url: string, type?: string): string;

/**
 * Extract MIME type from type string
 * @param type - Type string that may include codecs
 * @returns Clean MIME type
 */
function getMimeFromType(type: string): string;

/**
 * Detect media type from file URL
 * @param url - Media file URL
 * @returns Detected MIME type
 */
function getTypeFromFile(url: string): string;

/**
 * Get file extension from URL
 * @param url - File URL
 * @returns File extension (without dot)
 */
function getExtension(url: string): string;

/**
 * Normalize file extension
 * @param extension - File extension
 * @returns Normalized extension
 */
function normalizeExtension(extension: string): string;

Usage Examples:

import { mejs } from 'mediaelement';

// URL handling
const relativeUrl = '../videos/sample.mp4';
const absoluteUrl = mejs.Utils.absolutizeUrl(relativeUrl);
console.log('Absolute URL:', absoluteUrl);

// Media type detection
const videoUrl = 'https://example.com/video.mp4';
const detectedType = mejs.Utils.getTypeFromFile(videoUrl);
console.log('Detected type:', detectedType); // 'video/mp4'

const extension = mejs.Utils.getExtension(videoUrl);
console.log('Extension:', extension); // 'mp4'

// Type formatting
const formattedType = mejs.Utils.formatType(videoUrl);
console.log('Formatted type:', formattedType);

// MIME type extraction
const complexType = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
const mimeType = mejs.Utils.getMimeFromType(complexType);
console.log('MIME type:', mimeType); // 'video/mp4'

Time Formatting Utilities

Functions for converting and formatting time values and timecodes.

/**
 * Convert seconds to formatted timecode string
 * @param time - Time in seconds
 * @param forceHours - Force hour display even for short durations
 * @param showFrameCount - Include frame count in display
 * @param fps - Frames per second for frame calculation
 * @param secondsDecimalLength - Decimal places for seconds
 * @param timeFormat - Custom time format string
 * @returns Formatted time string
 */
function secondsToTimeCode(
  time: number,
  forceHours?: boolean,
  showFrameCount?: boolean,
  fps?: number,
  secondsDecimalLength?: number,
  timeFormat?: string
): string;

/**
 * Convert SMPTE timecode to seconds
 * @param smpte - SMPTE timecode string (HH:MM:SS:FF)
 * @returns Time in seconds
 */
function convertSMPTEtoSeconds(smpte: string): number;

/**
 * Convert time string to seconds
 * @param time - Time string in various formats
 * @returns Time in seconds
 */
function timeStringToSeconds(time: string): number;

/**
 * Calculate appropriate time format for duration
 * @param time - Duration in seconds
 * @param options - Formatting options
 * @param fps - Frames per second
 */
function calculateTimeFormat(time: number, options: TimeFormatOptions, fps?: number): void;

interface TimeFormatOptions {
  alwaysShowHours?: boolean;
  showTimecodeFrameCount?: boolean;
  framesPerSecond?: number;
  timeFormat?: string;
}

Usage Examples:

import { mejs } from 'mediaelement';

// Basic time formatting
const duration = 3661; // 1 hour, 1 minute, 1 second
const timeString = mejs.Utils.secondsToTimeCode(duration);
console.log('Duration:', timeString); // '1:01:01'

// Force hour display for short durations
const shortTime = 90; // 1.5 minutes
const withHours = mejs.Utils.secondsToTimeCode(shortTime, true);
console.log('With hours:', withHours); // '0:01:30'

// Frame count display for video editing
const timeWithFrames = mejs.Utils.secondsToTimeCode(10.5, false, true, 30);
console.log('With frames:', timeWithFrames); // '0:10:15' (15 frames at 30fps)

// Convert time strings to seconds
const timeInSeconds = mejs.Utils.timeStringToSeconds('1:30:45');
console.log('Seconds:', timeInSeconds); // 5445

// Convert SMPTE timecode
const smpteSeconds = mejs.Utils.convertSMPTEtoSeconds('01:30:45:15');
console.log('SMPTE seconds:', smpteSeconds);

// Format calculation
const formatOptions = {
  alwaysShowHours: false,
  showTimecodeFrameCount: false,
  framesPerSecond: 25
};
mejs.Utils.calculateTimeFormat(3661, formatOptions);

General Utilities

Miscellaneous utility functions for common tasks.

/**
 * Escape HTML entities in string
 * @param input - String to escape
 * @returns HTML-safe string
 */
function escapeHTML(input: string): string;

/**
 * Debounce function calls
 * @param func - Function to debounce
 * @param wait - Wait time in milliseconds
 * @param immediate - Execute immediately on first call
 * @returns Debounced function
 */
function debounce(func: Function, wait: number, immediate?: boolean): Function;

/**
 * Check if object is empty
 * @param instance - Object to check
 * @returns Whether object has no properties
 */
function isObjectEmpty(instance: object): boolean;

/**
 * Check if value is a string
 * @param value - Value to check
 * @returns Whether value is string type
 */
function isString(value: any): boolean;

/**
 * Create custom event
 * @param eventName - Name of event to create
 * @param target - Target element for event
 * @param isIframe - Whether event is for iframe
 * @returns Custom event object
 */
function createEvent(eventName: string, target?: HTMLElement, isIframe?: boolean): Event;

/**
 * Check if one DOM node comes after another
 * @param sourceNode - First node
 * @param targetNode - Second node  
 * @returns Whether sourceNode comes after targetNode
 */
function isNodeAfter(sourceNode: Node, targetNode: Node): boolean;

/**
 * Split events into document and window events
 * @param events - Event string with space-separated event names
 * @param id - Element ID for namespacing
 * @returns Object with document and window event arrays
 */
function splitEvents(events: string, id: string): { d: string[]; w: string[] };

Usage Examples:

import { mejs } from 'mediaelement';

// HTML escaping for safe display
const userInput = '<script>alert("xss")</script>';
const safeText = mejs.Utils.escapeHTML(userInput);
console.log('Safe text:', safeText); // '&lt;script&gt;alert("xss")&lt;/script&gt;'

// Debounce resize handler
const handleResize = mejs.Utils.debounce(() => {
  console.log('Window resized');
  // Expensive resize logic here
}, 250);

window.addEventListener('resize', handleResize);

// Type checking
const config = { autoplay: true };
if (!mejs.Utils.isObjectEmpty(config)) {
  console.log('Config has options');
}

const title = "My Video";
if (mejs.Utils.isString(title)) {
  console.log('Title is valid string');
}

// Custom events
const customEvent = mejs.Utils.createEvent('playerReady', playerElement);
playerElement.dispatchEvent(customEvent);

// DOM position checking
const button1 = document.getElementById('play-btn');
const button2 = document.getElementById('pause-btn');
if (mejs.Utils.isNodeAfter(button2, button1)) {
  console.log('Pause button comes after play button');
}

// Event splitting for different contexts
const eventString = 'click touchstart mouseover';
const events = mejs.Utils.splitEvents(eventString, 'player1');
console.log('Document events:', events.d);
console.log('Window events:', events.w);

Browser Feature Detection

Access to browser capability detection through the utility system.

// Access feature detection through mejs.Features
interface FeatureDetection {
  isiOS: boolean;
  isAndroid: boolean;
  isiPad: boolean;
  isiPhone: boolean;
  isIE: boolean;
  isChrome: boolean;
  isFirefox: boolean;
  isSafari: boolean;
  hasNativeFullscreen: boolean;
  supportsNativeHLS: boolean;
  hasMSE: boolean; // Media Source Extensions
}

// Available as mejs.Features
const features: FeatureDetection = window.mejs.Features;

Usage Examples:

import { mejs } from 'mediaelement';

// Platform-specific behavior
if (mejs.Features.isiOS) {
  console.log('Running on iOS device');
  // Use iOS-specific optimizations
}

if (mejs.Features.isAndroid) {
  console.log('Running on Android device');
  // Handle Android-specific quirks
}

// Browser capability checks
if (mejs.Features.hasNativeFullscreen) {
  console.log('Native fullscreen API available');
} else {
  console.log('Fallback fullscreen implementation needed');
}

if (mejs.Features.supportsNativeHLS) {
  console.log('Browser supports HLS natively');
  // Don't need hls.js library
} else {
  console.log('Need HLS.js for HLS support');
}

if (mejs.Features.hasMSE) {
  console.log('Media Source Extensions supported');
  // Can use adaptive streaming
}

docs

configuration.md

core-media-element.md

feature-system.md

index.md

media-player.md

renderer-system.md

utility-functions.md

tile.json