Skip to content

🎥 Make videos programmatically with React

player seek bar

Jonny Burgerbecc8c4cc6e9
diff --git a/packages/cli/src/editor/components/PlayPause.tsx b/packages/cli/src/editor/components/PlayPause.tsx
index 32749faf81..657a6ab59b 100644
--- a/packages/cli/src/editor/components/PlayPause.tsx
+++ b/packages/cli/src/editor/components/PlayPause.tsx
@@ -12,7 +12,7 @@ export const PlayPause: React.FC = () => {
const frame = Internals.Timeline.useTimelinePosition();
const video = Internals.useVideo();
- const [toggle, frameBack, frameForward, isLastFrame] = usePlaybackTime();
+ const {toggle, frameBack, frameForward, isLastFrame} = usePlaybackTime();
const onKeyPress = useCallback(
(e: KeyboardEvent) => {
diff --git a/packages/player-example/src/index.tsx b/packages/player-example/src/index.tsx
index 083a3677eb..b011bf50f2 100644
--- a/packages/player-example/src/index.tsx
+++ b/packages/player-example/src/index.tsx
@@ -3,4 +3,10 @@ import App from './App';
const rootElement = document.getElementById('root');
-render(<App />, rootElement);
+render(
+ <>
+ <App />
+ <App />
+ </>,
+ rootElement
+);
diff --git a/packages/player/src/PlayPause.ts b/packages/player/src/PlayPause.ts
index e946c4e89d..d39fba4c76 100644
--- a/packages/player/src/PlayPause.ts
+++ b/packages/player/src/PlayPause.ts
@@ -1,12 +1,12 @@
import {useCallback, useEffect, useRef} from 'react';
import {Internals} from 'remotion';
-export const usePlaybackTime = (): [
- toggle: () => void,
- frameBack: (frames: number) => void,
- frameForward: (frames: number) => void,
- isLastFrame: boolean
-] => {
+export const usePlaybackTime = (): {
+ toggle: () => void;
+ frameBack: (frames: number) => void;
+ frameForward: (frames: number) => void;
+ isLastFrame: boolean;
+} => {
const [playing, setPlaying] = Internals.Timeline.usePlayingState();
const frame = Internals.Timeline.useTimelinePosition();
const setFrame = Internals.Timeline.useTimelineSetFrame();
@@ -99,5 +99,5 @@ export const usePlaybackTime = (): [
};
}, [config, setFrame, playing]);
- return [toggle, frameBack, frameForward, isLastFrame];
+ return {toggle, frameBack, frameForward, isLastFrame};
};
diff --git a/packages/player/src/PlayerControls.tsx b/packages/player/src/PlayerControls.tsx
new file mode 100644
index 0000000000..bae11b2461
--- /dev/null
+++ b/packages/player/src/PlayerControls.tsx
@@ -0,0 +1,172 @@
+import {useCallback, useEffect, useRef, useState} from 'react';
+import {Internals, interpolate} from 'remotion';
+import {formatTime} from './format-time';
+import {usePlaybackTime} from './PlayPause';
+import {useElementSize} from './use-element-size';
+
+const getFrameFromX = (
+ clientX: number,
+ durationInFrames: number,
+ width: number
+) => {
+ const pos = clientX;
+ const frame = Math.round(
+ interpolate(pos, [0, width], [0, durationInFrames - 1 ?? 0], {
+ extrapolateLeft: 'clamp',
+ extrapolateRight: 'clamp',
+ })
+ );
+ return frame;
+};
+
+export const Controls: React.FC<{
+ fps: number;
+ durationInFrames: number;
+}> = ({durationInFrames, fps}) => {
+ const sliderAreaRef = useRef<HTMLDivElement>(null);
+ const size = useElementSize(sliderAreaRef);
+
+ const [dragging, setDragging] = useState<
+ | {
+ dragging: false;
+ }
+ | {
+ dragging: true;
+ wasPlaying: boolean;
+ }
+ >({
+ dragging: false,
+ });
+
+ const {toggle} = usePlaybackTime();
+ const [playing, setPlaying] = Internals.Timeline.usePlayingState();
+ const frame = Internals.Timeline.useTimelinePosition();
+ const setTimelinePosition = Internals.Timeline.useTimelineSetFrame();
+
+ const onPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ if (!size) {
+ throw new Error('Player has no size');
+ }
+ const _frame = getFrameFromX(
+ e.clientX - size.left,
+ durationInFrames,
+ size.width
+ );
+ setTimelinePosition(_frame);
+ setDragging({
+ dragging: true,
+ wasPlaying: playing,
+ });
+ setPlaying(false);
+ },
+ [durationInFrames, playing, setPlaying, setTimelinePosition, size]
+ );
+
+ const onPointerMove = useCallback(
+ (e: PointerEvent) => {
+ if (!size) {
+ throw new Error('Player has no size');
+ }
+ if (!dragging.dragging) {
+ return;
+ }
+ const _frame = getFrameFromX(
+ e.clientX - (size?.left ?? 0),
+ durationInFrames,
+ size.width
+ );
+ setTimelinePosition(_frame);
+ },
+ [dragging.dragging, durationInFrames, setTimelinePosition, size]
+ );
+
+ const onPointerUp = useCallback(() => {
+ setDragging({
+ dragging: false,
+ });
+ if (!dragging.dragging) {
+ return;
+ }
+ setPlaying(dragging.wasPlaying);
+ }, [dragging, setPlaying]);
+
+ useEffect(() => {
+ if (!dragging.dragging) {
+ return;
+ }
+ window.addEventListener('pointermove', onPointerMove);
+ window.addEventListener('pointerup', onPointerUp);
+ return () => {
+ window.removeEventListener('pointermove', onPointerMove);
+ window.removeEventListener('pointerup', onPointerUp);
+ };
+ }, [dragging.dragging, onPointerMove, onPointerUp]);
+
+ return (
+ <div
+ style={{
+ boxSizing: 'border-box',
+ position: 'absolute',
+ bottom: 0,
+ width: '100%',
+ paddingTop: 40,
+ paddingBottom: 10,
+ background: 'linear-gradient(transparent, rgba(0, 0, 0, 0.4))',
+ display: 'flex',
+ paddingRight: 12,
+ paddingLeft: 12,
+ flexDirection: 'column',
+ }}
+ >
+ <div
+ style={{
+ display: 'flex',
+ flexDirection: 'row',
+ width: '100%',
+ alignItems: 'center',
+ }}
+ >
+ <button type="button" onClick={toggle}>
+ {playing ? 'pause' : 'play'}
+ </button>
+ <div style={{width: 10}} />
+ <div
+ style={{
+ color: 'white',
+ fontFamily: 'sans-serif',
+ fontSize: 14,
+ }}
+ >
+ {formatTime(frame / fps)} / {formatTime(durationInFrames / fps)}
+ </div>
+ <div style={{flex: 1}} />
+ </div>
+ <div style={{height: 8}} />
+ <div
+ ref={sliderAreaRef}
+ onPointerDown={onPointerDown}
+ onPointerUp={onPointerUp}
+ style={{paddingTop: 4, paddingBottom: 4, cursor: 'pointer'}}
+ >
+ <div
+ style={{
+ height: 5,
+ backgroundColor: 'rgba(255, 255, 255, 0.5)',
+ width: '100%',
+ borderRadius: 3,
+ }}
+ >
+ <div
+ style={{
+ height: 5,
+ backgroundColor: 'rgba(255, 255, 255, 1)',
+ width: (frame / durationInFrames) * 100 + '%',
+ borderRadius: 3,
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/player/src/RootComponent.tsx b/packages/player/src/RootComponent.tsx
index 45431a4f34..0e89dda2fd 100644
--- a/packages/player/src/RootComponent.tsx
+++ b/packages/player/src/RootComponent.tsx
@@ -1,46 +1,44 @@
-import React, {Suspense} from 'react';
+import React, {Suspense, useMemo} from 'react';
import {Internals} from 'remotion';
-import {usePlaybackTime} from './PlayPause';
+import {Controls} from './PlayerControls';
const RootComponent: React.FC<{
controls: boolean;
style?: Omit<React.CSSProperties, 'width' | 'height'>;
}> = ({controls, style}) => {
const config = Internals.useUnsafeVideoConfig();
- const [toggle] = usePlaybackTime();
- const [playing] = Internals.Timeline.usePlayingState();
const video = Internals.useVideo();
const VideoComponent = video ? video.component : null;
+ const containerStyle: React.CSSProperties = useMemo(() => {
+ if (!config) {
+ return {};
+ }
+ return {
+ position: 'relative',
+ width: config.width,
+ height: config.height,
+ overflow: 'hidden',
+ ...style,
+ };
+ }, [config, style]);
+
+ if (!config) {
+ return null;
+ }
+
return (
<Suspense fallback={<h1>Loading...</h1>}>
- <div
- style={{
- position: 'relative',
- width: config?.width,
- height: config?.height,
- overflow: 'hidden',
- ...style,
- }}
- >
- {controls ? (
- <button
- type="button"
- style={{
- position: 'absolute',
- left: '50%',
- bottom: '10px',
- zIndex: 100,
- transform: 'translateX(-50%)',
- }}
- onClick={toggle}
- >
- {playing ? 'pause' : 'play'}
- </button>
- ) : null}
+ <div style={containerStyle}>
{VideoComponent ? (
<VideoComponent {...(((video?.props as unknown) as {}) ?? {})} />
) : null}
+ {controls ? (
+ <Controls
+ fps={config.fps}
+ durationInFrames={config.durationInFrames}
+ />
+ ) : null}
</div>
</Suspense>
);
diff --git a/packages/player/src/format-time.ts b/packages/player/src/format-time.ts
new file mode 100644
index 0000000000..68f1f23e81
--- /dev/null
+++ b/packages/player/src/format-time.ts
@@ -0,0 +1,5 @@
+export const formatTime = (timeInSeconds: number) => {
+ const minutes = Math.floor(timeInSeconds / 60);
+ const seconds = Math.floor(timeInSeconds - minutes * 60);
+ return `${String(minutes)}:${String(seconds).padStart(2, '0')}`;
+};
diff --git a/packages/player/src/types.d.ts b/packages/player/src/types.d.ts
new file mode 100644
index 0000000000..f2da914d4a
--- /dev/null
+++ b/packages/player/src/types.d.ts
@@ -0,0 +1,242 @@
+/**
+ * The **ResizeObserver** interface reports changes to the dimensions of an
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element)'s content
+ * or border box, or the bounding box of an
+ * [SVGElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement).
+ *
+ * > **Note**: The content box is the box in which content can be placed,
+ * > meaning the border box minus the padding and border width. The border box
+ * > encompasses the content, padding, and border. See
+ * > [The box model](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model)
+ * > for further explanation.
+ *
+ * `ResizeObserver` avoids infinite callback loops and cyclic dependencies that
+ * are often created when resizing via a callback function. It does this by only
+ * processing elements deeper in the DOM in subsequent frames. Implementations
+ * should, if they follow the specification, invoke resize events before paint
+ * and after layout.
+ *
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
+ */
+declare class ResizeObserver {
+ /**
+ * The **ResizeObserver** constructor creates a new `ResizeObserver` object,
+ * which can be used to report changes to the content or border box of an
+ * `Element` or the bounding box of an `SVGElement`.
+ *
+ * @example
+ * var ResizeObserver = new ResizeObserver(callback)
+ *
+ * @param callback
+ * The function called whenever an observed resize occurs. The function is
+ * called with two parameters:
+ * * **entries**
+ * An array of
+ * [ResizeObserverEntry](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry)
+ * objects that can be used to access the new dimensions of the element
+ * after each change.
+ * * **observer**
+ * A reference to the `ResizeObserver` itself, so it will definitely be
+ * accessible from inside the callback, should you need it. This could be
+ * used for example to automatically unobserve the observer when a certain
+ * condition is reached, but you can omit it if you don't need it.
+ *
+ * The callback will generally follow a pattern along the lines of:
+ * ```js
+ * function(entries, observer) {
+ * for (let entry of entries) {
+ * // Do something to each entry
+ * // and possibly something to the observer itself
+ * }
+ * }
+ * ```
+ *
+ * The following snippet is taken from the
+ * [resize-observer-text.html](https://mdn.github.io/dom-examples/resize-observer/resize-observer-text.html)
+ * ([see source](https://github.com/mdn/dom-examples/blob/master/resize-observer/resize-observer-text.html))
+ * example:
+ * @example
+ * const resizeObserver = new ResizeObserver(entries => {
+ * for (let entry of entries) {
+ * if(entry.contentBoxSize) {
+ * h1Elem.style.fontSize = Math.max(1.5, entry.contentBoxSize.inlineSize/200) + 'rem';
+ * pElem.style.fontSize = Math.max(1, entry.contentBoxSize.inlineSize/600) + 'rem';
+ * } else {
+ * h1Elem.style.fontSize = Math.max(1.5, entry.contentRect.width/200) + 'rem';
+ * pElem.style.fontSize = Math.max(1, entry.contentRect.width/600) + 'rem';
+ * }
+ * }
+ * });
+ *
+ * resizeObserver.observe(divElem);
+ */
+ constructor(callback: ResizeObserverCallback);
+
+ /**
+ * The **disconnect()** method of the
+ * [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)
+ * interface unobserves all observed
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) or
+ * [SVGElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement)
+ * targets.
+ */
+ disconnect: () => void;
+
+ /**
+ * The `observe()` method of the
+ * [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)
+ * interface starts observing the specified
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) or
+ * [SVGElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement).
+ *
+ * @example
+ * resizeObserver.observe(target, options);
+ *
+ * @param target
+ * A reference to an
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) or
+ * [SVGElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement)
+ * to be observed.
+ *
+ * @param options
+ * An options object allowing you to set options for the observation.
+ * Currently this only has one possible option that can be set.
+ */
+ observe: (target: Element, options?: ResizeObserverObserveOptions) => void;
+
+ /**
+ * The **unobserve()** method of the
+ * [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver)
+ * interface ends the observing of a specified
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) or
+ * [SVGElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement).
+ */
+ unobserve: (target: Element) => void;
+}
+
+interface ResizeObserverObserveOptions {
+ /**
+ * Sets which box model the observer will observe changes to. Possible values
+ * are `content-box` (the default), and `border-box`.
+ *
+ * @default "content-box"
+ */
+ box?: 'content-box' | 'border-box';
+}
+
+/**
+ * The function called whenever an observed resize occurs. The function is
+ * called with two parameters:
+ *
+ * @param entries
+ * An array of
+ * [ResizeObserverEntry](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry)
+ * objects that can be used to access the new dimensions of the element after
+ * each change.
+ *
+ * @param observer
+ * A reference to the `ResizeObserver` itself, so it will definitely be
+ * accessible from inside the callback, should you need it. This could be used
+ * for example to automatically unobserve the observer when a certain condition
+ * is reached, but you can omit it if you don't need it.
+ *
+ * The callback will generally follow a pattern along the lines of:
+ * @example
+ * function(entries, observer) {
+ * for (let entry of entries) {
+ * // Do something to each entry
+ * // and possibly something to the observer itself
+ * }
+ * }
+ *
+ * @example
+ * const resizeObserver = new ResizeObserver(entries => {
+ * for (let entry of entries) {
+ * if(entry.contentBoxSize) {
+ * h1Elem.style.fontSize = Math.max(1.5, entry.contentBoxSize.inlineSize/200) + 'rem';
+ * pElem.style.fontSize = Math.max(1, entry.contentBoxSize.inlineSize/600) + 'rem';
+ * } else {
+ * h1Elem.style.fontSize = Math.max(1.5, entry.contentRect.width/200) + 'rem';
+ * pElem.style.fontSize = Math.max(1, entry.contentRect.width/600) + 'rem';
+ * }
+ * }
+ * });
+ *
+ * resizeObserver.observe(divElem);
+ */
+type ResizeObserverCallback = (
+ entries: ResizeObserverEntry[],
+ observer: ResizeObserver
+) => void;
+
+/**
+ * The **ResizeObserverEntry** interface represents the object passed to the
+ * [ResizeObserver()](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver/ResizeObserver)
+ * constructor's callback function, which allows you to access the new
+ * dimensions of the
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) or
+ * [SVGElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement)
+ * being observed.
+ */
+interface ResizeObserverEntry {
+ /**
+ * An object containing the new border box size of the observed element when
+ * the callback is run.
+ */
+ readonly borderBoxSize: ResizeObserverEntryBoxSize;
+
+ /**
+ * An object containing the new content box size of the observed element when
+ * the callback is run.
+ */
+ readonly contentBoxSize: ResizeObserverEntryBoxSize;
+
+ /**
+ * A [DOMRectReadOnly](https://developer.mozilla.org/en-US/docs/Web/API/DOMRectReadOnly)
+ * object containing the new size of the observed element when the callback is
+ * run. Note that this is better supported than the above two properties, but
+ * it is left over from an earlier implementation of the Resize Observer API,
+ * is still included in the spec for web compat reasons, and may be deprecated
+ * in future versions.
+ */
+ // node_modules/typescript/lib/lib.dom.d.ts
+ readonly contentRect: DOMRectReadOnly;
+
+ /**
+ * A reference to the
+ * [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element) or
+ * [SVGElement](https://developer.mozilla.org/en-US/docs/Web/API/SVGElement)
+ * being observed.
+ */
+ readonly target: Element;
+}
+
+/**
+ * The **borderBoxSize** read-only property of the
+ * [ResizeObserverEntry](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry)
+ * interface returns an object containing the new border box size of the
+ * observed element when the callback is run.
+ */
+interface ResizeObserverEntryBoxSize {
+ /**
+ * The length of the observed element's border box in the block dimension. For
+ * boxes with a horizontal
+ * [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode),
+ * this is the vertical dimension, or height; if the writing-mode is vertical,
+ * this is the horizontal dimension, or width.
+ */
+ blockSize: number;
+
+ /**
+ * The length of the observed element's border box in the inline dimension.
+ * For boxes with a horizontal
+ * [writing-mode](https://developer.mozilla.org/en-US/docs/Web/CSS/writing-mode),
+ * this is the horizontal dimension, or width; if the writing-mode is
+ * vertical, this is the vertical dimension, or height.
+ */
+ inlineSize: number;
+}
+
+interface Window {
+ ResizeObserver: typeof ResizeObserver;
+}
diff --git a/packages/player/src/use-element-size.ts b/packages/player/src/use-element-size.ts
new file mode 100644
index 0000000000..94bce8225b
--- /dev/null
+++ b/packages/player/src/use-element-size.ts
@@ -0,0 +1,57 @@
+import {useCallback, useEffect, useMemo, useState} from 'react';
+
+export type Size = {
+ width: number;
+ height: number;
+ left: number;
+ top: number;
+};
+
+export const useElementSize = (
+ ref: React.RefObject<HTMLDivElement>
+): Size | null => {
+ const [size, setSize] = useState<Size | null>(null);
+ const observer = useMemo(
+ () =>
+ new ResizeObserver((entries) => {
+ const newSize = entries[0].target.getClientRects();
+ setSize({
+ width: newSize[0].width,
+ height: newSize[0].height,
+ left: newSize[0].x,
+ top: newSize[0].y,
+ });
+ }),
+ []
+ );
+ const updateSize = useCallback(() => {
+ if (!ref.current) {
+ return;
+ }
+ const rect = ref.current.getClientRects();
+ console.log(rect, ref.current);
+ if (!rect[0]) {
+ return;
+ }
+ setSize({
+ width: rect[0].width as number,
+ height: rect[0].height as number,
+ left: rect[0].x as number,
+ top: rect[0].y as number,
+ });
+ }, [ref]);
+
+ useEffect(() => {
+ updateSize();
+ const {current} = ref;
+ if (ref.current) {
+ observer.observe(ref.current);
+ }
+ return (): void => {
+ if (current) {
+ observer.unobserve(current);
+ }
+ };
+ }, [observer, ref, updateSize]);
+ return size;
+};