import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query' import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react' import regionPages from '../../seo/region.json' import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth' import { SITE_URL } from '../api/setup' import { addCommentMutation, agreeTermsMutation, blockAuthorMutation, deleteCommentMutation, getArticleOptions, getFeedQueryKey, getIndexOptions, getSeasonWeekOptions, likeCommentMutation, listCommentsInfiniteOptions, listBlockedOptions, listBlockedQueryKey, listCommentsInfiniteQueryKey, listRegionsOptions, meQueryKey, reportCommentMutation, unblockMutation, unlikeCommentMutation, updateMeMutation, withdrawMutation, } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import { AuthProvider, ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen' import { track } from '../lib/analytics' import { IS_TOSS, tossShare } from '../lib/platform' import { cx } from '../lib/utils' import { useAuth } from './authContext' import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib' import { GoogleButton } from './googleLogin' import { useInstall, useInstallable } from './install' import { InstallSheet } from './installBanner' import { ARTICLE_CAT, SHEET_OPEN_MS } from './lib' import { MixSheet } from './myGak' import { ownPage, useRegion } from './regionContext' import { WeatherWhySheet } from './weatherWhy' import { useSky } from './skyContext' import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage' import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext' import { HeartIcon } from './svg' import { MyTalks, TalkSheet } from './talk' import { Avatar, Ic, Skel, StateBox, TAP44, Thumb } from './ui' export function SheetProvider({ children }: { children: ReactNode }) { const [state, setState] = useState(null) // 창이 열려 있는 동안 방문 기록을 하나 쌓아 두어 뒤로 가기가 창만 닫게 한다 const pushed = useRef(false) const open = useCallback((s: Exclude) => { if (!pushed.current) { window.history.pushState({ ...window.history.state, sheet: true }, '') pushed.current = true } setState(s) }, []) const close = useCallback(() => { setState(null) if (!pushed.current) return pushed.current = false window.history.back() }, []) const api = useMemo(() => ({ open, close }), [open, close]) useEffect(() => { const onPop = () => { if (!pushed.current) return pushed.current = false setState(null) } window.addEventListener('popstate', onPop) return () => window.removeEventListener('popstate', onPop) }, []) // 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다 useEffect(() => subscribeAuth((reason) => reason === 'required' && open({ type: 'login' })), [open]) return ( {children} ) } const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기', install: '홈 화면에 추가', weatherWhy: '날씨 점수는 이렇게 나와요', talk: '이야기' } as const /** 아래에서 올라오는 창: 네이티브 라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) { const ref = useRef(null) const { kind } = useSky() const { open } = useSheet() const [gakTitle, setGakTitle] = useState('') const [articleTitle, setArticleTitle] = useState('') useEffect(() => { const el = ref.current if (!el) return if (state && !el.open) el.showModal() if (!state && el.open) el.close() }, [state]) // 창이 열려 있는 동안 뒤 페이지는 스크롤되지 않게 잠근다 const isOpen = state != null useEffect(() => { if (!isOpen) return const root = document.documentElement const before = root.style.overflow root.style.overflow = 'hidden' // 뒤 화면 움직임 멈추기는 페이지 전체 스타일을 다시 계산하게 해서, 창이 다 올라온 뒤에 한다 const pause = setTimeout(() => root.classList.add('b-sheet-open'), SHEET_OPEN_MS) return () => { clearTimeout(pause) root.style.overflow = before root.classList.remove('b-sheet-open') } }, [isOpen]) const then = state?.type === 'login' ? state.then : undefined const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : state.type === 'mix' ? (state.shared ? '받은 각' : '내 각 만들기') : TITLES[state.type] return ( { if (e.target === e.currentTarget) onClose() }} className="b-sheet-dialog b-app fixed inset-x-0 top-auto bottom-0 m-0 mx-auto max-h-[86dvh] w-full max-w-[440px] overflow-visible bg-transparent p-0 text-(--ink)" > {state && (
{state.type === 'gak' && } {state.type === 'article' && } {state.type === 'seasonWeek' && } {state.type === 'share' && } {state.type === 'comments' && } {state.type === 'login' && open(then) : onClose} />} {state.type === 'me' && } {state.type === 'region' && } {state.type === 'mix' && } {state.type === 'install' && } {state.type === 'weatherWhy' && } {state.type === 'talk' && }
)} {!state && }
) } function Body({ children, className }: { children: ReactNode; className?: string }) { return
{children}
} /** 문구를 모두 같은 칸에 겹쳐 두고 하나만 보인다: 대기 문구로 바뀌어도 버튼 크기가 그대로다 */ function Swap({ labels, at }: { labels: readonly ReactNode[]; at: number }) { return ( {labels.map((l, i) => ( {l} ))} ) } /* ---------- 시트 스켈레톤: 완료 화면과 같은 틀·같은 줄 높이 ---------- */ const N3 = [0, 1, 2] const N4 = [0, 1, 2, 3] const SLOT_KEYS = ['morning', 'day', 'evening', 'night'] as const const SLOT_NAMES = { morning: '아침', day: '낮', evening: '저녁', night: '밤' } as const const N6 = [0, 1, 2, 3, 4, 5] const N14 = Array.from({ length: 14 }, (_, i) => i) function GakSkel() { return ( ) } /** 읽을거리·이번 주 특집: 그림 150px · 머리말 · 제목 · 본문 */ function ArticleSkel() { return ( ) } function CommentsSkel() { return ( ) } function RegionsSkel() { return ( ) } /* ---------- 각 계산 근거 ---------- */ const labelLines = (label: string) => { const cut = label.indexOf(' ') return cut < 0 ? [label] : [label.slice(0, cut), label.slice(cut + 1)] } function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[]; size?: number }) { const c = size / 2 const r = size / 2 - 40 const n = factors.length const pt = (i: number, v: number) => { const a = -Math.PI / 2 + (i * 2 * Math.PI) / n return [c + Math.cos(a) * r * v, c + Math.sin(a) * r * v] as const } const ring = (v: number) => factors.map((_, i) => pt(i, v).join(',')).join(' ') return ( {[0.25, 0.5, 0.75, 1].map((v) => ( ))} {factors.map((f, i) => ( ))} pt(i, f.value / 100).join(',')).join(' ')} fill="rgb(255 122 69 / .38)" stroke="#ff7a45" strokeWidth="3" strokeLinejoin="round" /> {factors.map((f, i) => ( ))} {factors.map((f, i) => ( {labelLines(f.label).map((line, k, all) => ( {line} ))} ))} ) } function GakSheet({ indexId, onTitle }: { indexId: number; onTitle: (t: string) => void }) { const { region } = useRegion() const q = useQuery(getIndexOptions({ path: { index_id: indexId }, query: { region: region.code } })) const d: ResIndexDetail | undefined = q.data const g = d?.index useEffect(() => { onTitle(g ? `${g.rank}위 ${g.name}` : '계산 근거') }, [g, onTitle]) // 지역이 바뀌어 다시 받아도 한 번만 보낸다 const tracked = useRef(0) useEffect(() => { if (!g || tracked.current === g.index_id) return tracked.current = g.index_id track('view_gak', { index_id: g.index_id, gak_name: g.name, score: g.score, rank: g.rank }) }, [g]) const load = loadOf(q) if (!g) return {load === 'loading' ? : q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={} className="inset-0" />} const factors = d.factors ?? [] const bands = d.bands ?? [] const now = bands.find((b) => b.current) return (

{g.name}

{d.description &&

{d.description}

}
{g.score}
{!g.active &&

지금은 제철이 아니에요. 점수는 오늘 가장 좋은 시간대 기준이에요.

} {now && (

{now.low}~{now.high}점 {now.text}

)} {factors.length > 2 && } {g.slots && g.slots.length > 0 && (
{SLOT_KEYS.map((k) => { const s = g.slots?.find((x) => x.slot === k) const cur = g.active && g.slot === k return (
{SLOT_NAMES[k]} {cur && ' · 지금'} {s ? s.score : '–'}
) })}
)} {g.trend && g.trend.length > 0 && (
{g.trend.map((t) => (
{t.label} {t.score} 예상
))}
)} {bands.length > 0 && (
    {bands.map((b) => (
  1. {b.low}~{b.high} {b.text}
  2. ))}
)}
{factors.map((f) => (
{f.label} 비중 {f.weight}%

{f.note}

))}
{d.zero_reason && ( 오늘 걸린 조건: {d.zero_reason} )} {factors.length > 0 && ( 계산 방법: 요소 점수에 비중을 곱해 더하고, 가장 낮은 요소가 낮을수록 최대 25%까지 더 깎아요 )} {d.zero_rules && ( 점수 깎이는 조건: {d.zero_rules} )} {d.limit && ( 반영 못 한 것: {d.limit} )}
) } /* ---------- 읽을거리 ---------- */ function ArticleSheet({ articleId, onTitle }: { articleId: number; onTitle: (t: string) => void }) { const q = useQuery(getArticleOptions({ path: { article_id: articleId } })) const a = q.data?.article useEffect(() => { onTitle(a ? (ARTICLE_CAT[a.category]?.[0] ?? '') : '') }, [a, onTitle]) const tracked = useRef(0) useEffect(() => { if (!a || tracked.current === a.article_id) return tracked.current = a.article_id track('select_content', { content_type: 'article', item_id: a.article_id, category: ARTICLE_CAT[a.category]?.[0] ?? a.category }) }, [a]) const load = loadOf(q) if (!a) return {load === 'loading' ? : q.refetch()} empty="글을 찾지 못했어요." hold={} className="inset-0" />} return (

{articleMeta(a)}

{a.title}

{(q.data?.body ?? []).map((t) => (

{t}

))} ) } /* ---------- 이번 주 특집 ---------- */ function SeasonWeekSheet() { const { open } = useSheet() const q = useQuery(getSeasonWeekOptions()) const w = q.data const load = loadOf(q) if (!w?.headline) return {load === 'loading' ? : q.refetch()} empty="이번 주 특집이 아직 없어요." hold={} className="inset-0" />} return (

{w.start && w.end ? dateRange(w.start, w.end) : '이번 주'}

{w.headline}

{(w.poem_lines ?? []).length > 0 && (

{w.poem_lines?.join(' ')} {w.author && {w.author}}

)} {w.term_now && w.term_next && (

지금 절기는 {w.term_now.name}({shortDay(w.term_now.day)}), 다음 절기는 {w.term_next.name}({shortDay(w.term_next.day)})예요.

)} {(w.news ?? []).map((n) => ( ))} ) } /* ---------- 보내기 ---------- */ const SIZE_KEYS = Object.keys(SHARE_SIZES) as ShareSize[] function ShareSheet({ share }: { share: SharePayload }) { const { region } = useRegion() const { kind } = useSky() const [size, setSize] = useState('story') const [images, setImages] = useState>>({}) const [failed, setFailed] = useState>>({}) const srcs = useRef([]) const [toast, setToast] = useState('') const image = images[size] const text = `${share.title} · 날씨각` // 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다 useEffect(() => { if (images[size] || failed[size]) return let alive = true const today = new Date().toLocaleDateString('ko-KR', { month: 'long', day: 'numeric', weekday: 'long' }) shareImage(size === 'square' && share.square ? share.square : share.slides, { size, sky: kind, sub: `${region.name} · ${today}`, host: new URL(SITE_URL).host }).then( (blob) => { if (!alive) return const src = URL.createObjectURL(blob) srcs.current.push(src) setImages((m) => ({ ...m, [size]: { blob, src } })) }, (e: unknown) => { console.error('[share] image', e) if (alive) setFailed((m) => ({ ...m, [size]: true })) }, ) return () => { alive = false } }, [size, images, failed, share.slides, share.square, kind, region.name]) useEffect(() => { const list = srcs.current return () => list.forEach((s) => URL.revokeObjectURL(s)) }, []) // 휴대폰은 공유창에 이미지와 링크를 같이 넘기고, 이미지만 받는 앱이 있어 링크도 복사해 둔다. 공유창이 없으면 이미지를 내려받고 링크를 복사한다 const send = () => { if (!image) return const file = new File([image.blob], `nalssigak-${SHARE_SIZES[size].ratio.replace(':', 'x')}.png`, { type: 'image/png' }) if (IS_TOSS) { tossShare(image.blob, file.name, share.title).then( (r) => { setToast(r === 'saved' ? '이미지를 저장하고 링크를 보냈어요' : '링크를 보냈어요') track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio }) }, (e: unknown) => { console.error('[share] toss', e) setToast('보내지 못했어요. 한 번 더 눌러 주세요') }, ) return } if (navigator.canShare?.({ files: [file], text, url: SITE_URL })) { const copied = navigator.clipboard?.writeText(SITE_URL).then( () => true, (e: unknown) => { console.error('[share] copy link', e) return false }, ) navigator.share({ files: [file], title: share.title, text, url: SITE_URL }).then( async () => { setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요') track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio }) }, (e: unknown) => { if (e instanceof DOMException && e.name === 'AbortError') return console.error('[share] send', e) setToast('보내지 못했어요. 한 번 더 눌러 주세요') }, ) return } const a = document.createElement('a') a.href = image.src a.download = file.name a.click() track('share', { content_type: 'image', item_id: share.title, method: 'download', ratio: SHARE_SIZES[size].ratio }) if (!navigator.clipboard) { setToast('이미지를 내려받았어요') return } navigator.clipboard.writeText(`${text} ${SITE_URL}`).then( () => setToast('이미지를 내려받고 링크를 복사했어요'), () => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'), ) } return (
{SIZE_KEYS.map((k) => (