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 { setTokens, subscribeAuth } from '../api/auth' import { addCommentMutation, deleteCommentMutation, getArticleOptions, getFeedQueryKey, getIndexOptions, getSeasonWeekOptions, likeCommentMutation, listCommentsInfiniteOptions, listCommentsInfiniteQueryKey, listRegionsOptions, loginMutation, meQueryKey, signupMutation, unlikeCommentMutation, updateMeMutation, } from '../api/client/@tanstack/react-query.gen' import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen' import { cx } from '../lib/utils' import { useAuth } from './authContext' import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib' import { useRegion } from './regionContext' import { useSky } from './skyContext' import { storyImage } from './storyImage' import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext' import { HeartIcon } from './svg' import { Avatar, Ic, Skel, StateBox } from './ui' export function SheetProvider({ children }: { children: ReactNode }) { const [state, setState] = useState(null) const open = useCallback((s: Exclude) => setState(s), []) const close = useCallback(() => setState(null), []) const api = useMemo(() => ({ open, close }), [open, close]) // 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다 useEffect(() => subscribeAuth((reason) => reason === 'required' && setState({ type: 'login' })), []) return ( {children} ) } const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', me: '내 정보', region: '지역 바꾸기' } as const /** 아래에서 올라오는 창: 네이티브 라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */ function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) { const ref = useRef(null) 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' return () => { root.style.overflow = before } }, [isOpen]) const title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : 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' && } {state.type === 'me' && } {state.type === 'region' && }
)}
) } 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 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 load = loadOf(q) if (!g) return {load === 'loading' ? : q.refetch()} empty="이 각의 계산 근거가 아직 없어요." hold={} className="inset-0" />} const factors = d.factors ?? [] return (

{g.name}

{d.description &&

{d.description}

}
{g.score}
{factors.length > 2 && } {g.trend && g.trend.length > 0 && (
{g.trend.map((t) => (
{t.label} {t.score} 예상
))}
)}
{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 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) => ( ))} ) } /* ---------- 보내기 ---------- */ function ShareSheet({ share }: { share: SharePayload }) { const { region } = useRegion() const opts = [...share.messages, '직접 쓰기'] const [pick, setPick] = useState(0) const [mine, setMine] = useState('') const [toast, setToast] = useState('') const isMine = pick === opts.length - 1 const msg = isMine ? mine : opts[pick] const url = window.location.origin const text = msg.trim() ? `${msg} — ${share.title} · 날씨각` : `${share.title} · 날씨각` const { kind } = useSky() const [image, setImage] = useState<{ blob: Blob; src: string } | null>(null) const [imageError, setImageError] = useState(false) // 창이 열리면 카드를 스토리 크기 이미지로 미리 만들어 둔다 useEffect(() => { if (!share.card) return let src = '' let alive = true storyImage(share.card, { title: share.title, sub: `${region.name} · 날씨각`, sky: kind }).then( (blob) => { if (!alive) return src = URL.createObjectURL(blob) setImage({ blob, src }) }, (e: unknown) => { console.error('[share] story image', e) if (alive) setImageError(true) }, ) return () => { alive = false if (src) URL.revokeObjectURL(src) } }, [share.card, share.title, region.name, kind]) // 휴대폰은 공유창에 이미지 파일을 넘기고(인스타 스토리·카톡 등), 안 되면 이미지를 내려받는다 const shareImage = () => { if (!image) return const file = new File([image.blob], 'nalssigak.png', { type: 'image/png' }) if (navigator.canShare?.({ files: [file] })) { navigator.share({ files: [file], title: share.title, text }).then( () => setToast('보냈어요'), (e: unknown) => { if (e instanceof DOMException && e.name === 'AbortError') return setToast('공유하지 못했어요. 이미지를 내려받아 올려 주세요') }, ) return } const a = document.createElement('a') a.href = image.src a.download = 'nalssigak.png' a.click() setToast('이미지를 내려받았어요. 인스타 스토리에 올려 보세요') } // 휴대폰 기본 공유창. 없거나 실패하면 링크 복사로 대신한다. const shareNative = () => { if (!navigator.share) { copy() return } navigator.share({ title: share.title, text, url }).then( () => setToast('보냈어요'), (e: unknown) => { if (e instanceof DOMException && e.name === 'AbortError') return copy() }, ) } const copy = () => { if (!navigator.clipboard) { setToast('복사가 막혀 있어요') return } navigator.clipboard.writeText(`${text} ${url}`).then( () => setToast('보낼 말과 링크를 복사했어요'), () => setToast('복사가 막혀 있어요. 길게 눌러 복사해 주세요'), ) } return (
{share.title} 날씨각 · {region.name}
{opts.map((o, k) => ( ))}
{isMine && (