Spaces:
Running
Running
File size: 11,071 Bytes
e545160 bd5fab7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
<!-- videoslider/frontend/shared/VideoSliderPreview.svelte -->
<script lang="ts">
// Svelte and Gradio imports
import { createEventDispatcher, onMount, onDestroy, tick } from "svelte";
import type { FileData, Client } from "@gradio/client";
import type { I18nFormatter } from "@gradio/utils";
import Slider from "./Slider.svelte";
import Player from "./Player.svelte";
import { BlockLabel, Empty, IconButton, IconButtonWrapper, FullscreenButton } from "@gradio/atoms";
import { Video as VideoIcon, Download, Clear, VolumeMuted, VolumeHigh } from "@gradio/icons";
import { DownloadLink } from "@gradio/wasm/svelte";
// ------------------
// Props
// ------------------
export let value: [FileData | null, FileData | null] = [null, null];
export let label: string | undefined = undefined;
export let show_download_button = true;
export let show_label: boolean;
export let i18n: I18nFormatter;
export let position: number = 0.5;
export let slider_color: string;
export let show_fullscreen_button = true;
export let show_mute_button = true;
export let fullscreen = false;
export let interactive = true;
export let autoplay = false;
export let loop = false;
export let upload: Client["upload"];
const dispatch = createEventDispatcher<{
clear: void;
fullscreen: boolean;
load: { top: number; left: number; width: number; height: number };
}>();
// -----------------
// Internal State & Element References
// -----------------
let video1_el: HTMLVideoElement | undefined;
let video2_el: HTMLVideoElement | undefined;
let main_wrapper_el: HTMLDivElement | undefined;
let image_size = { top: 0, left: 0, width: 0, height: 0 };
let viewport_width = 0;
let resizeObserver: ResizeObserver | undefined;
/** Tracks the muted state for both videos. Starts true to allow autoplay. */
let isMuted = true;
/** A flag to prevent the main click handler from firing when interacting with overlay buttons. */
let isInteractingWithButtons = false;
/** A flag to ensure the dimension initialization logic runs only once. */
let is_initialized = false;
// -----------------
// Event Handlers
// -----------------
/** Toggles the muted state for both videos. */
function toggleMute(event: Event) {
event.stopPropagation();
isInteractingWithButtons = true;
if (video1_el && video2_el) {
isMuted = !isMuted;
video1_el.muted = isMuted;
video2_el.muted = isMuted;
}
setTimeout(() => (isInteractingWithButtons = false), 0);
}
/** Clears both videos and resets the slider position. */
function removeVideos(event: Event) {
event.stopPropagation();
isInteractingWithButtons = true;
value = [null, null];
position = 0.5;
dispatch("clear");
setTimeout(() => (isInteractingWithButtons = false), 0);
}
/** Toggles play/pause for both videos simultaneously. */
function toggle_playback(event: Event): void {
event.stopPropagation();
if (!video1_el || !video2_el) return;
const is_paused = video1_el.paused;
if (is_paused) {
video1_el.play().catch(() => {});
video2_el.play().catch(() => {});
} else {
video1_el.pause();
video2_el.pause();
}
}
/** Handles the fullscreen event from the button, resets position, and dispatches. */
function handle_fullscreen_toggle(event: CustomEvent{
position = 0.5; // We still want to reset the position
dispatch("fullscreen", event.detail);
}
/** Handles the load event from the Player component to update dimensions. */
function handle_video_load(event: CustomEvent) {
image_size = event.detail;
if (main_wrapper_el) {
viewport_width = main_wrapper_el.getBoundingClientRect().width;
}
position = 0.5;
dispatch("load", image_size);
}
/** A utility function to constrain a value within a minimum and maximum range. */
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
/**
* Calculates the clipped position of the slider based on the video's
* dimensions and offset within the viewport.
*/
function get_coords_at_viewport(
viewport_percent_x: number,
viewportWidth: number,
video_width: number,
video_offset_x: number
): number {
const px_relative_to_video = viewport_percent_x * video_width;
const pixel_position = px_relative_to_video + video_offset_x;
const percent_position = pixel_position / viewportWidth;
return clamp(percent_position, 0, 1);
}
/**
* Sets up a ResizeObserver to monitor the video and its container,
* updating the `image_size` state whenever their dimensions change.
*/
function init_video(video: HTMLVideoElement | null, wrapper: HTMLDivElement | null): void {
if (!video || !wrapper) return;
resizeObserver?.disconnect();
const updateVideoDimensions = () => {
const rect = video.getBoundingClientRect();
const wrapperRect = wrapper.getBoundingClientRect();
image_size = {
top: rect.top - wrapperRect.top,
left: rect.left - wrapperRect.left,
width: rect.width || wrapperRect.width,
height: rect.height || wrapperRect.height
};
viewport_width = wrapperRect.width;
dispatch("load", image_size);
};
resizeObserver = new ResizeObserver(() => {
updateVideoDimensions();
position = 0.5;
});
video.addEventListener('loadedmetadata', updateVideoDimensions);
resizeObserver.observe(wrapper);
resizeObserver.observe(video);
updateVideoDimensions();
}
// -----------------
// Reactive Logic & Lifecycle
// -----------------
/** Calculates the coordinates for the CSS clip-path. */
$: coords_at_viewport = get_coords_at_viewport(
position,
viewport_width || 640,
image_size.width || viewport_width || 640,
image_size.left || 0
);
/** A reactive CSS style to create the "reveal" effect. */
$: style = `clip-path: inset(0 0 0 ${coords_at_viewport * 100}%)`;
/** Initializes the video dimension tracking once the necessary elements are available. */
$: if (main_wrapper_el && video1_el && !is_initialized) {
init_video(video1_el, main_wrapper_el);
is_initialized = true;
}
/** Synchronizes the state of the two videos (playback time and pause state). */
$: {
if (video1_el && autoplay && !video1_el.played.length) {
video1_el.play().catch(() => {});
}
if (video1_el && video2_el) {
if (Math.abs(video1_el.currentTime - video2_el.currentTime) > 0.1) {
video2_el.currentTime = video1_el.currentTime;
}
if (video1_el.paused !== video2_el.paused) {
if (video1_el.paused) {
video2_el.pause();
} else {
video2_el.play().catch(() => {});
}
}
}
}
/** On mount, sets initial state and cleans up the observer on destroy. */
onMount(() => {
position = 0.5;
if (video1_el) video1_el.muted = true;
if (video2_el) video2_el.muted = true;
return () => {
resizeObserver?.disconnect();
};
});
</script>
<BlockLabel {show_label} Icon={VideoIcon} label={label || "Video Slider"} />
{#if value === null || value[0] === null || value[1] === null}
<Empty unpadded_box={true} size="large"><VideoIcon /></Empty>
{:else}
<div class="video-container">
<div
class="icon-button-wrapper"
role="group"
>
<IconButtonWrapper>
{#if show_fullscreen_button}
<FullscreenButton
bind:fullscreen
on:fullscreen={handle_fullscreen_toggle}
/>
{/if}
{#if show_download_button && value[1]}
<DownloadLink href={value[1]?.url} download={value[1]?.orig_name || "video"}>
<IconButton Icon={Download} label={i18n("common.download")} />
</DownloadLink>
{/if}
{#if show_mute_button}
<div role="button" tabindex="0" on:mousedown|stopPropagation on:touchstart|stopPropagation>
<IconButton
Icon={isMuted ? VolumeMuted : VolumeHigh}
label={isMuted ? i18n("common.unmute") : i18n("common.mute")}
on:click={toggleMute}
on:keydown={(event) => {
if (event.key === "Enter" || event.key === " ") {
toggleMute(event);
}
}}
/>
</div>
{/if}
{#if interactive}
<div role="button" tabindex="0" on:mousedown|stopPropagation on:touchstart|stopPropagation>
<IconButton
Icon={Clear}
label="Remove Videos"
on:click={removeVideos}
on:keydown={(event) => {
if (event.key === "Enter" || event.key === " ") {
removeVideos(event);
}
}}
/>
</div>
{/if}
</IconButtonWrapper>
</div>
<div
class="main-wrapper"
bind:this={main_wrapper_el}
on:mousedown|stopPropagation={toggle_playback}
on:touchstart|stopPropagation={toggle_playback}
on:keydown={(event) => {
if (event.key === "Enter" || event.key === " ") {
toggle_playback(event);
}
}}
role="button"
tabindex="0"
>
<Slider bind:position {slider_color} {image_size} disabled={isInteractingWithButtons} bind:parent_el={main_wrapper_el}>
<div class="player-wrapper">
{#if value[0]}
<Player
src={value[0].meta?._base64 || value[0].url}
bind:video_el={video1_el}
on:load={handle_video_load}
{loop}
muted={isMuted}
{i18n}
{upload}
mirror={false}
is_stream={value[0].is_stream}
interactive={false}
{fullscreen}
/>
{/if}
</div>
<div class="player-wrapper fixed" style={style}>
{#if value[1]}
<Player
src={value[1].meta?._base64 || value[1].url}
bind:video_el={video2_el}
{loop}
muted={isMuted}
{i18n}
{upload}
mirror={false}
is_stream={value[1].is_stream}
interactive={false}
{fullscreen}
/>
{/if}
</div>
</Slider>
</div>
</div>
{/if}
<style>
.video-container {
height: 100%;
width: 100%;
position: relative;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
z-index: 1;
}
.main-wrapper {
user-select: none;
height: 100%;
width: 100%;
position: relative;
display: flex;
align-items: center;
justify-content: center;
z-index: 2;
}
.player-wrapper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
z-index: 3;
pointer-events: none;
}
.player-wrapper.fixed {
background: var(--block-background-fill);
z-index: 4;
}
.player-wrapper :global(video) {
width: 100%;
height: 100%;
object-fit: contain;
z-index: 5;
pointer-events: none;
}
:global(.main-wrapper > .wrap) {
position: absolute;
top: 0;
left: 0;
z-index: 10;
cursor: default;
}
.icon-button-wrapper {
z-index: 1001; /* Above slider's z-index: 1000 */
pointer-events: auto;
position: absolute;
top: 10px;
right: 10px;
}
</style> |