@interactive-video-labs/svelte
Version:
Thin Svelte wrapper for the @interactive-video-labs/core engine. Enables cue-based interactive video playback in Svelte applications.
85 lines (84 loc) • 2.92 kB
JavaScript
import { onMount, onDestroy } from 'svelte';
import { IVLabsPlayer } from '@interactive-video-labs/core';
/**
* A Svelte component that wraps the IVLabsPlayer to provide interactive video capabilities.
* It handles the lifecycle of the player, including initialization, updates, and destruction.
*/
export default function InteractiveVideo(node, props) {
let player = null;
const playerTargetId = props.targetElementId || `ivlabs-player-${Math.random().toString(36).substr(2, 9)}`;
const initializePlayer = () => {
if (player) {
return; // Player already initialized
}
const targetElement = document.getElementById(playerTargetId);
if (!targetElement) {
console.error(`IVLabsPlayer target element with ID '${playerTargetId}' not found.`);
return;
}
// Exclude 'translations' from playerConfig to match PlayerConfig type
const { translations, ...restProps } = props;
const playerConfig = {
...restProps,
videoUrl: props.videoUrl,
autoplay: props.autoplay ?? false,
loop: props.loop ?? false,
locale: props.locale ?? 'en',
};
try {
player = new IVLabsPlayer(playerTargetId, playerConfig);
if (props.onAnalyticsEvent) {
const analyticsHandler = props.onAnalyticsEvent;
const eventsToRegister = [
'PLAYER_LOADED',
'VIDEO_STARTED',
'VIDEO_PAUSED',
'VIDEO_ENDED',
'CUE_TRIGGERED',
'INTERACTION_COMPLETED',
'ERROR',
];
eventsToRegister.forEach((event) => {
player.on(event, (payload) => {
analyticsHandler(event, payload);
});
});
}
if (props.cues) {
player.loadCues(props.cues);
}
if (props.translations) {
player.loadTranslations(props.locale ?? 'en', props.translations);
}
}
catch (error) {
console.error('Error initializing IVLabsPlayer:', error);
}
};
onMount(() => {
initializePlayer();
});
onDestroy(() => {
if (player) {
player.destroy();
player = null;
}
});
return {
update(newProps) {
if (player) {
if (newProps.cues) {
player.loadCues(newProps.cues);
}
if (newProps.translations) {
player.loadTranslations(newProps.locale ?? 'en', newProps.translations);
}
}
},
destroy() {
if (player) {
player.destroy();
}
}
};
}