embed element youtube video

This commit is contained in:
Yisroel Baum 2026-05-27 20:43:23 +03:00
parent c48312de00
commit 5f89db8028
Signed by: yisroelbaum
GPG key ID: 0FA60884F75520A9
2 changed files with 194 additions and 0 deletions

View file

@ -10,6 +10,7 @@ export interface ChildElement {
export interface Element extends ChildElement {
richText: string
pdfPath: string | null
youtubeUrl: string | null
}
interface ElementResponse {

View file

@ -5,10 +5,22 @@ import { useRoute } from 'vue-router'
import SiteHeader from '@/components/SiteHeader.vue'
import { useElementsStore } from '@/stores/elements'
type TimestampPart = string | undefined
const route = useRoute()
const elementsStore = useElementsStore()
const { element, childElements, isLoading, error } = storeToRefs(elementsStore)
const youtubeIframeAllow = [
'accelerometer',
'autoplay',
'clipboard-write',
'encrypted-media',
'gyroscope',
'picture-in-picture',
'web-share',
].join('; ')
const elementId = computed(() => {
const routeElementId = route.params.id
@ -19,6 +31,12 @@ const elementId = computed(() => {
return routeElementId
})
const youtubeEmbedUrl = computed(() => {
const youtubeUrl = element.value?.youtubeUrl ?? null
return getYoutubeEmbedUrl(youtubeUrl)
})
watch(
elementId,
(currentElementId) => {
@ -30,6 +48,154 @@ watch(
},
{ immediate: true },
)
function getYoutubeEmbedUrl(youtubeUrl: string | null): string | null {
if (youtubeUrl === null || youtubeUrl === '') {
return null
}
let parsedUrl: URL
try {
parsedUrl = new URL(youtubeUrl)
} catch {
return null
}
const videoId = getYoutubeVideoId(parsedUrl)
if (videoId === null) {
return null
}
const embedUrl = new URL(`https://www.youtube.com/embed/${videoId}`)
const startSeconds = getYoutubeStartSeconds(parsedUrl)
if (startSeconds !== null) {
embedUrl.searchParams.set('start', startSeconds.toString())
}
return embedUrl.toString()
}
function getYoutubeVideoId(parsedUrl: URL): string | null {
if (isShortYoutubeHost(parsedUrl.hostname)) {
return normalizeYoutubeVideoId(getFirstPathSegment(parsedUrl))
}
if (!isYoutubeHost(parsedUrl.hostname)) {
return null
}
if (parsedUrl.pathname === '/watch') {
return normalizeYoutubeVideoId(parsedUrl.searchParams.get('v'))
}
if (parsedUrl.pathname.startsWith('/embed/')) {
return normalizeYoutubeVideoId(getPathSegment(parsedUrl, 1))
}
return null
}
function getYoutubeStartSeconds(parsedUrl: URL): number | null {
const startParam = parsedUrl.searchParams.get('start')
if (startParam !== null) {
return getPositiveSeconds(startParam)
}
const timestampParam = parsedUrl.searchParams.get('t')
if (timestampParam === null) {
return null
}
return getTimestampSeconds(timestampParam)
}
function getTimestampSeconds(timestampParam: string): number | null {
if (/^\d+$/.test(timestampParam)) {
return getPositiveSeconds(timestampParam)
}
const hourRegex = '^(?:(\\d+)h)?'
const minuteRegex = '(?:(\\d+)m)?'
const secondRegex = '(?:(\\d+)s)?$'
const fullTimestampRegex = hourRegex + minuteRegex + secondRegex
const timestampPattern = new RegExp(fullTimestampRegex)
const timestampMatch = timestampParam.match(timestampPattern)
if (timestampMatch === null) {
return null
}
const hours = getTimestampHours(timestampMatch[1])
const minutes = getTimestampMinutes(timestampMatch[2])
const seconds = getTimestampSecondsPart(timestampMatch[3])
const totalSeconds = hours + minutes + seconds
return totalSeconds > 0 ? totalSeconds : null
}
function getTimestampHours(timestampPart: TimestampPart): number {
return getPartSeconds(timestampPart, 3600)
}
function getTimestampMinutes(timestampPart: TimestampPart): number {
return getPartSeconds(timestampPart, 60)
}
function getTimestampSecondsPart(timestampPart: TimestampPart): number {
return getPartSeconds(timestampPart, 1)
}
function getPartSeconds(timestamp: TimestampPart, multiplier: number): number {
if (timestamp === undefined) {
return 0
}
return Number(timestamp) * multiplier
}
function getPositiveSeconds(secondsParam: string): number | null {
const seconds = Number(secondsParam)
if (!Number.isInteger(seconds) || seconds < 0) {
return null
}
return seconds
}
function getFirstPathSegment(parsedUrl: URL): string | null {
return getPathSegment(parsedUrl, 0)
}
function getPathSegment(parsedUrl: URL, segmentIndex: number): string | null {
const pathSegments = parsedUrl.pathname.split('/').filter((pathSegment) => {
return pathSegment !== ''
})
return pathSegments[segmentIndex] ?? null
}
function normalizeYoutubeVideoId(videoId: string | null): string | null {
if (videoId === null || videoId === '') {
return null
}
if (!/^[A-Za-z0-9_-]+$/.test(videoId)) {
return null
}
return videoId
}
function isYoutubeHost(hostname: string): boolean {
const normalizedHostname = hostname.toLowerCase()
const isRootYoutubeHost = normalizedHostname === 'youtube.com'
const isYoutubeSubdomain = normalizedHostname.endsWith('.youtube.com')
return isRootYoutubeHost || isYoutubeSubdomain
}
function isShortYoutubeHost(hostname: string): boolean {
return hostname.toLowerCase() === 'youtu.be'
}
</script>
<template>
@ -56,6 +222,18 @@ watch(
v-html="element.richText"
/>
<div v-if="youtubeEmbedUrl !== null" class="element-page__youtube">
<iframe
:src="youtubeEmbedUrl"
:allow="youtubeIframeAllow"
class="element-page__youtube-iframe"
data-cy="element-youtube-embed"
title="YouTube video player"
loading="lazy"
allowfullscreen
/>
</div>
<div v-if="element.pdfPath !== null" class="element-page__actions">
<a
:href="element.pdfPath"
@ -149,6 +327,21 @@ watch(
font-weight: 700;
}
.element-page__youtube {
aspect-ratio: 16 / 9;
margin-top: 1.75rem;
overflow: hidden;
background: #000000;
border-radius: 8px;
}
.element-page__youtube-iframe {
display: block;
width: 100%;
height: 100%;
border: 0;
}
.element-page__actions {
display: flex;
justify-content: center;