/** * (c) 2026, Micro:bit Educational Foundation and contributors * * SPDX-License-Identifier: MIT */ import { AspectRatio, Icon } from "@microbit/ui"; import { useEffect, useRef, useState } from "react"; import { RiPlayFill } from "react-icons/ri"; import { useIntl } from "react-intl"; import { css } from "styled-system/css"; import { uiPatternsMessage } from "./messages"; export interface YoutubeVideoEmbedProps { /** YouTube video id. */ youtubeId: string; /** * Video title. Names the play button ("Play video: {title}") and the * player iframe. */ title: string; /** * Alt text for the preview image, for a description beyond the play * button's title. Defaults to decorative. */ alt?: string; } /** * WebKit doesn't carry a tap's user activation into a cross-origin iframe * created afterwards, and ignores autoplay=1 without one — so on iOS the * facade would cost a second tap, on the loaded player's own play button. * iPadOS reports the platform as macOS, hence the touch-points check. */ const isIOS = () => typeof navigator !== "undefined" && /iP(hone|ad|od)|Mac/.test(navigator.platform) && navigator.maxTouchPoints > 1; /** * A YouTube video as a click-to-play facade: the video's own preview image * (from YouTube's cookieless image CDN) behind a play button, swapped for the * privacy-enhanced youtube-nocookie player on activation. * * The player only exists after a deliberate click, so no YouTube script runs * on page load — and, inside a modal, keyboard users aren't tabbed into an * embedded document just to get past the video. * * On iOS the player renders upfront instead — WebKit won't autoplay the * swapped-in iframe (see isIOS), so the facade would demand two taps there. * If we revisit this we should change the facade UX to a consent interaction. */ export const YoutubeVideoEmbed = ({ youtubeId, title, alt, }: YoutubeVideoEmbedProps) => { const intl = useIntl(); const id = encodeURIComponent(youtubeId.trim()); const [activated, setActivated] = useState(false); const showPlayer = activated || isIOS(); // maxresdefault only exists for videos uploaded in ≥720p; fall back to // hqdefault, which YouTube generates for everything. const [thumbnail, setThumbnail] = useState<"maxresdefault" | "hqdefault">( "maxresdefault", ); const iframeRef = useRef(null); useEffect(() => { if (activated) { // rAF, not a direct call: Firefox drops a synchronous focus() of a // cross-origin iframe made while a UI event is being dispatched. const raf = requestAnimationFrame(() => iframeRef.current?.focus()); return () => cancelAnimationFrame(raf); } }, [activated]); return ( {showPlayer ? (