Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set up scheduling for slides #15 #22

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions studio/schemaTypes/documents/slide.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,15 @@ export default {
{type: 'testSlide'},
].filter((e) => e),
}),
defineField({
name: 'duration',
type: 'number',
title: 'Optional slide duration in seconds, default is 30',
description:
'If there is a video it will play the duration of the video, except if this field is set',
validation: (Rule) =>
Rule.min(1).integer().positive().warning('Duration should be a positive whole number'),
}),
].filter((e) => e),
orderings: [
{
Expand All @@ -47,12 +56,13 @@ export default {
preview: {
select: {
title: 'title',
duration: 'duration',
},
prepare(selection: any) {
const {title} = selection
const {title, duration} = selection
return {
title: title,
subtitle: 'Slide ',
subtitle: `Duration: ${duration || 30} seconds`,
}
},
},
Expand Down
16 changes: 6 additions & 10 deletions web/app/[slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,25 @@
import { getSlideshowsQuery, pagesSlugs } from '@/sanity/lib/queries'
import Slideshow from '@/components/sections/Slideshow'
import { sanityFetch } from '@/sanity/lib/live'

type Props = {
params: Promise<{ slug: string }>
}
import Slideshow from '@/components/sections/Slideshow'

export const revalidate = 60
export const dynamicParams = true

export async function generateStaticParams() {
/** Fetching all locations to create separate route for each */
const { data } = await sanityFetch({
query: pagesSlugs,
// // Use the published perspective in generateStaticParams
perspective: 'published',
stega: false,
})

return data
}

export default async function Page(props: Props) {
const params = await props.params
const { data: slideshows } = await sanityFetch({ query: getSlideshowsQuery, params })
export default async function Page({ params }: { params: { slug: string } }) {
const { data: slideshows } = await sanityFetch({
query: getSlideshowsQuery,
params,
})

return (
<div className="h-full w-full">
Expand Down
40 changes: 40 additions & 0 deletions web/common/helpers/isSlideActive.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
export function isSlideActive(slide: any): boolean {
const scheduling = slide.scheduling
if (!scheduling) return true

const now = new Date()

switch (scheduling.scheduleType) {
case '1': {
// Specific period
const from = scheduling.period?.from ? new Date(scheduling.period.from) : null
const to = scheduling.period?.to ? new Date(scheduling.period.to) : null
if (from && now < from) return false
if (to && now > to) return false
return true
}

case '2': {
// Selected weekdays
const today = now.toLocaleString('en-US', { weekday: 'long' }).toLowerCase()
return scheduling.weekdays?.includes(today) || false
}

case '3': {
// Slide frequency
const dayOfMonth = now.getDate()
return (
scheduling.slideFrequency?.some((freq: string) => {
const freqNum = parseInt(freq, 10)
// Basic example: "every Xth day" means dayOfMonth % X == 0
return dayOfMonth % freqNum === 0
}) || false
)
}

default:
return true
}
}

export default isSlideActive
6 changes: 2 additions & 4 deletions web/components/sections/SectionMapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,11 @@ const componentMap: { [key: string]: React.ComponentType<any> } = {
testSlide: TestSlide,
}

export default function SectionMapper({ section }: { section?: any }) {
export default function SectionMapper({ section, onVideoDuration }: { section?: any; onVideoDuration?: any }) {
const type = section?.content?.[0]
console.log('type', type)
const Component = componentMap[type?.type]
if (!Component) {
// Fallback for unknown section types to debug
return <div data-type={type} key={type?.id} />
}
return <Component {...type} key={type?.id} />
return <Component {...type} onVideoDuration={onVideoDuration} key={type?.id} />
}
63 changes: 55 additions & 8 deletions web/components/sections/Slideshow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,68 @@

import { useEffect, useState } from 'react'
import SectionMapper from './SectionMapper'
import isSlideActive from '@/common/helpers/isSlideActive'

type Slide = {
content: any
duration?: number | null
scheduling?: any
}

type SlideshowProps = {
slideshows: any[]
slideshows: {
slides: Slide[]
}[]
}

export default function Slideshow({ slideshows }: SlideshowProps) {
const [activeSlideIndex, setActiveSlideIndex] = useState(0)
const [activeSlides, setActiveSlides] = useState<Slide[]>([])
const [currentIndex, setCurrentIndex] = useState(0)
const [videoDuration, setVideoDuration] = useState<number | null>(null)

function handleVideoDuration(durationSeconds: number) {
setVideoDuration(durationSeconds)
}

useEffect(() => {
if (!slideshows[0]) return
const initiallyActive = slideshows[0].slides.filter(isSlideActive) || []
setActiveSlides(initiallyActive)
setCurrentIndex(0)
}, [slideshows])

useEffect(() => {
const interval = setInterval(() => setActiveSlideIndex((i) => (i + 1) % slideshows?.[0]?.slides.length), 30000)
if (activeSlides.length === 0) return
const currentSlide = activeSlides[currentIndex]
const durationMs = (currentSlide?.duration || videoDuration || 30) * 1000

const timer = setTimeout(() => {
const refreshed = slideshows[0]?.slides?.filter(isSlideActive) || []

setActiveSlides((prevActive) => {
if (refreshed.length !== prevActive.length && currentIndex >= refreshed.length) {
setCurrentIndex(0)
}
return refreshed
})

setCurrentIndex((prev) => {
if (refreshed.length === 0) return 0
return (prev + 1) % refreshed.length
})
}, durationMs)

return () => clearTimeout(timer)
}, [activeSlides, currentIndex, slideshows])

if (activeSlides.length === 0) {
return <div>No active slides</div>
}

return () => {
clearInterval(interval)
}
}, [])
const slide = activeSlides[currentIndex]
if (!slide || !slide.content || slide.content.length === 0) {
return <div>This slide has no content</div>
}

return <SectionMapper section={slideshows?.[0]?.slides[activeSlideIndex]} />
return <SectionMapper section={slide} onVideoDuration={handleVideoDuration} />
}
29 changes: 23 additions & 6 deletions web/components/slides/FullscreenVideo.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,34 @@
import { Suspense } from 'react'
import React, { useEffect, useRef, Suspense } from 'react'

interface FullscreenVideoProps {
video: any
video: { url: string }
thumbnail?: string
onVideoDuration?: any
}

export default function FullscreenImage(props: FullscreenVideoProps) {
const { video, thumbnail } = props
console.log('video', video)
export default function FullscreenVideo(props: FullscreenVideoProps) {
const { video, onVideoDuration } = props
const videoRef = useRef<HTMLVideoElement>(null)

useEffect(() => {
const el = videoRef.current
if (!el) return

function handleMetadata() {
const duration = el?.duration
if (onVideoDuration) {
onVideoDuration(duration)
}
}

el.addEventListener('loadedmetadata', handleMetadata)
return () => el.removeEventListener('loadedmetadata', handleMetadata)
}, [onVideoDuration])

return (
<div className="absolute inset-0 -z-10 w-full overflow-hidden">
<Suspense fallback={<p>Loading video...</p>}>
<video autoPlay controls={false} muted playsInline loop className="h-screen w-screen object-cover">
<video ref={videoRef} autoPlay muted playsInline loop className="h-screen w-screen object-cover">
<source src={video.url} type="video/mp4" />
Your browser does not support the video tag.
</video>
Expand Down
1 change: 1 addition & 0 deletions web/sanity/lib/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export const getSlideshowsQuery = defineQuery(`
scheduling{
...,
},
duration,
content[]{
_type == "infoBoard" => {
"type": _type,
Expand Down
Loading