Merged in fix/BOOK-257-video-player (pull request #3373)

Fix/BOOK-257 video player

* fix(BOOK-257): Fixes to VideoPlayerButton and added stories

* fix(BOOK-257): Hiding mute button when the user has interacted with it

* fix(BOOK-257): Added support for poster image

* fix(BOOK-257): add crossOrigin attr to videoplayer

* fix(BOOK-257): comment


Approved-by: Anton Gunnarsson
This commit is contained in:
Erik Tiekstra
2025-12-19 12:41:00 +00:00
committed by Bianca Widstam
parent 3f632e6031
commit c21aa2dc73
15 changed files with 436 additions and 117 deletions

View File

@@ -0,0 +1,95 @@
import type { Meta, StoryObj } from '@storybook/nextjs-vite'
import { fn } from 'storybook/test'
import { VideoPlayerButton } from '.'
import { videoPlayerButtonIconNames } from './types'
import { config } from './variants'
const meta: Meta<typeof VideoPlayerButton> = {
title: 'Core Components/Video/VideoPlayerButton',
component: VideoPlayerButton,
parameters: {
docs: {
description: {
component:
'A component to display a VideoPlayer and content inside a card connected to the video. The size and gaps are determined by the parent container.',
},
},
},
argTypes: {
onPress: {
table: {
type: { summary: 'function' },
},
defaultValue: { summary: 'undefined' },
},
size: {
control: 'select',
options: Object.keys(config.variants.size),
table: {
defaultValue: {
summary: config.defaultVariants.size,
},
type: {
summary: Object.keys(config.variants.size).join(' | '),
},
},
description: 'The size of the button.',
},
iconName: {
control: 'select',
options: videoPlayerButtonIconNames,
table: {
defaultValue: {
summary: 'undefined',
},
type: {
summary: videoPlayerButtonIconNames.join(' | '),
},
},
description:
'This decides the background color and text color of the card.',
},
},
}
export default meta
function renderAllIcons(args: Story['args']) {
return (
<div
style={{
display: 'flex',
gap: '16px',
alignItems: 'center',
justifyContent: 'center',
flexWrap: 'wrap',
}}
>
{videoPlayerButtonIconNames.map((iconName) => (
<VideoPlayerButton key={iconName} {...args} iconName={iconName} />
))}
</div>
)
}
type Story = StoryObj<typeof VideoPlayerButton>
export const Default: Story = {
args: { iconName: 'play_arrow', onPress: fn() },
}
export const Small: Story = {
args: { ...Default.args, size: 'sm' },
render: (args) => renderAllIcons(args),
}
export const Medium: Story = {
args: { ...Default.args, size: 'md' },
render: (args) => renderAllIcons(args),
}
export const Large: Story = {
args: { ...Default.args, size: 'lg' },
render: (args) => renderAllIcons(args),
}

View File

@@ -2,38 +2,44 @@
import { Button as ButtonRAC } from 'react-aria-components' import { Button as ButtonRAC } from 'react-aria-components'
import { MaterialIcon } from '../../Icons/MaterialIcon' import { MaterialIcon } from '../../Icons/MaterialIcon'
import styles from './button.module.css' import { VideoPlayerButtonProps } from './types'
import { variants } from './variants'
interface VideoPlayerButtonProps { import styles from './videoPlayerButton.module.css'
onPress: () => void
iconName: 'play_arrow' | 'pause' | 'volume_up' | 'volume_off'
ariaLabel: string
className?: string
}
export function VideoPlayerButton({ export function VideoPlayerButton({
onPress,
ariaLabel,
iconName, iconName,
size,
className, className,
...props
}: VideoPlayerButtonProps) { }: VideoPlayerButtonProps) {
const classNames = variants({
size,
className,
})
return ( return (
<div className={className}> <ButtonRAC className={classNames} {...props}>
<ButtonRAC <span className={styles.transparentBackground} />
className={styles.videoPlayerButton} <span className={styles.iconWrapper}>
onPress={onPress} <MaterialIcon
aria-label={ariaLabel} icon={iconName}
> size={getIconSize(size)}
<span className={styles.transparentBackground} /> color="CurrentColor"
<span className={styles.iconWrapper}> isFilled
<MaterialIcon />
icon={iconName} </span>
size={32} </ButtonRAC>
color="CurrentColor"
isFilled
/>
</span>
</ButtonRAC>
</div>
) )
} }
function getIconSize(size: VideoPlayerButtonProps['size']) {
switch (size) {
case 'sm':
return 28
case 'lg':
return 40
case 'md':
default:
return 32
}
}

View File

@@ -0,0 +1,22 @@
import type { VariantProps } from 'class-variance-authority'
import { Button as ButtonRAC } from 'react-aria-components'
import { ComponentProps } from 'react'
import type { SymbolCodepoints } from '../../Icons/MaterialIcon/MaterialSymbol/types'
import type { variants } from './variants'
export const videoPlayerButtonIconNames = [
'play_arrow',
'pause',
'volume_up',
'volume_off',
] satisfies SymbolCodepoints[]
type VideoPlayerButtonIconName = (typeof videoPlayerButtonIconNames)[number]
export interface VideoPlayerButtonProps
extends
Omit<ComponentProps<typeof ButtonRAC>, 'children'>,
VariantProps<typeof variants> {
iconName: VideoPlayerButtonIconName
}

View File

@@ -0,0 +1,18 @@
import { cva } from 'class-variance-authority'
import styles from './videoPlayerButton.module.css'
export const config = {
variants: {
size: {
sm: styles['size-sm'],
md: styles['size-md'],
lg: styles['size-lg'],
},
},
defaultVariants: {
size: 'md',
},
} as const
export const variants = cva(styles.videoPlayerButton, config)

View File

@@ -7,7 +7,6 @@
align-items: center; align-items: center;
justify-content: center; justify-content: center;
position: relative; position: relative;
overflow: hidden;
cursor: pointer; cursor: pointer;
z-index: 0; z-index: 0;
border-width: 0; border-width: 0;
@@ -29,11 +28,45 @@
} }
&:focus-visible { &:focus-visible {
border-width: 2px;
outline: 2px solid var(--Border-Inverted); outline: 2px solid var(--Border-Inverted);
outline-offset: 2px;
.transparentBackground { &::before {
background-color: var(--Base-Border-Subtle); content: '';
position: absolute;
inset: -2px;
border: 2px solid var(--Border-Interactive-Focus);
border-radius: inherit;
pointer-events: none;
}
}
&.size-sm {
height: 52px;
width: 52px;
.iconWrapper {
width: 40px;
height: 40px;
}
}
&.size-md {
height: 56px;
width: 56px;
.iconWrapper {
width: 43px;
height: 43px;
}
}
&.size-lg {
height: 72px;
width: 72px;
.iconWrapper {
width: 56px;
height: 56px;
} }
} }
} }
@@ -54,5 +87,4 @@
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
padding: var(--Space-x05);
} }

