Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

fix: Rewrite Vimeo component to fix a bug and make logic readable (#3177)

Oleg Isonen1cbb1853f210
diff --git a/packages/sdk-components-react/package.json b/packages/sdk-components-react/package.json
index 50d96c4a51..c91aec9077 100644
--- a/packages/sdk-components-react/package.json
+++ b/packages/sdk-components-react/package.json
@@ -52,8 +52,7 @@
"@webstudio-is/icons": "workspace:*",
"@webstudio-is/image": "workspace:*",
"@webstudio-is/react-sdk": "workspace:*",
- "colord": "^2.9.3",
- "shallow-equal": "^3.1.0"
+ "colord": "^2.9.3"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
diff --git a/packages/sdk-components-react/src/vimeo-play-button.tsx b/packages/sdk-components-react/src/vimeo-play-button.tsx
index 76a226a5c7..e12e440b09 100644
--- a/packages/sdk-components-react/src/vimeo-play-button.tsx
+++ b/packages/sdk-components-react/src/vimeo-play-button.tsx
@@ -15,7 +15,7 @@ export const VimeoPlayButton = forwardRef<ElementRef<typeof defaultTag>, Props>(
(props, ref) => {
const vimeoContext = useContext(VimeoContext);
if (vimeoContext.status !== "initial") {
- return null;
+ return;
}
return <Button {...props} onClick={vimeoContext.onInitPlayer} ref={ref} />;
}
diff --git a/packages/sdk-components-react/src/vimeo-spinner.tsx b/packages/sdk-components-react/src/vimeo-spinner.tsx
index 3385cc8ad0..28d470573f 100644
--- a/packages/sdk-components-react/src/vimeo-spinner.tsx
+++ b/packages/sdk-components-react/src/vimeo-spinner.tsx
@@ -14,8 +14,8 @@ export const VimeoSpinner = forwardRef<ElementRef<typeof defaultTag>, Props>(
(props, ref) => {
const vimeoContext = useContext(VimeoContext);
- if (vimeoContext.status !== "initialized") {
- return null;
+ if (vimeoContext.status !== "loading") {
+ return;
}
return <div {...props} ref={ref} />;
diff --git a/packages/sdk-components-react/src/vimeo.tsx b/packages/sdk-components-react/src/vimeo.tsx
index f13d5efcda..8328e07758 100644
--- a/packages/sdk-components-react/src/vimeo.tsx
+++ b/packages/sdk-components-react/src/vimeo.tsx
@@ -8,20 +8,14 @@ import { colord } from "colord";
import {
forwardRef,
useState,
- useRef,
useEffect,
type ElementRef,
type ComponentProps,
useContext,
createContext,
type ContextType,
- useMemo,
- useCallback,
} from "react";
import { ReactSdkContext } from "@webstudio-is/react-sdk";
-import { shallowEqual } from "shallow-equal";
-
-const defaultTag = "div";
// https://developer.vimeo.com/player/sdk/embed
type VimeoPlayerOptions = {
@@ -68,7 +62,7 @@ type VimeoPlayerOptions = {
transparent?: boolean;
};
-const getUrl = (options: VimeoPlayerOptions) => {
+const getVideoUrl = (options: VimeoOptions) => {
if (options.url === undefined) {
return;
}
@@ -84,30 +78,43 @@ const getUrl = (options: VimeoPlayerOptions) => {
return;
}
- let option: keyof VimeoPlayerOptions;
+ const optionsMap = {
+ showPortrait: "portrait",
+ showByline: "byline",
+ showTitle: "title",
+ controlsColor: "color",
+ showControls: "controls",
+ interactiveParams: "interactive_params",
+ backgroundMode: "background",
+ doNotTrack: "dnt",
+ } as const;
+
+ let option: keyof VimeoOptions;
for (option in options) {
const value = options[option];
if (option === "url" || value === undefined) {
continue;
}
- url.searchParams.append(option, value.toString());
+ const mappedOption =
+ optionsMap[option as keyof typeof optionsMap] ?? option;
+ url.searchParams.append(mappedOption, value.toString());
}
- // We always set autoplay to true because we have a button that starts the video
+ // We always set autoplay to true because we render the iframe only after user hits Webstudio play button.
url.searchParams.set("autoplay", "true");
// Vimeo needs a hex color value without the hash
- if (typeof options.color === "string") {
- const color = colord(options.color).toHex().replace("#", "");
+ if (typeof options.controlsColor === "string") {
+ const color = colord(options.controlsColor).toHex().replace("#", "");
url.searchParams.set("color", color);
}
// Portrait option won't work if at title is not set to true
- if (options.portrait) {
+ if (options.showPortrait) {
url.searchParams.set("title", "true");
}
// Byline won't show up if portrait and title is not set to true
- if (options.byline) {
+ if (options.showByline) {
url.searchParams.set("portrait", "true");
url.searchParams.set("title", "true");
}
@@ -148,52 +155,10 @@ const warmConnections = () => {
warmed = true;
};
-const createPlayer = (
- parent: Element,
- vimeoOptions: VimeoPlayerOptions,
- extendedOptions: { loading: VimeoOptions["loading"] },
- callback: () => void
-) => {
- const url = getUrl(vimeoOptions);
- if (url === undefined) {
- return;
- }
- const iframe = document.createElement("iframe");
- iframe.setAttribute(
- "allow",
- "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture;"
- );
- iframe.setAttribute("frameborder", "0");
- iframe.setAttribute("allowfullscreen", "true");
- iframe.setAttribute("src", url);
- iframe.setAttribute(
- "style",
- "position: absolute; width: 100%; height: 100%; opacity: 0; transition: opacity 1s;"
- );
- if (extendedOptions.loading) {
- iframe.setAttribute("loading", extendedOptions.loading);
- }
-
- // Show iframe only once it's loaded to avoid weird flashes.
- iframe.addEventListener(
- "load",
- () => {
- iframe.style.opacity = "1";
- callback();
- },
- { once: true }
- );
- parent.appendChild(iframe);
-
- return () => {
- iframe.parentElement?.removeChild(iframe);
- };
-};
-
const getVideoId = (url: string) => {
try {
const parsedUrl = new URL(url);
- const id = parsedUrl.pathname.split("/")[1];
+ const id = parsedUrl.pathname.split("/")[2];
if (id === "" || id == null) {
return;
}
@@ -202,7 +167,7 @@ const getVideoId = (url: string) => {
} catch {}
};
-const loadPreviewImage = async (element: HTMLElement, videoUrl: string) => {
+const loadPreviewImageUrl = async (videoUrl: string) => {
const videoId = getVideoId(videoUrl);
// API is the video-id based
// http://vimeo.com/api/v2/video/364402896.json
@@ -225,97 +190,6 @@ const loadPreviewImage = async (element: HTMLElement, videoUrl: string) => {
return imageUrl;
};
-type PlayerStatus = "initial" | "initialized" | "ready";
-
-const useVimeo = ({
- options,
- renderer,
- showPreview,
- loading,
-}: {
- options: VimeoPlayerOptions;
- showPreview?: boolean;
- loading: VimeoOptions["loading"];
- renderer: ContextType<typeof ReactSdkContext>["renderer"];
-}) => {
- const [playerStatus, setPlayerStatus] = useState<PlayerStatus>("initial");
- const elementRef = useRef<ElementRef<typeof defaultTag> | null>(null);
- const [previewImageUrl, setPreviewImageUrl] = useState<URL>();
- const [isPending, setIsPending] = useState(false);
- const loadPreviewOnceRef = useRef(false);
-
- useEffect(() => {
- setPlayerStatus(
- options.autoplay && renderer !== "canvas" ? "initialized" : "initial"
- );
- }, [options.autoplay, renderer]);
-
- useEffect(() => {
- if (
- elementRef.current === null ||
- playerStatus === "ready" ||
- options.url === undefined
- ) {
- return;
- }
-
- if (showPreview) {
- if (loadPreviewOnceRef.current) {
- return;
- }
-
- loadPreviewOnceRef.current = true;
-
- loadPreviewImage(elementRef.current, options.url)
- .then(setPreviewImageUrl)
- .catch(() => {
- /* DO NOTHING */
- });
- return;
- }
- setPreviewImageUrl(undefined);
- }, [renderer, showPreview, options.url, playerStatus]);
-
- const optionsRef = useRef(options);
- const stableOptions = useMemo(() => {
- if (shallowEqual(options, optionsRef.current) === false) {
- optionsRef.current = options;
- }
- return optionsRef.current;
- }, [options]);
-
- useEffect(() => {
- if (isPending) {
- setPlayerStatus((status) =>
- status === "initial" ? "initialized" : status
- );
- }
- }, [isPending]);
-
- const toggleCreatePlayer = playerStatus !== "initial";
-
- useEffect(() => {
- if (elementRef.current === null) {
- return;
- }
- if (toggleCreatePlayer === false) {
- return;
- }
-
- return createPlayer(elementRef.current, stableOptions, { loading }, () => {
- setPlayerStatus("ready");
- });
- }, [stableOptions, toggleCreatePlayer, loading]);
-
- const start = useCallback(() => {
- setIsPending(true);
- }, []);
-
- const status = isPending ? "initialized" : playerStatus;
-
- return { previewImageUrl, status, start, elementRef };
-};
-
export type VimeoOptions = Omit<
VimeoPlayerOptions,
| "dnt"
@@ -350,6 +224,121 @@ export type VimeoOptions = Omit<
showPortrait?: VimeoPlayerOptions["portrait"];
};
+const EmptyState = () => {
+ return (
+ <div
+ style={{
+ display: "flex",
+ width: "100%",
+ height: "100%",
+ alignItems: "center",
+ justifyContent: "center",
+ fontSize: "1.2em",
+ }}
+ >
+ {
+ 'Open the "Settings" panel and paste a video URL, e.g. https://vimeo.com/831343124.'
+ }
+ </div>
+ );
+};
+
+type PlayerStatus = "initial" | "loading" | "ready";
+
+type PlayerProps = Pick<
+ VimeoOptions,
+ "loading" | "autoplay" | "showPreview"
+> & {
+ videoUrl: string;
+ status: PlayerStatus;
+ renderer: ContextType<typeof ReactSdkContext>["renderer"];
+ previewImageUrl?: URL;
+ onStatusChange: (status: PlayerStatus) => void;
+ onPreviewImageUrlChange: (url?: URL) => void;
+};
+
+const Player = ({
+ status,
+ loading,
+ videoUrl,
+ previewImageUrl,
+ autoplay,
+ renderer,
+ showPreview,
+ onStatusChange,
+ onPreviewImageUrlChange,
+}: PlayerProps) => {
+ const [opacity, setOpacity] = useState(0);
+
+ useEffect(() => {
+ if (autoplay && renderer !== "canvas" && status === "initial") {
+ onStatusChange("loading");
+ }
+ }, [autoplay, status, renderer, onStatusChange]);
+
+ useEffect(() => {
+ if (renderer !== "canvas") {
+ warmConnections();
+ }
+ }, [renderer]);
+
+ useEffect(() => {
+ if (videoUrl === undefined) {
+ return;
+ }
+
+ if (showPreview === false) {
+ onPreviewImageUrlChange(undefined);
+ return;
+ }
+
+ if (previewImageUrl === undefined) {
+ loadPreviewImageUrl(videoUrl)
+ .then(onPreviewImageUrlChange)
+ .catch(() => {
+ console.error(`Could not load preview image for ${videoUrl}`);
+ });
+ }
+ }, [onPreviewImageUrlChange, showPreview, videoUrl, previewImageUrl]);
+
+ if (renderer === "canvas" || status === "initial") {
+ return;
+ }
+
+ return (
+ <iframe
+ src={videoUrl}
+ loading={loading}
+ allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture;"
+ allowFullScreen
+ style={{
+ position: "absolute",
+ width: "100%",
+ height: "100%",
+ opacity,
+ transition: "opacity 1s",
+ border: "none",
+ }}
+ onLoad={() => {
+ onStatusChange("ready");
+ setOpacity(1);
+ }}
+ />
+ );
+};
+
+export const VimeoContext = createContext<{
+ previewImageUrl?: URL;
+ onInitPlayer: () => void;
+ status: PlayerStatus;
+}>({
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
+ onInitPlayer: () => {},
+ status: "initial",
+});
+
+const defaultTag = "div";
+
type Props = Omit<ComponentProps<typeof defaultTag>, keyof VimeoOptions> &
VimeoOptions;
type Ref = ElementRef<typeof defaultTag>;
@@ -386,33 +375,31 @@ export const Vimeo = forwardRef<Ref, Props>(
},
ref
) => {
+ const [status, setStatus] = useState<PlayerStatus>("initial");
+ const [previewImageUrl, setPreviewImageUrl] = useState<URL>();
const { renderer } = useContext(ReactSdkContext);
- const { previewImageUrl, status, start, elementRef } = useVimeo({
- renderer,
- showPreview,
- loading,
- options: {
- url,
- autoplay,
- autopause,
- keyboard,
- loop,
- muted,
- pip,
- playsinline,
- quality,
- responsive,
- speed,
- transparent,
- portrait: showPortrait,
- byline: showByline,
- title: showTitle,
- color: controlsColor,
- controls: showControls,
- interactive_params: interactiveParams,
- background: backgroundMode,
- dnt: doNotTrack,
- },
+ const videoUrl = getVideoUrl({
+ url,
+ autoplay,
+ autopause,
+ backgroundMode,
+ showControls,
+ controlsColor,
+ doNotTrack,
+ interactiveParams,
+ keyboard,
+ loop,
+ muted,
+ pip,
+ playsinline,
+ quality,
+ responsive,
+ speed,
+ texttrack,
+ showTitle,
+ transparent,
+ showPortrait,
+ autopip,
});
return (
@@ -422,7 +409,7 @@ export const Vimeo = forwardRef<Ref, Props>(
previewImageUrl,
onInitPlayer() {
if (renderer !== "canvas") {
- start();
+ setStatus("loading");
}
},
}}
@@ -430,18 +417,29 @@ export const Vimeo = forwardRef<Ref, Props>(
<div
{...rest}
ref={(value: Ref) => {
- elementRef.current = value;
if (ref !== null) {
typeof ref === "function" ? ref(value) : (ref.current = value);
}
}}
- onPointerOver={() => {
- if (renderer !== "canvas") {
- warmConnections();
- }
- }}
>
- {url === undefined ? <EmptyState /> : children}
+ {videoUrl === undefined ? (
+ <EmptyState />
+ ) : (
+ <>
+ {children}
+ <Player
+ autoplay={autoplay}
+ videoUrl={videoUrl}
+ previewImageUrl={previewImageUrl}
+ loading={loading}
+ showPreview={showPreview}
+ renderer={renderer}
+ status={status}
+ onStatusChange={setStatus}
+ onPreviewImageUrlChange={setPreviewImageUrl}
+ />
+ </>
+ )}
</div>
</VimeoContext.Provider>
);
@@ -449,32 +447,3 @@ export const Vimeo = forwardRef<Ref, Props>(
);
Vimeo.displayName = "Vimeo";
-
-const EmptyState = () => {
- return (
- <div
- style={{
- display: "flex",
- width: "100%",
- height: "100%",
- alignItems: "center",
- justifyContent: "center",
- fontSize: "1.2em",
- }}
- >
- {
- 'Open the "Settings" panel and paste a video URL, e.g. https://vimeo.com/831343124.'
- }
- </div>
- );
-};
-
-export const VimeoContext = createContext<{
- previewImageUrl?: URL;
- onInitPlayer: () => void;
- status: PlayerStatus;
-}>({
- // eslint-disable-next-line @typescript-eslint/no-empty-function
- onInitPlayer: () => {},
- status: "initial",
-});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b0d7f867e8..8b77725136 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1939,9 +1939,6 @@ importers:
colord:
specifier: ^2.9.3
version: 2.9.3
- shallow-equal:
- specifier: ^3.1.0
- version: 3.1.0
devDependencies:
'@jest/globals':
specifier: ^29.7.0