@soffits/dsh-media-hub 0.0.0-stage → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The Watching tab's optional parts, each shown only when switched on in the
3
+ * `presence` setting and when there is something to show: "How was it?" for
4
+ * shows finished or removed lately (one tap writes a rating to the watch
5
+ * log), and picks from the recommender extension with the reason for each.
6
+ */
7
+ import { Picture } from './details.js'
8
+ import { FollowButton } from './follow.js'
9
+ import { Btn, Icon, K, P, asPerson, displayName, fillNodes, h, React } from './ui.js'
10
+
11
+ /** The answers, in order, with the icon each one shows (DSH's own where it has one). */
12
+ const ANSWERS = [
13
+ { rating: 'loved', icon: () => h(K.Icon, { name: 'heart', size: 16 }) },
14
+ { rating: 'fine', icon: () => h(P.IconLikeOutlineRegular, { size: 16 }) },
15
+ { rating: 'not-for-me', icon: () => h(P.IconDislikeOutlineRegular, { size: 16 }) },
16
+ { rating: 'unfinished', icon: () => h(K.Icon, { name: 'circle-pause', size: 16 }) },
17
+ ]
18
+
19
+ /** Loads a person route once the part is on; `null` until it answers. */
20
+ function usePersonList(on, path, field, version) {
21
+ const [list, setList] = React.useState(null)
22
+ React.useEffect(() => {
23
+ if (!on) return undefined
24
+ let live = true
25
+ asPerson(path, undefined).then((answer) => { if (live) setList(Array.isArray(answer[field]) ? answer[field] : []) })
26
+ return () => { live = false }
27
+ }, [on, path, field, version])
28
+ return [on ? list : null, setList]
29
+ }
30
+
31
+ function Section({ id, title, hint, children }) {
32
+ return h('section', { className: 'vsync-section', 'aria-labelledby': id },
33
+ h('div', { className: 'vsync-sectionHead vsync-sectionHeadInline' },
34
+ h('h2', { id }, title),
35
+ hint && h('span', { className: 'vsync-sectionMeta' }, hint)),
36
+ children)
37
+ }
38
+
39
+ function RatingRow({ t, ask, onAnswered }) {
40
+ const [busy, setBusy] = React.useState(false)
41
+ const answer = async (rating) => {
42
+ setBusy(true)
43
+ const result = await asPerson('ratings', { show: ask.show, title: ask.title, rating })
44
+ setBusy(false)
45
+ if (!result.error) onAnswered(ask.show)
46
+ }
47
+ return h(K.Surface, { as: 'li', className: 'vsync-rate' },
48
+ h('div', { className: 'vsync-rateHead' },
49
+ h(K.Tile, { icon: 'clapperboard', tone: 'violet', size: 36 }),
50
+ h('div', { className: 'vsync-rateText' },
51
+ h('p', { className: 'vsync-rowTitle' }, ask.title),
52
+ h('p', { className: 'vsync-rowMeta' }, fillNodes(t(`ratings.${ask.why}`), { when: h(K.TimeAgo, { at: new Date(ask.at).toISOString() }) })))),
53
+ h('div', { className: 'vsync-rateAnswers', role: 'group', 'aria-label': t('ratings.heading') },
54
+ ANSWERS.map(({ rating, icon }) => h(Btn, { key: rating, variant: rating === 'unfinished' ? 'toolbar' : 'outline', disabled: busy, icon: icon(), onClick: () => answer(rating) }, t(`ratings.${rating}`)))))
55
+ }
56
+
57
+ export function RatingsSection({ t, on, version }) {
58
+ const [pending, setPending] = usePersonList(on, 'ratings', 'pending', version)
59
+ if (!pending || pending.length === 0) return null
60
+ return h(Section, { id: 'vsync-ratings', title: t('ratings.heading'), hint: t('ratings.hint') },
61
+ h('ul', { className: 'vsync-cards' }, pending.map(ask => h(RatingRow, { key: ask.show, t, ask, onAnswered: show => setPending(pending.filter(other => other.show !== show)) }))))
62
+ }
63
+
64
+ function PickCard({ t, pick, onOpen, onOpenWork }) {
65
+ const { work, why } = pick
66
+ const [busy, setBusy] = React.useState(false)
67
+ const [error, setError] = React.useState(null)
68
+ const meta = [work.kind && t(`kind.${work.kind}`) !== `kind.${work.kind}` ? t(`kind.${work.kind}`) : null, work.year, Number.isFinite(work.score) ? [work.scoreLabel, work.score].filter(Boolean).join(' ') : null].filter(Boolean)
69
+ const together = async () => {
70
+ setBusy(true)
71
+ setError(null)
72
+ const answer = await asPerson('fetch', { source: work.source, id: work.id, watch: true, together: true, language: t.language, by: await displayName(t('guest')) })
73
+ setBusy(false)
74
+ if (answer.error) return setError(answer.error)
75
+ return onOpen(answer.room.id)
76
+ }
77
+ return h(K.Surface, { as: 'li', className: 'vsync-pickCard' },
78
+ h('button', { type: 'button', className: 'vsync-pickOpen', tabIndex: -1, 'aria-hidden': true, onClick: () => onOpenWork(work.source, work) },
79
+ h(Picture, { pictures: [work.cover], className: 'vsync-pickCover', emptyClassName: 'vsync-pickCover vsync-ccPosterEmpty', icon: h(Icon.Film, { size: 22 }) })),
80
+ h('div', { className: 'vsync-pickBody' },
81
+ h('button', { type: 'button', className: 'vsync-pickTitle', onClick: () => onOpenWork(work.source, work) }, work.title),
82
+ meta.length > 0 && h('p', { className: 'vsync-rowMeta' }, meta.join(' · ')),
83
+ h('p', { className: 'vsync-pickWhy' }, h(K.Icon, { name: 'sparkles', size: 14, tone: 'violet' }), h('span', null, why)),
84
+ h('div', { className: 'vsync-pickActions' },
85
+ h(Btn, { disabled: busy, onClick: together, icon: h(P.IconUsersOutlineRegular, { size: 16 }) }, t('room.watchTogether')),
86
+ h(FollowButton, { t, source: work.source, work, compact: true })),
87
+ error && h('p', { className: 'vsync-error', role: 'alert' }, error)))
88
+ }
89
+
90
+ export function PicksSection({ t, on, onOpen, onOpenWork }) {
91
+ const [picks] = usePersonList(on, 'picks', 'picks', 0)
92
+ if (!picks || picks.length === 0) return null
93
+ return h(Section, { id: 'vsync-picks', title: t('picks.heading'), hint: t('picks.hint') },
94
+ h('ul', { className: 'vsync-cards vsync-pickGrid' }, picks.map(pick => h(PickCard, { key: `${pick.work.source}:${pick.work.id}`, t, pick, onOpen, onOpenWork }))))
95
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * When a <video> held at the ready gate counts as ready, and what to do when
3
+ * it never gets there on its own. Pure, so Node tests it.
4
+ *
5
+ * Desktop browsers keep loading a paused video. Safari on iOS loads little
6
+ * or nothing until the element plays, so a test like "3 s buffered" can wait
7
+ * forever there. Ready therefore means the element itself says it can play
8
+ * (HAVE_FUTURE_DATA, the state behind `canplay`), with a few seconds buffered
9
+ * while the browser is still fetching, or as much as it chose to fetch once it
10
+ * stopped. An element that does not get even that far is primed: played muted
11
+ * for a moment, which makes iOS load, then put back where the room holds.
12
+ */
13
+
14
+ export const HAVE_FUTURE_DATA = 3
15
+ export const HAVE_ENOUGH_DATA = 4
16
+ /** Ready with this much buffered ahead (or to the end) while the browser is still fetching. */
17
+ export const READY_AHEAD_S = 3
18
+ /** The browser stopped fetching when no `progress` came for this long. */
19
+ export const LOAD_IDLE_MS = 1000
20
+ /** A viewer held at a gate this long without being able to play gets its player primed. */
21
+ export const PRIME_AFTER_MS = 1500
22
+ /** A viewer still loading after this long is offered a button that starts loading from a tap. */
23
+ export const TAP_AFTER_MS = 8000
24
+
25
+ /** Seconds buffered ahead of `at` in one continuous range. */
26
+ export function bufferedAhead(ranges, at) {
27
+ for (const [start, end] of ranges) if (start <= at + 0.05 && end > at) return end - at
28
+ return 0
29
+ }
30
+
31
+ /**
32
+ * Whether the element can start from where it stands.
33
+ * @param {{ readyState: number, seeking: boolean, at: number, duration: number, ranges: Array<[number, number]>, loadIdleMs: number }} media
34
+ */
35
+ export function canStart({ readyState, seeking, at, duration, ranges, loadIdleMs }) {
36
+ if (seeking || readyState < HAVE_FUTURE_DATA) return false
37
+ if (readyState >= HAVE_ENOUGH_DATA || !fetching(loadIdleMs)) return true
38
+ const need = Math.min(READY_AHEAD_S, Math.max(0, (Number.isFinite(duration) ? duration : Infinity) - at - 0.1))
39
+ return bufferedAhead(ranges, at) >= need
40
+ }
41
+
42
+ /** Whether the browser is still fetching for the element: a `progress` came lately. */
43
+ export const fetching = loadIdleMs => loadIdleMs < LOAD_IDLE_MS
44
+
45
+ /**
46
+ * Whether to prime a held player now: it has waited a while, cannot start,
47
+ * is paused, the browser stopped fetching for it (a slow line that still
48
+ * loads is left alone), and it was not primed for this gate yet.
49
+ */
50
+ export function shouldPrime({ heldMs, ready, paused, loadIdleMs, primed }) {
51
+ return !ready && paused && !primed && !fetching(loadIdleMs) && heldMs >= PRIME_AFTER_MS
52
+ }
53
+
54
+ /** Whether to offer this viewer "tap to continue": still loading at a gate after a while. */
55
+ export const offerTap = ({ loadingMs }) => loadingMs >= TAP_AFTER_MS
@@ -0,0 +1,114 @@
1
+ /**
2
+ * One search result as a card: cover, title, score, how many watched it,
3
+ * episodes, status and tags at a glance, with the actions to watch or save
4
+ * it. Details (web/details.js) opens everything the source gives and the
5
+ * other seasons and linked works, which open as a work of their own.
6
+ */
7
+ import { ChatButton } from './books-view.js'
8
+ import { Cover, WorkDetails, glance, infoOf } from './details.js'
9
+ import { FollowButton } from './follow.js'
10
+ import { hasEpisodes, resumeLabel } from './format.js'
11
+ import { useKnownWork } from './known.js'
12
+ import { Confirm, EPISODE_BYTES, Icon, React, Spinner, asPerson, bytes, chatAbout, clock, displayName, fill, h } from './ui.js'
13
+
14
+ /** Episodes fetched ahead of the one being watched; the Host's `cacheAhead` default, for the size hint. */
15
+ const WINDOW_EPISODES = 6
16
+
17
+ /** The words for a quality a source offers: auto, audio, or a height. */
18
+ const qualityLabel = (t, quality) => (/^\d+$/.test(quality) ? fill(t('quality.height'), { n: quality }) : t(`quality.${quality}`))
19
+
20
+ /** How the episodes are fetched, for a source that offers a choice (Link); its first choice (auto) is the default. */
21
+ function QualityPicker({ t, qualities, value, onChange }) {
22
+ return h('select', { className: 'vsync-field vsync-pick vsync-quality', value, 'aria-label': t('quality.label'), title: t('quality.label'), onChange: event => onChange(event.target.value) },
23
+ qualities.map(quality => h('option', { key: quality, value: quality }, qualityLabel(t, quality))))
24
+ }
25
+
26
+ export function Result({ t, source, result, onOpen, onSaved, onFocus, defaultOpen = false }) {
27
+ const [info, setInfo] = React.useState(null)
28
+ const [open, setOpen] = React.useState(defaultOpen)
29
+ const [state, setState] = React.useState({ step: 'idle' })
30
+ const qualities = result.qualities ?? []
31
+ const [quality, setQuality] = React.useState(qualities[0] ?? '')
32
+ const submitting = React.useRef(false)
33
+ const known = useKnownWork(source.id, result.id)
34
+ // The episode count normally comes with the result; ask for the details only when it did not.
35
+ const needInfo = open || result.episodes === null
36
+ React.useEffect(() => {
37
+ if (!needInfo) return undefined
38
+ let live = true
39
+ infoOf(source.id, result.id, t.language).then(value => { if (live && !value.error) setInfo(value) })
40
+ return () => { live = false }
41
+ }, [source.id, result.id, needInfo])
42
+
43
+ const episodes = result.episodes ?? info?.episodes ?? null
44
+ const shown = { ...result, ...(info ?? {}), episodes, cover: result.cover ?? info?.cover }
45
+
46
+ /** One request at a time per result: a second click while one is on its way does nothing. */
47
+ const fetchIt = async ({ watch, all = false }) => {
48
+ if (submitting.current) return undefined
49
+ submitting.current = true
50
+ setState({ step: watch ? 'opening' : 'saving' })
51
+ const by = await displayName(t('guest'))
52
+ const answer = await asPerson('fetch', { source: source.id, id: result.id, watch, all, quality, language: t.language, by })
53
+ submitting.current = false
54
+ if (answer.error) return setState({ step: 'error', message: answer.error })
55
+ if (watch && answer.room) return onOpen(answer.room.id)
56
+ setState({ step: 'saved', all })
57
+ onSaved()
58
+ return undefined
59
+ }
60
+
61
+ const busy = state.step === 'opening' || state.step === 'saving'
62
+ let actions
63
+ if (state.step === 'confirm') {
64
+ actions = h(Confirm, {
65
+ t,
66
+ danger: false,
67
+ question: fill(t('search.saveAllQuestion'), { n: episodes, size: bytes(t, episodes * (EPISODE_BYTES[result.kind] ?? EPISODE_BYTES.drama)) }),
68
+ confirmLabel: t('search.saveAll'),
69
+ onCancel: () => setState({ step: 'idle' }),
70
+ onConfirm: () => fetchIt({ watch: false, all: true }),
71
+ })
72
+ } else if (busy) {
73
+ actions = h('span', { className: 'vsync-pending', role: 'status' }, h(Spinner), t(state.step === 'opening' ? 'search.opening' : 'search.saving'))
74
+ } else if (state.step === 'saved' && known.show === null) {
75
+ actions = h('span', { className: 'vsync-pending' }, t(state.all ? 'search.savedAll' : 'search.saved'))
76
+ } else if (known.show !== null) {
77
+ // Already here: say so, and offer what makes sense for it instead of saving it again.
78
+ const { show, room } = known
79
+ const resume = show.resume
80
+ actions = h(React.Fragment, null,
81
+ h('span', { className: 'vsync-badge vsync-badgeHere' }, t(show.pinned ? 'search.offline' : 'search.inLibrary')),
82
+ h(FollowButton, { t, source: source.id, work: result }),
83
+ !show.pinned && show.sourced && hasEpisodes(show.total) && show.episodes < show.total && h('button', { type: 'button', className: 'vsync-btn', title: t('search.saveAllHint'), onClick: () => setState({ step: 'confirm' }) }, t('search.saveAll')),
84
+ room !== null
85
+ ? h('button', { type: 'button', className: 'vsync-btn vsync-primary', onClick: () => onOpen(room.id) }, t('search.joinRoom'))
86
+ : h('button', { type: 'button', className: 'vsync-btn vsync-primary', onClick: () => fetchIt({ watch: true }) }, resume ? resumeLabel(t, { count: show.total ?? show.episodes, n: resume.index + 1, position: resume.position, at: clock(resume.position) }) : t('search.open')))
87
+ } else {
88
+ actions = h(React.Fragment, null,
89
+ result.account && h('span', { className: 'vsync-account', title: t('link.accountHint') }, fill(t('link.account'), { name: result.account.name })),
90
+ qualities.length > 1 && h(QualityPicker, { t, qualities, value: quality, onChange: setQuality }),
91
+ h(FollowButton, { t, source: source.id, work: result }),
92
+ hasEpisodes(result.episodes) && h('button', { type: 'button', className: 'vsync-btn', disabled: episodes === null, title: t('search.saveAllHint'), onClick: () => setState({ step: 'confirm' }) }, t('search.saveAll')),
93
+ h('button', { type: 'button', className: 'vsync-btn', title: fill(t('search.saveHint'), { n: WINDOW_EPISODES }), onClick: () => fetchIt({ watch: false }) }, t('search.save')),
94
+ h('button', { type: 'button', className: 'vsync-btn vsync-primary', onClick: () => fetchIt({ watch: true }) }, t('search.watch')))
95
+ }
96
+
97
+ return h('li', { className: 'vsync-card' },
98
+ h(Cover, { result: shown }),
99
+ h('div', { className: 'vsync-cardBody' },
100
+ h('div', { className: 'vsync-cardHead' },
101
+ h('span', { className: 'vsync-rowTitle' }, result.title),
102
+ result.relation && h('span', { className: 'vsync-badge' }, t(`relation.${result.relation}`)),
103
+ result.score && h('span', { className: 'vsync-score' }, fill(t('search.score'), { score: result.score.toFixed(1) }))),
104
+ h('span', { className: 'vsync-rowMeta' }, glance(t, shown).map((part, n) => h('span', { key: n }, part))),
105
+ result.tags.length > 0 && h('span', { className: 'vsync-tags' }, result.tags.slice(0, 6).map(tag => h('span', { key: tag, className: 'vsync-tag' }, tag))),
106
+ result.blurb && !open && h('span', { className: 'vsync-blurb' }, result.blurb),
107
+ open && h(WorkDetails, { t, info, source: source.id, onFocus }),
108
+ state.step === 'error' && h('span', { className: 'vsync-error', role: 'alert' }, state.message),
109
+ h('div', { className: 'vsync-cardFoot' },
110
+ h('button', { type: 'button', className: 'vsync-metaButton vsync-detailsToggle', 'aria-expanded': String(open), onClick: () => setOpen(!open) }, h(Icon.Chevron, { size: 12, open }), ' ', t(open ? 'search.hideDetails' : 'search.details')),
111
+ h('span', { className: 'vsync-actions' },
112
+ h(ChatButton, { t, onClick: () => chatAbout({ title: result.title, lines: [glance(t, shown).join(' · '), result.blurb], context: { source: source.id, id: result.id, kind: result.kind } }) }),
113
+ actions))))
114
+ }
@@ -0,0 +1,188 @@
1
+ /**
2
+ * One room: the player, its episodes, who is watching, and who did what.
3
+ * The player and its sync live in player.js.
4
+ */
5
+ import { About, nextSeason } from './about-view.js'
6
+ import { AvatarStack } from './avatars.js'
7
+ import { Cover } from './details.js'
8
+ import { useKnownWork } from './known.js'
9
+ import { Confirm, Icon, ProgressBar, React, api, asPerson, base, captionText, clock, copyText, displayName, fill, h, post, progressFraction, progressText, roomLink, watchMark } from './ui.js'
10
+
11
+ const TOAST_MS = 4000
12
+ /** A wait shorter than this (a seek into what is already loaded) shows nothing. */
13
+ const WAIT_SHOWN_AFTER_MS = 600
14
+
15
+ function toastText(t, event) {
16
+ if (event.kind === 'joined' || event.kind === 'left') return fill(t(`toast.${event.kind}`), { name: event.name })
17
+ if (event.kind === 'error') return event.message
18
+ const { last, item } = event
19
+ const values = { name: last.by, time: clock(last.position), episode: item?.title ?? fill(t('room.episodeN'), { n: (last.index ?? 0) + 1 }), rate: last.rate, names: (last.skipped ?? []).join(', ') }
20
+ return fill(t(`toast.${last.op}`), values)
21
+ }
22
+
23
+ /**
24
+ * The waiting room, like Plex's: the room holds until everyone can play,
25
+ * each viewer listed as loading or ready; after a while anyone may start
26
+ * without those still loading.
27
+ */
28
+ function WaitPanel({ t, view, item, onSkip, onContinue }) {
29
+ const others = view.members.filter(member => member.clientId !== view.clientId && member.wait === 'loading')
30
+ const names = others.map(member => member.name).join(', ')
31
+ let title
32
+ if (item.status !== 'ready') title = progressText(t, item.progress)
33
+ else if (others.length > 0) title = fill(t('room.waitingFor'), { names })
34
+ else title = t('room.loading')
35
+ return h('div', { className: 'vsync-wait', role: 'status' },
36
+ h('p', { className: 'vsync-waitTitle' }, title),
37
+ item.status !== 'ready' && h(ProgressBar, { progress: item.progress }),
38
+ h('ul', { className: 'vsync-waitList' }, view.members.map(member => h('li', { key: member.clientId, className: 'vsync-waitMember', 'data-wait': member.wait },
39
+ member.wait === 'ready' ? h('span', { className: 'vsync-waitMark' }, h(Icon.Check, { size: 14 })) : h('span', { className: 'vsync-spinner', 'aria-hidden': 'true' }),
40
+ h('span', { className: 'vsync-waitName' }, member.clientId === view.clientId ? `${member.name} (${t('room.you')})` : member.name),
41
+ h('span', { className: 'vsync-waitState' }, t(`room.wait.${member.wait}`))))),
42
+ view.wait.tap && h('button', { type: 'button', className: 'vsync-btn vsync-primary', onClick: onContinue }, t('room.tapToContinue')),
43
+ view.wait.canSkip && others.length > 0 && view.wait.held && h('button', { type: 'button', className: 'vsync-btn', onClick: onSkip }, fill(t('room.startWithout'), { names })))
44
+ }
45
+
46
+ export function RoomView({ t, roomId, onLeave, onOpen }) {
47
+ const stage = React.useRef(null)
48
+ const session = React.useRef(null)
49
+ const [view, setView] = React.useState({ connection: 'connecting', room: null, members: [], needsGesture: false })
50
+ const [toasts, setToasts] = React.useState([])
51
+ const [copied, setCopied] = React.useState(false)
52
+ /** What the show's source told about its work, kept with the show (null: none, or not known yet). */
53
+ const [about, setAbout] = React.useState(null)
54
+ const [side, setSide] = React.useState('episodes')
55
+ const [seasonBusy, setSeasonBusy] = React.useState(false)
56
+
57
+ const toast = React.useCallback((text) => {
58
+ const id = Math.random()
59
+ setToasts(list => [...list.slice(-2), { id, text }])
60
+ setTimeout(() => setToasts(list => list.filter(item => item.id !== id)), TOAST_MS)
61
+ }, [])
62
+
63
+ React.useEffect(() => {
64
+ let cancelled = false
65
+ const start = async () => {
66
+ const [module, name] = await Promise.all([import('./player.js'), displayName(t('guest'))])
67
+ if (cancelled || stage.current === null) return
68
+ session.current = module.joinRoom({
69
+ base: base(),
70
+ roomId,
71
+ name,
72
+ language: t.language,
73
+ trackLabel: label => captionText(t, label),
74
+ stage: stage.current,
75
+ onUpdate: setView,
76
+ onEvent: event => toast(toastText(t, event)),
77
+ })
78
+ }
79
+ start().catch(error => toast(error.message))
80
+ return () => {
81
+ cancelled = true
82
+ session.current?.destroy()
83
+ session.current = null
84
+ }
85
+ }, [roomId])
86
+
87
+ React.useEffect(() => {
88
+ let live = true
89
+ api(`rooms/${encodeURIComponent(roomId)}/work`).then((answer) => { if (live && answer.work) setAbout(answer) })
90
+ return () => { live = false }
91
+ }, [roomId])
92
+
93
+ const room = view.room
94
+ const item = room?.items[room.index]
95
+ const copy = async () => {
96
+ if (await copyText(roomLink(roomId), t('room.copy'))) {
97
+ setCopied(true)
98
+ setTimeout(() => setCopied(false), 2000)
99
+ }
100
+ }
101
+ /** Someone watching alone opens the room to others where it stands, and gets its link to send. */
102
+ const together = async () => {
103
+ const answer = await post(`rooms/${encodeURIComponent(roomId)}/together`, {})
104
+ if (answer.error) return toast(answer.error)
105
+ if (await copyText(roomLink(roomId), t('room.copy'))) toast(t('room.togetherCopied'))
106
+ return undefined
107
+ }
108
+ const [closing, setClosing] = React.useState(false)
109
+ const close = async () => {
110
+ await api(`rooms/${encodeURIComponent(roomId)}`, { method: 'DELETE' })
111
+ onLeave()
112
+ }
113
+
114
+ const season = about ? nextSeason(about.work) : null
115
+ const seasonKnown = useKnownWork(about?.source, season?.id)
116
+ const watchSeason = async () => {
117
+ if (seasonKnown.room !== null) return onOpen(seasonKnown.room.id)
118
+ setSeasonBusy(true)
119
+ const answer = await asPerson('fetch', { source: about.source, id: season.id, watch: true, all: false, language: t.language, by: await displayName(t('guest')) })
120
+ setSeasonBusy(false)
121
+ if (answer.error) return toast(answer.error)
122
+ return onOpen(answer.room.id)
123
+ }
124
+
125
+ let overlay = null
126
+ if (view.connection === 'closed') overlay = h('p', null, t('room.closed'))
127
+ else if (item?.status === 'failed') overlay = h('p', null, item.reason ? t(`error.${item.reason}`) : t('room.failed'))
128
+ else if (item && view.wait && (item.status !== 'ready' || view.wait.tap || (view.wait.held && view.wait.age >= WAIT_SHOWN_AFTER_MS))) overlay = h(WaitPanel, { t, view, item, onSkip: () => session.current?.skip(), onContinue: () => session.current?.continueLoading() })
129
+ else if (item?.status === 'preparing' || item?.status === 'remote') overlay = h('div', { className: 'vsync-preparing', role: 'status' }, h('p', null, progressText(t, item.progress)), h(ProgressBar, { progress: item.progress }))
130
+ else if (view.needsGesture) overlay = h('button', { type: 'button', className: 'vsync-btn vsync-btnLarge vsync-primary', onClick: () => session.current?.unlock() }, t('room.tapToJoin'))
131
+ else if (room === null) overlay = h('p', null, t('room.connecting'))
132
+
133
+ return h(React.Fragment, null,
134
+ h('div', { className: 'vsync-bar' },
135
+ h('button', { type: 'button', className: 'vsync-icon', 'aria-label': t('room.back'), title: t('room.back'), onClick: onLeave }, h(Icon.Back)),
136
+ about && h('span', { className: 'vsync-barCover' }, h(Cover, { result: about.work, small: true })),
137
+ h('div', { className: 'vsync-barTitle' },
138
+ h('strong', null, room?.title ?? ''),
139
+ room && room.items.length > 1 && item && h('span', null, item.title ?? fill(t('room.episodeN'), { n: room.index + 1 }))),
140
+ view.connection === 'reconnecting' && h('span', { className: 'vsync-status', role: 'status' }, t('room.reconnecting')),
141
+ room && !room.together && h('button', { type: 'button', className: 'vsync-btn', onClick: together }, h(Icon.Link), t('room.watchTogether')),
142
+ room?.together && h('div', { className: 'vsync-members', 'aria-label': t('room.viewers') }, h(AvatarStack, {
143
+ t,
144
+ members: view.members.map(member => ({ key: member.clientId, name: member.name, self: member.clientId === view.clientId, state: member.wait ? t(`room.wait.${member.wait}`) : t(room?.playing ? 'room.state.playing' : 'room.state.paused') })),
145
+ })),
146
+ closing
147
+ ? h(Confirm, { t, question: t('room.closeConfirm'), confirmLabel: t('room.close'), onCancel: () => setClosing(false), onConfirm: close })
148
+ : h(React.Fragment, null,
149
+ room?.together && h('button', { type: 'button', className: 'vsync-icon', 'aria-label': copied ? t('room.copied') : t('room.copy'), title: copied ? t('room.copied') : t('room.copy'), onClick: copy }, h(Icon.Link)),
150
+ h('button', { type: 'button', className: 'vsync-icon', 'aria-label': t('room.close'), title: t('room.close'), onClick: () => setClosing(true) }, h(Icon.Close)))),
151
+ h('div', { className: 'vsync-body' },
152
+ h('div', { className: 'vsync-stageWrap' },
153
+ h('div', { className: 'vsync-stage', ref: stage }),
154
+ overlay && h('div', { className: 'vsync-overlay' }, overlay),
155
+ h('div', { className: 'vsync-toasts', role: 'status', 'aria-live': 'polite' }, toasts.map(item => h('span', { key: item.id, className: 'vsync-toast' }, item.text)))),
156
+ room && (room.items.length > 1 || about) && h('aside', { className: 'vsync-episodes', 'aria-label': t('room.episodes') },
157
+ about && room.items.length > 1 && h('div', { className: 'vsync-sideTabs', role: 'tablist' },
158
+ ['episodes', 'about'].map(tab => h('button', { key: tab, type: 'button', role: 'tab', className: 'vsync-chip', 'aria-selected': String(side === tab), onClick: () => setSide(tab) }, t(`room.tab.${tab}`)))),
159
+ (side === 'about' || room.items.length === 1) && about
160
+ ? h(About, { t, work: about.work, source: about.source, workId: about.id })
161
+ : h(React.Fragment, null,
162
+ !about && h('h2', null, t('room.episodes')),
163
+ h('ol', { className: 'vsync-episodeList' }, room.items.map((episode, index) => {
164
+ const mark = watchMark(t, episode.watch, index === room.index)
165
+ const title = episode.title ?? fill(t('room.episodeN'), { n: index + 1 })
166
+ return h('li', { key: index },
167
+ h('button', {
168
+ type: 'button',
169
+ className: 'vsync-episode',
170
+ 'aria-current': String(index === room.index),
171
+ 'data-watch': mark.state,
172
+ 'data-cached': String(episode.cached),
173
+ title: episode.cached ? undefined : t('room.notCached'),
174
+ disabled: episode.status === 'failed' && episode.cached,
175
+ onClick: () => session.current?.select(index),
176
+ },
177
+ h('span', { className: 'vsync-episodeNo' }, index + 1),
178
+ h('span', { className: 'vsync-episodeMain' },
179
+ h('span', { className: 'vsync-episodeTitle' }, title),
180
+ mark.bar),
181
+ episode.status === 'preparing'
182
+ ? h('span', { className: 'vsync-episodeState' }, progressFraction(episode.progress) === null ? '…' : `${Math.floor(progressFraction(episode.progress) * 100)}%`)
183
+ : mark.note))
184
+ })),
185
+ season && h('div', { className: 'vsync-nextSeason', 'data-last': String(room.index === room.items.length - 1) },
186
+ h('span', { className: 'vsync-nextSeasonText' }, fill(t('room.nextSeason'), { title: season.title })),
187
+ h('button', { type: 'button', className: 'vsync-btn vsync-primary', disabled: seasonBusy, onClick: watchSeason }, seasonBusy ? t('search.opening') : seasonKnown.room !== null ? t('search.joinRoom') : seasonKnown.show !== null ? t(seasonKnown.show.resume ? 'search.continue' : 'search.open') : t('search.watch')))))))
188
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Open rooms: who is in each, which episode, and joining, copying the
3
+ * link or closing it from the list.
4
+ */
5
+ import { AvatarStack } from './avatars.js'
6
+ import { Picture } from './details.js'
7
+ import { Btn, Confirm, Icon, K, P, api, copyText, fill, h, React, roomLink, time } from './ui.js'
8
+
9
+ function meta(t, room) {
10
+ const parts = []
11
+ if (room.episodes > 1) parts.push(fill(t('rooms.episode'), { n: room.index + 1, total: room.episodes }))
12
+ if (room.episodes > 1 && room.current && room.current !== room.title) parts.push(room.current)
13
+ if (room.members.length === 0) {
14
+ if (room.emptySince) parts.push(fill(t('rooms.emptySince'), { time: time(t, room.emptySince) }))
15
+ else if (room.opened === false) parts.push(t('rooms.unopened'))
16
+ }
17
+ if (room.preparing > 0) parts.push(fill(t('rooms.preparing'), { n: room.preparing }))
18
+ parts.push(fill(t('rooms.openedBy'), { name: room.createdBy || t('assistant') }))
19
+ return parts
20
+ }
21
+
22
+ function RoomRow({ t, room, onOpen, onChanged }) {
23
+ const [closing, setClosing] = React.useState(false)
24
+ const [copied, setCopied] = React.useState(false)
25
+ const copy = async () => {
26
+ if (await copyText(roomLink(room.id), t('room.copy'))) {
27
+ setCopied(true)
28
+ setTimeout(() => setCopied(false), 2000)
29
+ }
30
+ }
31
+ const share = room.duration > 0 ? Math.min(1, Math.max(0, room.position / room.duration)) : null
32
+ return h(K.Surface, { as: 'li', className: 'vsync-row vsync-roomCard' },
33
+ h(Picture, { pictures: [room.frame, room.cover], className: 'vsync-preview', emptyClassName: 'vsync-glyph', icon: h(Icon.Film) }),
34
+ h('span', { className: 'vsync-rowText' },
35
+ h('span', { className: 'vsync-rowTitle' }, room.title),
36
+ h('span', { className: 'vsync-rowMeta' },
37
+ room.members.length > 0 && h('span', { key: 'who', className: 'vsync-roomWho' }, h(AvatarStack, { t, members: room.members.map(name => ({ name })) })),
38
+ meta(t, room).map((part, n) => h('span', { key: n }, part))),
39
+ share !== null && h('span', { className: 'vsync-watchBar vsync-roomBar', 'aria-hidden': true }, h('span', { style: { width: `${Math.max(2, share * 100)}%` } }))),
40
+ closing
41
+ ? h(Confirm, {
42
+ t,
43
+ question: room.members.length > 0 ? fill(t('rooms.closeQuestionBusy'), { names: room.members.join(', ') }) : t('rooms.closeQuestion'),
44
+ confirmLabel: t('room.close'),
45
+ onCancel: () => setClosing(false),
46
+ onConfirm: async () => {
47
+ await api(`rooms/${encodeURIComponent(room.id)}`, { method: 'DELETE' })
48
+ setClosing(false)
49
+ onChanged()
50
+ },
51
+ })
52
+ : h('span', { className: 'vsync-actions' },
53
+ h(Btn, { variant: 'ghost', 'aria-label': copied ? t('room.copied') : t('room.copy'), title: copied ? t('room.copied') : t('room.copy'), onClick: copy, icon: h(P.IconLinkOutlineRegular, { size: 16 }) }),
54
+ h(Btn, { variant: 'ghost', 'aria-label': t('room.close'), title: t('room.close'), onClick: () => setClosing(true), icon: h(P.IconCloseOutlineRegular, { size: 16 }) }),
55
+ h(Btn, { onClick: () => onOpen(room.id) }, t('rooms.join'))))
56
+ }
57
+
58
+ /** The shared rooms; nothing while there are none (the Continue card says what can be started). */
59
+ export function RoomsSection({ t, rooms, onOpen, onChanged }) {
60
+ if (rooms === undefined || rooms.length === 0) return null
61
+ return h('section', { className: 'vsync-section', 'aria-labelledby': 'vsync-rooms' },
62
+ h('h2', { id: 'vsync-rooms' }, t('rooms.heading')),
63
+ h('ul', { className: 'vsync-cards' }, rooms.map(room => h(RoomRow, { key: room.id, t, room, onOpen, onChanged }))))
64
+ }
package/web/sort.js ADDED
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Sorting a list of search results by what the results carry: how many
3
+ * played it, when it was last updated. The source's own order stays the
4
+ * default. Pure.
5
+ */
6
+
7
+ /** The date a result says it was updated (its `updated` fact), as a time, or null. */
8
+ export function updatedAt(result) {
9
+ const text = (result.meta ?? []).find(row => row.key === 'updated')?.value
10
+ const time = text ? Date.parse(String(text).replace(/\./g, '-')) : NaN
11
+ return Number.isFinite(time) ? time : null
12
+ }
13
+
14
+ /** The orders worth offering for these results: the default, and the ones at least two results can be told apart by. */
15
+ export function sortModes(results) {
16
+ const modes = ['default']
17
+ if (results.filter(result => result.popularity?.count > 0).length > 1) modes.push('plays')
18
+ if (results.filter(result => updatedAt(result) !== null).length > 1) modes.push('newest')
19
+ return modes
20
+ }
21
+
22
+ /** The results in an order; ones without the value go last, and ties keep the source's order. */
23
+ export function sortResults(results, mode) {
24
+ const key = { plays: result => result.popularity?.count ?? null, newest: updatedAt }[mode]
25
+ if (key === undefined) return results
26
+ return results
27
+ .map((result, n) => ({ result, n, value: key(result) }))
28
+ .sort((a, b) => (b.value ?? -Infinity) - (a.value ?? -Infinity) || a.n - b.n)
29
+ .map(entry => entry.result)
30
+ }