/** * SPDX-License-Identifier: AGPL-3.0-or-later * Adapted 2026-10-25 from Onliine (Copyright (C) 2024 José Enrique), * bd3bd968b1a4b36988c174d50b0f3253de45c283/index.html (channel selection), * and iu5dm/ourapi 2b3f750631ad435a1583fff17d788678baebb598 (channel cycling). * Changes: native DOM, accessible dialog, rendered Astro content, reduced motion, * synthesized sound, no iframe, account service or third-party media. * Full source and notices: /channels/source/ . License: /channels/COPYING.txt . */ import { createInterfaceSound } from './interface-sound'; const CLOCK_REFRESH_MS = 30_000; function initializeConsole(root: HTMLElement) { const find = (selector: string): T => { const element = root.querySelector(selector); if (!element) throw new Error(`Channel console element is missing: ${selector}`); return element; }; const cards = Array.from(root.querySelectorAll('[data-channel]')); const channels = new Map(cards.map((card) => [card.dataset.channel, card])); const readers = new Map(Array.from(root.querySelectorAll('[data-reader]')).map((reader) => [reader.dataset.reader, reader])); const grid = find('[data-channel-grid]'); const dialog = find('[data-channel-dialog]'); const preview = find('[data-preview]'); const previewArt = find('[data-preview-art]'); const reading = find('[data-reading]'); const readingScroll = find('[data-reading-scroll]'); const start = find('[data-start]'); const menu = find('[data-return-menu]'); const permalink = find('[data-permalink]'); const soundToggle = find('[data-console-sound]'); const motionToggle = find('[data-console-motion]'); const status = find('[data-console-status]'); const curtain = find('.launch-curtain'); const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)'); const playSound = createInterfaceSound(); let selected: HTMLButtonElement | null = null; let view: 'preview' | 'reading' = 'preview'; let launching = false; let motion = !reducedMotion.matches; let sound = false; let curtainAnimation: Animation | undefined; function setLaunching(value: boolean) { launching = value; start.disabled = value; menu.disabled = value; if (value) dialog.setAttribute('aria-busy', 'true'); else dialog.removeAttribute('aria-busy'); } function beep(frequency: number) { if (!sound) return; void playSound(frequency).catch((error: unknown) => { sound = false; soundToggle.setAttribute('aria-pressed', 'false'); soundToggle.setAttribute('aria-label', '声音:关'); status.textContent = '提示音播放失败,请检查浏览器音频设置。'; console.error('Channel console audio failed:', error); }); } function renderMotion() { root.dataset.motion = motion ? 'on' : 'off'; motionToggle.setAttribute('aria-pressed', String(motion)); motionToggle.textContent = `动效:${motion ? '开' : '关'}`; if (!motion) { curtainAnimation?.finish(); root.classList.remove('channel-returning'); } } function showPreview() { pauseReaderMedia(); view = 'preview'; dialog.dataset.view = view; preview.hidden = false; reading.hidden = true; start.hidden = false; if (dialog.open) start.focus({ preventScroll: true }); } function pauseReaderMedia() { reading.querySelectorAll('video, audio').forEach((media) => media.pause()); } function selectChannel(card: HTMLButtonElement) { selected = card; const art = card.querySelector('.channel-art'); if (!art) throw new Error('Selected channel has no artwork.'); previewArt.replaceChildren(art.cloneNode(true)); find('[data-preview-title]').textContent = card.dataset.title ?? ''; find('[data-preview-description]').textContent = card.dataset.description ?? ''; const startLabel = card.dataset.startLabel; if (!startLabel) throw new Error('Selected channel has no start label.'); start.replaceChildren(document.createTextNode(startLabel + ' ')); const triangle = document.createElement('span'); triangle.textContent = '▶'; triangle.setAttribute('aria-hidden', 'true'); start.append(triangle); showPreview(); if (!dialog.open) { // Adapted from Onliine: zoom from the selected tile's center. const tileBounds = card.getBoundingClientRect(); const gridBounds = grid.getBoundingClientRect(); grid.style.transformOrigin = `${tileBounds.left - gridBounds.left + tileBounds.width / 2}px ${tileBounds.top - gridBounds.top + tileBounds.height / 2}px`; dialog.style.setProperty('--preview-origin-x', `${(tileBounds.left + tileBounds.width / 2) / innerWidth * 100}%`); dialog.style.setProperty('--preview-origin-y', `${(tileBounds.top + tileBounds.height / 2) / innerHeight * 100}%`); root.classList.remove('channel-returning'); root.classList.add('channel-is-selected'); dialog.showModal(); start.focus({ preventScroll: true }); } beep(520); } function cycleChannel(direction: number) { if (!selected || launching || view !== 'preview') return; const index = cards.indexOf(selected); selectChannel(cards[(index + direction + cards.length) % cards.length]); } async function fadeCurtain(covered: boolean) { if (!motion) { curtain.style.opacity = covered ? '1' : '0'; return; } curtainAnimation = curtain.animate([{ opacity: covered ? 0 : 1 }, { opacity: covered ? 1 : 0 }], { duration: covered ? 160 : 220, easing: 'ease-out', fill: 'forwards' }); await curtainAnimation.finished; curtain.style.opacity = covered ? '1' : '0'; curtainAnimation.cancel(); curtainAnimation = undefined; } async function startSelected() { if (!selected || launching) return; const card = selected; const target = card.dataset.target; if (!target) throw new Error('Selected channel has no destination.'); const reader = readers.get(card.dataset.channel); if (card.dataset.kind !== 'link' && !reader) throw new Error('Selected channel has no reading page.'); setLaunching(true); beep(760); await fadeCurtain(true); if (card.dataset.kind === 'link') { location.assign(target); return; } readers.forEach((entry) => { entry.hidden = entry !== reader; }); view = 'reading'; dialog.dataset.view = view; preview.hidden = true; reading.hidden = false; start.hidden = true; permalink.href = target; readingScroll.scrollTop = 0; reader?.querySelector('h2')?.focus({ preventScroll: true }); await fadeCurtain(false); setLaunching(false); } function startFromButton() { void startSelected().catch((error: unknown) => { setLaunching(false); curtainAnimation?.cancel(); curtainAnimation = undefined; curtain.style.opacity = '0'; status.textContent = '频道启动失败,请关闭窗口后重试。'; console.error('Channel launch failed:', error); }); } cards.forEach((card) => card.addEventListener('click', () => selectChannel(card))); find('[data-previous]').addEventListener('click', () => cycleChannel(-1)); find('[data-next]').addEventListener('click', () => cycleChannel(1)); start.addEventListener('click', startFromButton); menu.addEventListener('click', () => dialog.close()); find('[data-back-preview]').addEventListener('click', () => { showPreview(); beep(350); }); dialog.addEventListener('cancel', (event) => { if (launching) { event.preventDefault(); return; } if (view === 'reading') { event.preventDefault(); showPreview(); beep(350); } }); dialog.addEventListener('keydown', (event) => { if (view !== 'preview' || event.altKey || event.ctrlKey || event.metaKey) return; if (event.key === 'ArrowLeft') { event.preventDefault(); cycleChannel(-1); } if (event.key === 'ArrowRight') { event.preventDefault(); cycleChannel(1); } }); dialog.addEventListener('close', () => { pauseReaderMedia(); root.classList.remove('channel-is-selected'); const bounds = selected?.getBoundingClientRect(); const outsideViewport = bounds && (bounds.top < 0 || bounds.bottom > innerHeight || bounds.left < 0 || bounds.right > innerWidth); // A newly selected off-screen tile must be visible before restoring focus. if (motion && !outsideViewport) root.classList.add('channel-returning'); if (outsideViewport) selected?.scrollIntoView({ block: 'nearest', behavior: 'instant' }); selected?.focus({ preventScroll: true }); beep(350); }); window.addEventListener('pageshow', (event) => { if (!event.persisted) return; setLaunching(false); curtainAnimation?.cancel(); curtainAnimation = undefined; curtain.style.opacity = '0'; if (dialog.open) showPreview(); }); grid.addEventListener('animationend', (event) => { if (event.animationName === 'channel-menu-return') root.classList.remove('channel-returning'); }); root.querySelectorAll('[data-open-article]').forEach((link) => { link.addEventListener('click', (event) => { if (event.button !== 0 || event.altKey || event.metaKey || event.ctrlKey || event.shiftKey) return; const card = channels.get(link.dataset.openArticle); if (!card) return; // Unfeatured notes keep their ordinary article URLs. event.preventDefault(); selectChannel(card); startFromButton(); }); }); motionToggle.addEventListener('click', () => { motion = !motion; renderMotion(); }); reducedMotion.addEventListener('change', (event) => { if (event.matches) { motion = false; renderMotion(); } }); if (typeof AudioContext === 'undefined') { soundToggle.disabled = true; soundToggle.setAttribute('aria-label', '此浏览器不支持提示音'); } else { soundToggle.addEventListener('click', () => { sound = !sound; soundToggle.setAttribute('aria-pressed', String(sound)); soundToggle.setAttribute('aria-label', `声音:${sound ? '开' : '关'}`); beep(680); }); } function updateClock() { const now = new Date(); const clock = find('[data-console-clock]'); clock.dateTime = now.toISOString(); clock.textContent = new Intl.DateTimeFormat('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false }).format(now); find('[data-console-date]').textContent = new Intl.DateTimeFormat('zh-CN', { month: 'long', day: 'numeric', weekday: 'short' }).format(now); } updateClock(); setInterval(updateClock, CLOCK_REFRESH_MS); renderMotion(); } const consoleRoot = document.querySelector('[data-channel-console]'); if (consoleRoot) initializeConsole(consoleRoot);