View File

@@ -30,6 +30,16 @@ const meta: Meta<typeof VideoPlayer> = {
description: description:
'The different sources of the video, including their formats.', 'The different sources of the video, including their formats.',
}, },
poster: {
table: {
type: {
summary:
'{src: string, dimensions?: { width: number; height: number }}',
},
},
description:
'The poster image to be displayed before playback. Default behavior in iOS is that the first frame of the video is not visible until playback starts, so providing a poster image is recommended for better user experience.',
},
captions: { captions: {
table: { table: {
type: { type: {
@@ -77,17 +87,29 @@ export default meta
type Story = StoryObj<typeof VideoPlayer> type Story = StoryObj<typeof VideoPlayer>
const inlineSources = [
{
src: 'https://eu-assets.contentstack.com/v3/assets/bltfd73aa2de3a5c4e3/bltf1f715c41793a9fb/6943e943ca0c69c3d00bd620/Scandic_EB_Video.mp4',
type: 'video/mp4',
},
]
const heroSources = [
{
src: 'https://eu-assets.contentstack.com/v3/assets/bltfd73aa2de3a5c4e3/bltc3aa53ac9bf6798c/693ad4b65b0889d6348893f3/Test_video.mp4',
type: 'video/mp4',
},
{
src: 'https://eu-assets.contentstack.com/v3/assets/bltfd73aa2de3a5c4e3/blt029be07ddd444eea/693c251c09e17b33c93c1dd6/hero-banner-1920-vp9.webm',
type: 'video/webm',
},
]
const defaultArgs = { const defaultArgs = {
sources: [ sources: inlineSources,
{ poster: {
src: 'https://eu-assets.contentstack.com/v3/assets/bltfd73aa2de3a5c4e3/bltc3aa53ac9bf6798c/693ad4b65b0889d6348893f3/Test_video.mp4', src: 'https://imagevault.scandichotels.com/publishedmedia/dtpv2wgm6jhix2pqpp88/Scandic_Downtown_Camper_restaurang_bar_The_Nest_lounge_eld.jpg',
type: 'video/mp4', },
},
{
src: 'https://eu-assets.contentstack.com/v3/assets/bltfd73aa2de3a5c4e3/blt029be07ddd444eea/693c251c09e17b33c93c1dd6/hero-banner-1920-vp9.webm',
type: 'video/webm',
},
],
captions: [ captions: [
{ {
src: './video/captions_en.vtt', src: './video/captions_en.vtt',
@@ -114,6 +136,7 @@ export const BareHero: Story = {
args: { args: {
...Default.args, ...Default.args,
variant: 'hero', variant: 'hero',
sources: heroSources,
}, },
name: 'Hero (barebones)', name: 'Hero (barebones)',
parameters: { parameters: {

View File

@@ -1,5 +1,6 @@
import type { Meta, StoryObj } from '@storybook/nextjs-vite' import type { Meta, StoryObj } from '@storybook/nextjs-vite'
import { Lang } from '@scandic-hotels/common/constants/language'
import { VideoWithCard } from '.' import { VideoWithCard } from '.'
import { config } from './variants' import { config } from './variants'
@@ -80,7 +81,7 @@ const meta: Meta<typeof VideoWithCard> = {
table: { table: {
type: { type: {
summary: summary:
'{ sources: { src: string; type: string }[]; captions?: Caption[]; focalPoint?: FocalPoint}', '{ sources: { src: string; type: string }[]; poster?: { src: string; dimensions?: { width: number; height: number } }; captions?: Caption[]; focalPoint?: FocalPoint}',
}, },
}, },
description: description:
@@ -104,6 +105,22 @@ const videoProps = {
type: 'video/webm', type: 'video/webm',
}, },
], ],
poster: {
src: 'https://imagevault.scandichotels.com/publishedmedia/dtpv2wgm6jhix2pqpp88/Scandic_Downtown_Camper_restaurang_bar_The_Nest_lounge_eld.jpg',
},
captions: [
{
src: './video/captions_en.vtt',
srcLang: Lang.en,
isDefault: false,
},
{
src: './video/captions_sv.vtt',
srcLang: Lang.sv,
isDefault: false,
},
],
fullHeight: true,
} }
const quoteCardProps = { const quoteCardProps = {

View File

@@ -2,7 +2,8 @@ import { VariantProps } from 'class-variance-authority'
import { Typography } from '../../Typography' import { Typography } from '../../Typography'
import { variants } from './variants' import { variants } from './variants'
import { VideoPlayer, VideoPlayerProps } from '..' import { VideoPlayer } from '..'
import { VideoPlayerProps } from '../types'
import styles from './videoWithCard.module.css' import styles from './videoWithCard.module.css'
interface TextCardProps { interface TextCardProps {
variant: 'text' variant: 'text'

View File

@@ -1,68 +1,59 @@
'use client' 'use client'
import { cx, VariantProps } from 'class-variance-authority' import { cx } from 'class-variance-authority'
import { import { useCallback, useEffect, useRef, useState } from 'react'
useCallback,
useEffect,
useRef,
useState,
VideoHTMLAttributes,
} from 'react'
import { Lang, languages } from '@scandic-hotels/common/constants/language' import { languages } from '@scandic-hotels/common/constants/language'
import { FocalPoint } from '@scandic-hotels/common/utils/imageVault'
import { useIntl } from 'react-intl' import { useIntl } from 'react-intl'
import Image from '../Image'
import { VideoPlayerButton } from './Button' import { VideoPlayerButton } from './Button'
import { VideoPlayerProps } from './types'
import { useVideoDimensions } from './useVideoDimensions'
import { getVideoPropsByVariant } from './utils'
import { variants } from './variants' import { variants } from './variants'
import styles from './videoPlayer.module.css' import styles from './videoPlayer.module.css'
interface Caption {
src: string
srcLang: Lang
isDefault: boolean
}
export interface VideoPlayerProps extends VariantProps<typeof variants> {
sources: {
src: string
type: string
}[]
className?: string
captions?: Caption[]
focalPoint?: FocalPoint
autoPlay?: boolean
hasOverlay?: boolean
}
export function VideoPlayer({ export function VideoPlayer({
sources, sources,
captions, captions,
focalPoint = { x: 50, y: 50 }, focalPoint = { x: 50, y: 50 },
className, className,
variant = 'inline', variant = 'inline',
poster,
autoPlay, autoPlay,
hasOverlay, hasOverlay,
}: VideoPlayerProps) { }: VideoPlayerProps) {
const intl = useIntl() const intl = useIntl()
const videoRef = useRef<HTMLVideoElement>(null) const videoRef = useRef<HTMLVideoElement>(null)
const [isInteractedWith, setIsInteractedWith] = useState(false) const shouldAutoPlay =
const [isPlaying, setIsPlaying] = useState(
(variant === 'hero' && (autoPlay ?? true)) || !!autoPlay (variant === 'hero' && (autoPlay ?? true)) || !!autoPlay
) const [hasManuallyPlayed, setHasManuallyPlayed] = useState(false)
const [hasToggledMute, setHasToggledMute] = useState(false)
const [isPlaying, setIsPlaying] = useState(shouldAutoPlay)
const [isMuted, setIsMuted] = useState(true) const [isMuted, setIsMuted] = useState(true)
const [userPaused, setUserPaused] = useState(false) const [userPaused, setUserPaused] = useState(false)
const [showPoster, setShowPoster] = useState(!shouldAutoPlay)
const {
containerRef,
handleMetadataLoaded,
containerWidth,
hasError,
handleError,
} = useVideoDimensions()
const defaultProps = getVideoPropsByVariant( const defaultProps = getVideoPropsByVariant(
variant, variant,
isInteractedWith, hasManuallyPlayed,
autoPlay shouldAutoPlay
) )
const classNames = variants({ const classNames = variants({
className, className,
variant, variant,
}) })
const showPlayButton = const showPlayButton =
variant === 'hero' || (variant === 'inline' && !isInteractedWith) !hasError &&
const showMuteButton = variant === 'inline' && isInteractedWith (variant === 'hero' || (variant === 'inline' && !hasManuallyPlayed))
const showMuteButton =
!hasError && variant === 'inline' && hasManuallyPlayed && !hasToggledMute
const handleIntersection = useCallback( const handleIntersection = useCallback(
(entries: IntersectionObserverEntry[]) => { (entries: IntersectionObserverEntry[]) => {
@@ -89,7 +80,7 @@ export function VideoPlayer({
videoElement.pause() videoElement.pause()
} }
} else { } else {
setIsInteractedWith(true) setHasManuallyPlayed(true)
videoElement.play() videoElement.play()
} }
} }
@@ -101,6 +92,7 @@ export function VideoPlayer({
const currentlyMuted = videoElement.muted const currentlyMuted = videoElement.muted
videoElement.muted = !currentlyMuted videoElement.muted = !currentlyMuted
setIsMuted(!currentlyMuted) setIsMuted(!currentlyMuted)
setHasToggledMute(true)
} }
} }
@@ -112,6 +104,11 @@ export function VideoPlayer({
} }
} }
function handlePlay() {
setShowPoster(false)
setIsPlaying(true)
}
useEffect(() => { useEffect(() => {
const videoElement = videoRef.current const videoElement = videoRef.current
@@ -143,18 +140,27 @@ export function VideoPlayer({
}) })
return ( return (
<div className={cx(classNames, { [styles.hasOverlay]: hasOverlay })}> <div
ref={containerRef}
className={cx(classNames, {
[styles.hasOverlay]: hasOverlay,
[styles.hasError]: hasError,
})}
>
<video <video
ref={videoRef} ref={videoRef}
className={styles.video} className={styles.video}
style={ style={{
focalPoint objectPosition: focalPoint
? { objectPosition: `${focalPoint.x}% ${focalPoint.y}%` } ? `${focalPoint.x}% ${focalPoint.y}%`
: undefined : undefined,
} }}
onPlay={() => setIsPlaying(true)} onLoadedMetadata={handleMetadataLoaded}
onPlay={handlePlay}
onPause={() => setIsPlaying(false)} onPause={() => setIsPlaying(false)}
onVolumeChange={handleVolumeChangeEvent} onVolumeChange={handleVolumeChangeEvent}
onError={handleError}
crossOrigin="anonymous"
{...defaultProps} {...defaultProps}
> >
{sortedSources.map(({ src, type }) => ( {sortedSources.map(({ src, type }) => (
@@ -173,12 +179,28 @@ export function VideoPlayer({
)) ))
: null} : null}
</video> </video>
{(showPoster || hasError) && poster ? (
<Image
src={poster.src}
alt=""
aria-hidden="true"
focalPoint={focalPoint}
dimensions={poster.dimensions}
fill
sizes={
containerWidth
? `${containerWidth}px`
: `(min-width: 1367px) ${variant === 'inline' ? '700px' : '100vw'}, 100vw`
}
/>
) : null}
{showPlayButton ? ( {showPlayButton ? (
<VideoPlayerButton <VideoPlayerButton
className={styles.playButton} className={styles.playButton}
onPress={togglePlay} onPress={togglePlay}
iconName={isPlaying ? 'pause' : 'play_arrow'} iconName={isPlaying ? 'pause' : 'play_arrow'}
ariaLabel={ size={variant === 'hero' ? 'sm' : 'lg'}
aria-label={
isPlaying isPlaying
? intl.formatMessage({ ? intl.formatMessage({
id: 'videoPlayer.pause', id: 'videoPlayer.pause',
@@ -196,7 +218,8 @@ export function VideoPlayer({
className={styles.muteButton} className={styles.muteButton}
onPress={handleMuteToggle} onPress={handleMuteToggle}
iconName={isMuted ? 'volume_off' : 'volume_up'} iconName={isMuted ? 'volume_off' : 'volume_up'}
ariaLabel={ size="sm"
aria-label={
isMuted isMuted
? intl.formatMessage({ ? intl.formatMessage({
id: 'videoPlayer.mute', id: 'videoPlayer.mute',
@@ -212,31 +235,3 @@ export function VideoPlayer({
</div> </div>
) )
} }
function getVideoPropsByVariant(
variant: VideoPlayerProps['variant'],
isInteractedWith: boolean,
autoPlay?: boolean
): VideoHTMLAttributes<HTMLVideoElement> {
switch (variant) {
case 'hero':
return {
controls: false,
controlsList: 'nodownload nofullscreen noremoteplayback',
autoPlay: autoPlay ?? true,
muted: true,
loop: true,
playsInline: true,
}
case 'inline':
default:
return {
controls: isInteractedWith,
controlsList: 'nodownload noremoteplayback',
autoPlay: autoPlay ?? isInteractedWith,
muted: true,
loop: false,
playsInline: true,
}
}
}

View File

@@ -0,0 +1,27 @@
import { Lang } from '@scandic-hotels/common/constants/language'
import { FocalPoint } from '@scandic-hotels/common/utils/imageVault'
import { VariantProps } from 'class-variance-authority'
import { variants } from './variants'
interface Caption {
src: string
srcLang: Lang
isDefault: boolean
}
export interface VideoPlayerProps extends VariantProps<typeof variants> {
sources: {
src: string
type: string
}[]
poster?: {
src: string
dimensions?: { width: number; height: number }
} | null
className?: string
captions?: Caption[]
focalPoint?: FocalPoint
autoPlay?: boolean
hasOverlay?: boolean
fullHeight?: boolean
}

View File

@@ -0,0 +1,39 @@
import { useRef, useState } from 'react'
/**
* Hook to measure container width for optimizing poster image sizes.
* Captures the container width when video metadata loads to pass to Image component.
*/
export function useVideoDimensions() {
const containerRef = useRef<HTMLDivElement>(null)
const [containerWidth, setContainerWidth] = useState<number | null>(null)
const [hasError, setHasError] = useState(false)
function handleMetadataLoaded() {
const container = containerRef.current
if (!container || containerWidth) {
return
}
setContainerWidth(container.getBoundingClientRect().width)
}
function handleError() {
setHasError(true)
const container = containerRef.current
if (!container || containerWidth) {
return
}
setContainerWidth(container.getBoundingClientRect().width)
}
return {
containerRef,
handleMetadataLoaded,
containerWidth,
handleError,
hasError,
}
}

View File

@@ -0,0 +1,30 @@
import { VideoHTMLAttributes } from 'react'
import { VideoPlayerProps } from './types'
export function getVideoPropsByVariant(
variant: VideoPlayerProps['variant'],
hasManuallyPlayed: boolean,
shouldAutoPlay: boolean
): VideoHTMLAttributes<HTMLVideoElement> {
switch (variant) {
case 'hero':
return {
controls: false,
controlsList: 'nodownload nofullscreen noremoteplayback',
autoPlay: shouldAutoPlay,
muted: true,
loop: true,
playsInline: true,
}
case 'inline':
default:
return {
controls: hasManuallyPlayed,
controlsList: 'nodownload noremoteplayback',
autoPlay: shouldAutoPlay,
muted: true,
loop: false,
playsInline: true,
}
}
}

View File

@@ -14,6 +14,7 @@
&.hero { &.hero {
height: 100%; height: 100%;
.overlay { .overlay {
display: contents; display: contents;
} }
@@ -35,6 +36,10 @@
rgba(31, 28, 27, 0.8) 100% rgba(31, 28, 27, 0.8) 100%
); );
} }
&.hasError .video {
aspect-ratio: 16 / 9;
}
} }
.video { .video {

View File

@@ -12,6 +12,7 @@ export const Video = gql`
} }
} }
} }
poster_image
focal_point { focal_point {
x x
y y

View File

@@ -2,6 +2,7 @@ import { z } from "zod"
import { Lang } from "@scandic-hotels/common/constants/language" import { Lang } from "@scandic-hotels/common/constants/language"
import { focalPointSchema } from "@scandic-hotels/common/utils/focalPoint" import { focalPointSchema } from "@scandic-hotels/common/utils/focalPoint"
import { transformedImageVaultAssetSchema } from "@scandic-hotels/common/utils/imageVault"
import { assetSystemSchema } from "./system" import { assetSystemSchema } from "./system"
@@ -16,6 +17,7 @@ export const videoSchema = z.object({
}) })
), ),
}), }),
poster_image: transformedImageVaultAssetSchema.nullish(),
focal_point: focalPointSchema.nullish(), focal_point: focalPointSchema.nullish(),
captions: z.array( captions: z.array(
z.object({ z.object({
@@ -57,6 +59,12 @@ export const transformedVideoSchema = videoSchema
return { return {
sources, sources,
poster: video.poster_image?.url
? {
src: video.poster_image.url,
dimensions: video.poster_image.dimensions,
}
: null,
focalPoint: video.focal_point focalPoint: video.focal_point
? { x: video.focal_point.x, y: video.focal_point.y } ? { x: video.focal_point.x, y: video.focal_point.y }
: { x: 50, y: 50 }, : { x: 50, y: 50 },