diff --git a/components/Preview/components/Airing/index.tsx b/components/Preview/components/Airing/index.tsx new file mode 100644 index 0000000..625b51f --- /dev/null +++ b/components/Preview/components/Airing/index.tsx @@ -0,0 +1,30 @@ +'use client'; + +import { FC } from 'react'; + +import Hint from '@/components/ui/hint'; +import { formatDate } from '@/lib/utils'; + +interface Props { + airing: Airing; + className?: string; +} + +const pad = (value: number) => String(value).padStart(2, '0'); + +const getLabels = ({ season, episode, seasons, ended, next }: Airing) => [ + `Season ${season}, episode ${episode}`, + next + ? `Next episode ${formatDate(next)}` + : ended + ? `Ended after ${seasons} season${seasons === 1 ? '' : 's'}` + : 'Next episode date to be announced' +]; + +const Airing: FC = ({ airing, className }) => ( + + S{pad(airing.season)} E{pad(airing.episode)} + +); + +export default Airing; diff --git a/components/Preview/components/Availability/index.tsx b/components/Preview/components/Availability/index.tsx new file mode 100644 index 0000000..0a4ab6d --- /dev/null +++ b/components/Preview/components/Availability/index.tsx @@ -0,0 +1,52 @@ +'use client'; + +import { FC } from 'react'; +import { Disc, MonitorPlay, Popcorn } from 'lucide-react'; + +import Hint from '@/components/ui/hint'; +import { getAvailabilityState, isUpcoming } from '@/data/dto/Availability'; +import { formatDate } from '@/lib/utils'; + +interface Props { + availability: Availability; + className?: string; +} + +const ICONS = { + theatre: Popcorn, + stream: MonitorPlay, + bluray: Disc +}; + +const getLabels = ({ theatre, stream, bluray }: Availability, state: AvailabilityState) => { + if (state === 'bluray') return [bluray ? `On Blu-ray since ${formatDate(bluray)}` : 'On Blu-ray']; + if (state === 'stream') return [stream ? `Streaming since ${formatDate(stream)}` : 'Streaming']; + if (theatre && isUpcoming(theatre)) return [`In theatres from ${formatDate(theatre)}`]; + + const announced = [ + stream && isUpcoming(stream) && `Streaming from ${formatDate(stream)}`, + bluray && isUpcoming(bluray) && `Blu-ray from ${formatDate(bluray)}` + ].filter(Boolean) as string[]; + + return ['In theatres only', ...(announced.length ? announced : ['Streaming date to be announced'])]; +}; + +const Availability: FC = ({ availability, className }) => { + const state = getAvailabilityState(availability); + + if (!state) return null; + + const Icon = ICONS[state]; + + return ( + + + + ); +}; + +export default Availability; diff --git a/components/Preview/index.tsx b/components/Preview/index.tsx index d5ffc8d..33302b0 100644 --- a/components/Preview/index.tsx +++ b/components/Preview/index.tsx @@ -10,6 +10,8 @@ import { Modal } from '@/components/ui/dialog'; import { cn } from '@/lib/utils'; import Actions from './components/Actions'; +import Airing from './components/Airing'; +import Availability from './components/Availability'; interface Props { show?: Show & Partial
; @@ -52,8 +54,12 @@ const Preview: FC = ({
{show.title} -
+
{new Date(show.release).getFullYear()} + {Boolean(show.availability) && ( + + )} + {Boolean(show.airing) && } {Boolean(show.runtime) && ( {show.runtime} minutes )} diff --git a/components/ui/hint.tsx b/components/ui/hint.tsx new file mode 100644 index 0000000..ca88da0 --- /dev/null +++ b/components/ui/hint.tsx @@ -0,0 +1,51 @@ +'use client'; + +import { FC, ReactNode, useState } from 'react'; + +import { cn } from '@/lib/utils'; + +interface Props { + lines: string[]; + children: ReactNode; + className?: string; + triggerClassName?: string; +} + +const Hint: FC = ({ lines, children, className, triggerClassName }) => { + const [open, setOpen] = useState(false); + + // an animation that lands on a transform turns this wrapper into a stacking context, + // so the tooltip can only reach above the following rows by raising the wrapper itself + return ( + + + + {lines.map((line) => ( + + {line} + + ))} + + + ); +}; + +export default Hint; diff --git a/data/dto/Airing.ts b/data/dto/Airing.ts new file mode 100644 index 0000000..b4511e9 --- /dev/null +++ b/data/dto/Airing.ts @@ -0,0 +1,23 @@ +const ENDED_STATUSES = ['Ended', 'Canceled']; + +export const mapDetailsToAiring = ({ + last_episode_to_air, + next_episode_to_air, + number_of_seasons, + status +}: TMDBSeriesDetails): Airing | undefined => { + // before a premiere there is nothing aired yet, the upcoming episode is the only position we have + const current = last_episode_to_air || next_episode_to_air; + + if (!current) return undefined; + + return { + season: current.season_number, + episode: current.episode_number, + seasons: number_of_seasons || current.season_number, + ended: ENDED_STATUSES.includes(status || ''), + next: next_episode_to_air?.air_date || undefined + }; +}; + +export default mapDetailsToAiring; diff --git a/data/dto/Availability.ts b/data/dto/Availability.ts new file mode 100644 index 0000000..259f6ab --- /dev/null +++ b/data/dto/Availability.ts @@ -0,0 +1,45 @@ +// TMDB release types: 1 premiere, 2 limited theatrical, 3 theatrical, 4 digital, 5 physical, 6 TV +const STATE_BY_RELEASE_TYPE: Record = { + 1: 'theatre', + 2: 'theatre', + 3: 'theatre', + 4: 'stream', + 5: 'bluray' +}; + +/** How long a movie is assumed to still be running in theatres when TMDB has no digital/physical date yet */ +const THEATRICAL_WINDOW = 120 * 24 * 60 * 60 * 1000; + +export const mapReleaseDatesToAvailability = (results?: TMDBCountryReleaseDates[]): Availability | undefined => { + // TMDB reports dates per country, it doesn't matter where a window opened first — only when + const availability = (results || []).reduce((dates, { release_dates }) => { + (release_dates || []).forEach(({ type, release_date }) => { + const state = STATE_BY_RELEASE_TYPE[type]; + const earliest = state && dates[state]; + + if (!state || !release_date) return; + if (!earliest || release_date < earliest) dates[state] = release_date; + }); + + return dates; + }, {}); + + return Object.keys(availability).length ? availability : undefined; +}; + +export const isUpcoming = (date?: string) => Boolean(date && Date.parse(date) > Date.now()); + +const isReleased = (date?: string) => Boolean(date && Date.parse(date) <= Date.now()); + +export const getAvailabilityState = ({ theatre, stream, bluray }: Availability): AvailabilityState | undefined => { + if (isReleased(bluray)) return 'bluray'; + if (isReleased(stream)) return 'stream'; + if (isUpcoming(theatre)) return 'theatre'; + if (!theatre) return undefined; + + // Still in theatres only while the run lasts or while a digital/physical date is announced but not reached, + // otherwise TMDB simply never got the digital entry and the movie is long out of cinemas + const isRunning = Date.now() - Date.parse(theatre) < THEATRICAL_WINDOW; + + return isRunning || isUpcoming(stream) || isUpcoming(bluray) ? 'theatre' : 'stream'; +}; diff --git a/data/queries/credits.ts b/data/queries/credits.ts index ed5722d..eb263cb 100644 --- a/data/queries/credits.ts +++ b/data/queries/credits.ts @@ -5,6 +5,17 @@ export type CreditsQueryProps = { showType?: Show['type']; }; +const photo = (path: string) => `https://image.tmdb.org/t/p/w185${path}`; + +// a series has no single director, so the one behind most episodes stands in for it +const findDirector = (crew: Crew[] = []) => + crew + .filter( + ({ profile_path, job, jobs }) => + profile_path && (job === 'Director' || jobs?.some((entry) => entry.job === 'Director')) + ) + .sort((a, b) => (b.total_episode_count || 0) - (a.total_episode_count || 0))[0]; + const creditsQuery = ({ showId, showType }: CreditsQueryProps) => ({ enabled: Boolean(showId), queryKey: ['credits', showId, showType], @@ -12,12 +23,15 @@ const creditsQuery = ({ showId, showType }: CreditsQueryProps) => ({ movieAdvisor .get<{ cast: Array; + crew: Crew[]; }>(`/${showType}/${showId}/${showType === 'tv' ? 'aggregate_credits' : 'credits'}`) - .then(({ cast }) => { - return cast - .filter((person) => person.profile_path) + .then(({ cast, crew }) => { + const director = findDirector(crew); + + const actors: Actor[] = cast + .filter((person) => person.profile_path && person.id !== director?.id) .map((actor) => { - const photoUrl = `https://image.tmdb.org/t/p/w185${actor.profile_path}`; + const photoUrl = photo(actor.profile_path); if ('character' in actor) return { ...actor, photoUrl }; @@ -25,6 +39,10 @@ const creditsQuery = ({ showId, showType }: CreditsQueryProps) => ({ return { ...actor, character, photoUrl }; }); + + if (!director) return actors; + + return [{ ...director, character: 'Director', photoUrl: photo(director.profile_path) }, ...actors]; }) }); diff --git a/data/queries/details.ts b/data/queries/details.ts index 2337cf9..c2d677c 100644 --- a/data/queries/details.ts +++ b/data/queries/details.ts @@ -1,4 +1,6 @@ import movieAdvisor from '../clients/movieAdvisor'; +import { mapDetailsToAiring } from '../dto/Airing'; +import { mapReleaseDatesToAvailability } from '../dto/Availability'; import { mapMovieSeriesToShow } from '../dto/Show'; export type DetailsQueryProps = { @@ -6,13 +8,27 @@ export type DetailsQueryProps = { showType?: Show['type']; }; +type DetailsResponse = (Movie | Series) & + Details & + TMDBSeriesDetails & { + release_dates?: { results: TMDBCountryReleaseDates[] }; + }; + const detailsQuery = ({ showId, showType }: DetailsQueryProps) => ({ enabled: Boolean(showId), queryKey: ['details', showId, showType], queryFn: () => movieAdvisor - .get<(Movie | Series) & Details>(`/${showType}/${showId}`) - .then((response) => ({ ...response, ...mapMovieSeriesToShow(response, showType) })) + .get( + `/${showType}/${showId}`, + showType === 'movie' ? { params: { append_to_response: 'release_dates' } } : undefined + ) + .then(({ release_dates, ...response }) => ({ + ...response, + ...mapMovieSeriesToShow(response, showType), + availability: mapReleaseDatesToAvailability(release_dates?.results), + airing: showType === 'tv' ? mapDetailsToAiring(response) : undefined + })) .catch((error) => Promise.reject(error)) }); diff --git a/data/queries/popular.ts b/data/queries/popular.ts index 89fd2e5..1b109f4 100644 --- a/data/queries/popular.ts +++ b/data/queries/popular.ts @@ -15,7 +15,7 @@ const popularQuery = ({ sortBy = 'popularity.desc', starring }: PopularQueryProp params: { page: pageParam, sort_by: sortBy, - with_cast: starring, + // with_people covers cast and crew, with_cast on top of it would AND directors away with_people: starring, 'vote_count.gte': 300, 'vote_average.lte': 10, diff --git a/lib/utils.ts b/lib/utils.ts index 34710fe..f10ab7f 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -3,6 +3,12 @@ import { twMerge } from 'tailwind-merge'; export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs)); +// TMDB dates are UTC midnight, formatting them in the local zone would shift them a day back +export const formatDate = (date: string) => + new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }) + .format(new Date(date)) + .replace(/\//g, '.'); + export const createUniqueRandomGenerator = (max: number) => { const numbers = Array.from({ length: max }, (_, i) => i + 1); diff --git a/types.d.ts b/types.d.ts index 2b0a688..1382f8b 100644 --- a/types.d.ts +++ b/types.d.ts @@ -18,8 +18,52 @@ interface Details { imdb_id: string; runtime: number; tagline: string; + availability?: Availability; + airing?: Airing; } +interface TMDBEpisode { + air_date: string | null; + episode_number: number; + season_number: number; + name: string; +} + +interface TMDBSeriesDetails { + last_episode_to_air?: TMDBEpisode | null; + next_episode_to_air?: TMDBEpisode | null; + number_of_seasons?: number; + status?: string; +} + +/** Where a series currently stands — the latest aired episode plus what follows it */ +interface Airing { + season: number; + episode: number; + seasons: number; + ended: boolean; + /** air date of the next episode, ISO string, only when TMDB knows one */ + next?: string; +} + +interface TMDBReleaseDate { + certification: string; + iso_639_1: string; + note: string; + release_date: string; + type: number; +} + +interface TMDBCountryReleaseDates { + iso_3166_1: string; + release_dates: TMDBReleaseDate[]; +} + +type AvailabilityState = 'theatre' | 'stream' | 'bluray'; + +/** Earliest worldwide release date per window, ISO strings */ +type Availability = Partial>; + interface Movie { adult: boolean; backdrop_path: string; @@ -82,9 +126,18 @@ interface Person { original_name: string; popularity: number; profile_path: string; - cast_id: number; credit_id: string; - order: number; + // crew members carry neither + cast_id?: number; + order?: number; +} + +interface Crew extends Person { + department: string; + /** movie credits carry a single job, tv aggregate credits carry one entry per job */ + job?: string; + jobs?: Array<{ credit_id: string; job: string; episode_count: number }>; + total_episode_count?: number; } interface Actor extends Person {