ChannelSidebar.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. 'use client';
  2. import './style.scss';
  3. import { useEffect, useState, useCallback } from 'react';
  4. import Image from 'next/image';
  5. import { useRouter } from 'next/navigation';
  6. import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
  7. import { faSun, faMoon, faGlobe, faBookmark, faAnglesLeft, faAnglesRight, faEllipsis } from '@fortawesome/free-solid-svg-icons';
  8. import { useSignalRContext } from '@/contexts/signalrProvider';
  9. import { ChannelListItem, ChannelStatusUpdate } from '@/types/channel';
  10. import { buildChannelUrl, buildWatchUrl, formatHandle } from '@/lib/utils/channel';
  11. import useTheme from '@/hooks/useTheme';
  12. const STORAGE_KEY = 'antooza-sidebar-collapsed';
  13. const PAGE_SIZE = 10;
  14. const WIDTH_EXPANDED = '220px';
  15. const WIDTH_COLLAPSED = '64px';
  16. const THUMB_PLACEHOLDER = '/resources/no-image.png';
  17. // 뷰포트 높이 기반 최초 표시 채널 수 계산용 상수
  18. // 채널 아이템 1개 ≒ padding 10px*2 + thumb 36px = 56px
  19. // 헤더(약 60) + 푸터(약 70) + "더 보기" 버튼(약 46) ≒ 180px 예약
  20. const ITEM_HEIGHT_PX = 56;
  21. const RESERVED_HEIGHT_PX = 180;
  22. function computeInitialVisible(): number
  23. {
  24. if (typeof window === 'undefined') {
  25. return PAGE_SIZE;
  26. }
  27. const available = window.innerHeight - RESERVED_HEIGHT_PX;
  28. const fit = Math.floor(available / ITEM_HEIGHT_PX);
  29. return Math.max(PAGE_SIZE, fit);
  30. }
  31. type Props = {
  32. initialChannels?: ChannelListItem[];
  33. };
  34. export default function ChannelSidebar({ initialChannels }: Props)
  35. {
  36. const sortChannels = useCallback((list: ChannelListItem[]) => {
  37. return [...list].sort((a, b) => {
  38. if (a.isLive && !b.isLive) {
  39. return -1;
  40. }
  41. if (!a.isLive && b.isLive) {
  42. return 1;
  43. }
  44. if (a.isLive && b.isLive) {
  45. return b.viewerCount - a.viewerCount;
  46. }
  47. // 비라이브: 서버가 반환한 random 순서 유지 (_offlineRank 는 로드 시점 index 부여)
  48. return (a._offlineRank ?? 0) - (b._offlineRank ?? 0);
  49. });
  50. }, []);
  51. const [channels, setChannels] = useState<ChannelListItem[]>(() => sortChannels(initialChannels ?? []));
  52. const [langOpen, setLangOpen] = useState(false);
  53. const [collapsed, setCollapsed] = useState(false);
  54. const [visibleCount, setVisibleCount] = useState<number>(PAGE_SIZE);
  55. const router = useRouter();
  56. // ChannelStatusBroadcaster 는 AppHub 의 channel:{sid} 그룹으로 송출하므로 appConnection 사용 필수.
  57. // (ChatHub 를 쓰면 그룹 키(chat:channel:{sid}) 불일치로 ReceiveChannelStatus 가 영영 안 옴 + 채팅 입장 메시지 도배)
  58. const { appConnection } = useSignalRContext();
  59. const { toggleTheme, isDark } = useTheme();
  60. // 최초 mount 시 localStorage에서 collapsed 상태 복원
  61. useEffect(() => {
  62. try {
  63. const saved = window.localStorage.getItem(STORAGE_KEY);
  64. if (saved === 'true') {
  65. setCollapsed(true);
  66. }
  67. } catch {}
  68. }, []);
  69. // 뷰포트 높이에 따라 최초 표시 채널 수 계산 — 4K/8K 등 세로가 긴 화면에서 더 많은 채널을 한번에 표시
  70. // 사용자가 "더 보기" 를 눌러 늘려놓은 경우 줄어들지 않도록 max 로 갱신
  71. useEffect(() => {
  72. const apply = () => {
  73. const next = computeInitialVisible();
  74. setVisibleCount(prev => Math.max(prev, next));
  75. };
  76. apply();
  77. window.addEventListener('resize', apply);
  78. return () => {
  79. window.removeEventListener('resize', apply);
  80. };
  81. }, []);
  82. // collapsed 변경 시 html 루트의 CSS variable + 클래스 동기화 (layout grid가 반응)
  83. useEffect(() => {
  84. const root = document.documentElement;
  85. root.style.setProperty('--antooza-sidebar-width', collapsed ? WIDTH_COLLAPSED : WIDTH_EXPANDED);
  86. root.classList.toggle('antooza-sidebar-collapsed', collapsed);
  87. try {
  88. window.localStorage.setItem(STORAGE_KEY, String(collapsed));
  89. } catch {}
  90. return () => {
  91. // unmount 시 원복 (전체 앱 재사용성 보장)
  92. root.style.removeProperty('--antooza-sidebar-width');
  93. root.classList.remove('antooza-sidebar-collapsed');
  94. };
  95. }, [collapsed]);
  96. // SignalR: 채널 상태 실시간 업데이트 (AppHub.ReceiveChannelStatus)
  97. useEffect(() => {
  98. if (!appConnection) {
  99. return;
  100. }
  101. const handler = (status: ChannelStatusUpdate) => {
  102. setChannels(prev => {
  103. const updated = prev.map(ch =>
  104. ch.channelSID === status.channelSID ? { ...ch, isLive: status.isLive, viewerCount: status.viewerCount, videoId: status.videoId } : ch
  105. );
  106. return sortChannels(updated);
  107. });
  108. };
  109. appConnection.on('ReceiveChannelStatus', handler);
  110. return () => {
  111. appConnection.off('ReceiveChannelStatus', handler);
  112. };
  113. }, [appConnection, sortChannels]);
  114. // ChannelStatusBroadcaster 가 AppHub 의 Clients.Group("channel:{sid}") 로 송출 → AppHub.JoinChannel 로 그룹 가입.
  115. // AppHub.JoinChannel 은 순수 그룹 가입만 수행 (사이드이펙트 없음).
  116. // SID 목록 변경 또는 재연결 시 다시 가입.
  117. const channelSidsKey = channels.map(c => c.channelSID).join(',');
  118. useEffect(() => {
  119. if (!appConnection) {
  120. return;
  121. }
  122. const sids = channelSidsKey ? channelSidsKey.split(',') : [];
  123. if (sids.length === 0) {
  124. return;
  125. }
  126. const joinAll = async () => {
  127. if (appConnection.state !== 'Connected') {
  128. return;
  129. }
  130. for (const sid of sids) {
  131. try {
  132. await appConnection.invoke('JoinChannel', sid);
  133. } catch (err) {
  134. console.warn('[ChannelSidebar] JoinChannel 실패:', sid, err);
  135. }
  136. }
  137. };
  138. joinAll();
  139. appConnection.onreconnected(joinAll);
  140. return () => {
  141. if (appConnection.state !== 'Connected') {
  142. return;
  143. }
  144. for (const sid of sids) {
  145. appConnection.invoke('LeaveChannel', sid).catch(() => {});
  146. }
  147. };
  148. }, [appConnection, channelSidsKey]);
  149. const handleClick = (ch: ChannelListItem) => {
  150. if (ch.isLive && ch.videoId) {
  151. router.push(buildWatchUrl(ch));
  152. } else {
  153. router.push(buildChannelUrl(ch));
  154. }
  155. };
  156. const formatCount = (n: number) => {
  157. if (n >= 10000) {
  158. return `${(n / 10000).toFixed(1)}만`;
  159. }
  160. if (n >= 1000) {
  161. return `${(n / 1000).toFixed(1)}K`;
  162. }
  163. return n.toString();
  164. };
  165. const getThumbnailUrl = (ch: ChannelListItem) => {
  166. if (ch.thumbnailUrl) {
  167. return ch.thumbnailUrl;
  168. }
  169. // YouTube 채널 ID 를 `/a/` 경로에 끼워넣은 fallback 은 항상 400 (해당 path 는 Google 계정 아바타 토큰용)
  170. // → 로컬 placeholder 로 안전 대체. 실제 채널 썸네일은 YouTube Data API 동기화로 채워야 함.
  171. return THUMB_PLACEHOLDER;
  172. };
  173. const handleToggleCollapse = useCallback(() => {
  174. setCollapsed(prev => !prev);
  175. setLangOpen(false);
  176. }, []);
  177. const handleShowMore = useCallback(() => {
  178. setVisibleCount(prev => prev + PAGE_SIZE);
  179. }, []);
  180. const visibleChannels = channels.slice(0, visibleCount);
  181. const hasMore = channels.length > visibleCount;
  182. return (
  183. <div className={`channel-sidebar${collapsed ? ' channel-sidebar--collapsed' : ''}`}>
  184. {/* 헤더 */}
  185. <div className="channel-sidebar__header">
  186. {!collapsed && <span className="channel-sidebar__header-title">생방송 채널</span>}
  187. <button
  188. type="button"
  189. className="channel-sidebar__collapse-btn"
  190. onClick={handleToggleCollapse}
  191. aria-label={collapsed ? '사이드바 펼치기' : '사이드바 접기'}
  192. aria-expanded={!collapsed}
  193. title={collapsed ? '사이드바 펼치기' : '사이드바 접기'}
  194. >
  195. <FontAwesomeIcon icon={collapsed ? faAnglesRight : faAnglesLeft} />
  196. </button>
  197. </div>
  198. {/* 채널 목록 */}
  199. <div className="channel-sidebar__list">
  200. {channels.length === 0 && !collapsed && (
  201. <div className="channel-sidebar__empty">등록된 채널이 없습니다</div>
  202. )}
  203. {visibleChannels.map(ch => (
  204. <div
  205. key={ch.channelSID}
  206. className={`channel-sidebar__item${ch.isLive ? ' channel-sidebar__item--live' : ''}`}
  207. onClick={() => handleClick(ch)}
  208. role="button"
  209. tabIndex={0}
  210. aria-label={`${ch.name}${ch.isLive ? ` · 시청자 ${formatCount(ch.viewerCount)}` : ''}`}
  211. onKeyDown={(e) => {
  212. if (e.key === 'Enter' || e.key === ' ') {
  213. e.preventDefault();
  214. handleClick(ch);
  215. }
  216. }}
  217. title={collapsed ? `${ch.name}${ch.isLive ? ` · 시청자 ${formatCount(ch.viewerCount)}` : ''}` : undefined}
  218. >
  219. <div className="channel-sidebar__thumb">
  220. <Image src={getThumbnailUrl(ch)} alt={ch.name} width={36} height={36} unoptimized />
  221. {collapsed && ch.isLive && <span className="channel-sidebar__thumb-dot" aria-hidden="true" />}
  222. </div>
  223. {!collapsed && (
  224. <>
  225. <div className="channel-sidebar__info">
  226. <div className="channel-sidebar__name">{ch.name}</div>
  227. <div className="channel-sidebar__sub">
  228. {ch.subscriberCount > 0 ? `구독자 ${formatCount(ch.subscriberCount)}` : (ch.handle ? formatHandle(ch.handle) : '')}
  229. </div>
  230. </div>
  231. <div className="channel-sidebar__status">
  232. {ch.isLive && (
  233. <span className="channel-sidebar__viewers">{formatCount(ch.viewerCount)}</span>
  234. )}
  235. <span className={`channel-sidebar__led${ch.isLive ? ' channel-sidebar__led--on' : ''}`} />
  236. </div>
  237. </>
  238. )}
  239. </div>
  240. ))}
  241. {/* 더 보기 */}
  242. {hasMore && (
  243. <button
  244. type="button"
  245. className="channel-sidebar__more"
  246. onClick={handleShowMore}
  247. aria-label={`채널 ${PAGE_SIZE}개 더 보기`}
  248. title={collapsed ? '더 보기' : undefined}
  249. >
  250. {collapsed ? <FontAwesomeIcon icon={faEllipsis} /> : <span>더 보기</span>}
  251. </button>
  252. )}
  253. </div>
  254. {/* 하단: 다크모드 / 다국어 / 즐겨찾기 */}
  255. <div className="channel-sidebar__footer">
  256. {langOpen && !collapsed && (
  257. <div className="channel-sidebar__lang-dropdown">
  258. <button type="button" className="channel-sidebar__lang-option channel-sidebar__lang-option--active" onClick={() => setLangOpen(false)}>한국어</button>
  259. <button type="button" className="channel-sidebar__lang-option" onClick={() => setLangOpen(false)}>English</button>
  260. </div>
  261. )}
  262. <div className="channel-sidebar__footer-actions">
  263. <button type="button" className="channel-sidebar__icon-btn" onClick={toggleTheme} aria-label={isDark ? '라이트 모드' : '다크 모드'} title={isDark ? '라이트 모드' : '다크 모드'}>
  264. <FontAwesomeIcon icon={isDark ? faSun : faMoon} />
  265. </button>
  266. <button type="button" className="channel-sidebar__icon-btn" onClick={() => setLangOpen(prev => !prev)} aria-label="다국어" title="다국어">
  267. <FontAwesomeIcon icon={faGlobe} />
  268. </button>
  269. <button type="button" className="channel-sidebar__icon-btn" onClick={() => alert('Ctrl+D (Mac: ⌘+D)를 누르면 사이트를 즐겨찾기에 추가할 수 있습니다.')} aria-label="즐겨찾기" title="즐겨찾기">
  270. <FontAwesomeIcon icon={faBookmark} />
  271. </button>
  272. </div>
  273. </div>
  274. </div>
  275. );
  276. }