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 { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth' import { SITE_URL } from '../api/setup' import { addCommentMutation, addTalkCommentMutation, agreeTermsMutation, blockAuthorMutation, deleteCommentMutation, getArticleOptions, getFeedQueryKey, getIndexOptions, getSeasonWeekOptions, likeCommentMutation, listCommentsInfiniteOptions, listTalkCommentsInfiniteOptions, listTalkCommentsInfiniteQueryKey, listBlockedOptions, listBlockedQueryKey, listCommentsInfiniteQueryKey, listRegionsOptions, meQueryKey, reportCommentMutation, tossMutation, 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, tossLogin, 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_CLOSE_MS, SHEET_OPEN_MS } from './lib' import { MixSheet, MyGakSheet } from './myGak' import { TarotSheet } from './fortune' import { LevelCard, LevelSheet, LevelUpSheet, useShareReward } from './level' import { ownPage, useRegion } from './regionContext' import { WeatherWhySheet } from './weatherWhy' import { useSky } from './skyContext' import { LEVELS } from './cloudMerge' import { SHARE_SIZES, shareImage, type ShareSize } from './storyImage' import { SheetContext, useSheet, type CommentTarget, type SharePayload, type SheetState } from './sheetContext' import { HeartIcon } from './svg' import { MyTalks } 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 } track('sheet_open', { sheet: s.type }) 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: '이야기', tarot: '오늘 타로', level: '내 레벨', levelUp: '레벨이 올랐어요', gameHelp: '구름 합치기 하는 법', contact: '날씨각 문의' } 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('') // 닫히는 동안에도 내려가는 창에 내용이 남아 있게, 마지막으로 연 창을 들고 있는다 const [shown, setShown] = useState(state) if (state && state !== shown) setShown(state) const closing = !state && shown != null useEffect(() => { const el = ref.current if (!el) return if (state) { if (!el.open) el.showModal() return } if (!el.open) return // 내려가는 애니메이션이 끝난 뒤에 실제로 닫는다 const t = setTimeout(() => { el.close() setShown(null) }, SHEET_CLOSE_MS) return () => clearTimeout(t) }, [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 = shown?.type === 'login' ? shown.then : undefined const title = !shown ? '' : shown.type === 'gak' ? gakTitle : shown.type === 'article' ? articleTitle || TITLES.article : shown.type === 'mix' ? (shown.shared ? '받은 각' : '내 각 만들기') : shown.type === 'myGak' ? '내 각' : TITLES[shown.type] return ( { e.preventDefault() onClose() }} onClick={(e) => { if (e.target === e.currentTarget) onClose() }} className={cx('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)', closing && 'b-sheet-closing')} > {shown && (
{shown.type === 'gak' && } {shown.type === 'article' && } {shown.type === 'seasonWeek' && } {shown.type === 'share' && } {shown.type === 'comments' && } {shown.type === 'login' && open(then) : onClose} why={shown.why} />} {shown.type === 'me' && } {shown.type === 'region' && } {shown.type === 'mix' && } {shown.type === 'myGak' && } {shown.type === 'install' && } {shown.type === 'weatherWhy' && } {shown.type === 'tarot' && } {shown.type === 'level' && } {shown.type === 'levelUp' && } {shown.type === 'gameHelp' && } {shown.type === 'contact' && }
)}
) } 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}

))} ) } /* ---------- 이번 주 특집 ---------- */ const GAME_STEPS = [ '목표 점수를 채우면 다음 라운드로 넘어가요. 라운드가 오를수록 목표가 높아져요.', '손가락을 좌우로 움직여 떨어뜨릴 자리를 고르고, 손을 떼면 떨어져요.', '떨어지는 동안 오늘 우리 동네 바람만큼 옆으로 밀려요. 바람 방향을 보고 조금 비켜 떨어뜨리세요.', '같은 그림끼리 닿으면 한 단계 큰 그림으로 합쳐지고 점수가 올라요.', '해 둘이 만나면 사라지면서 보너스 점수!', '쌓인 그림이 위쪽 점선을 넘은 채로 잠깐 있으면 끝나요. 판은 다음 라운드로 그대로 이어져요.', '로그인하면 라운드를 깰 때마다 2각을 받아요. 하루 20각까지예요.', ] function GameHelpSheet() { return (
    {GAME_STEPS.map((t) => (
  1. {t}
  2. ))}

합쳐지는 순서

{LEVELS.map((l, i) => ( {i + 1}. {l.name} ))}
) } const CONTACTS = [ { method: 'phone', label: '전화 문의', value: '010-2755-6463', href: 'tel:010-2755-6463', icon: 'M6.6 3h3l1.5 4.2-2 1.5a12 12 0 0 0 6.2 6.2l1.5-2L21 14.4v3A2.6 2.6 0 0 1 18.4 20 15.4 15.4 0 0 1 4 5.6 2.6 2.6 0 0 1 6.6 3Z' }, { method: 'email', label: '이메일 문의', value: 'sales@o2o.kr', href: 'mailto:sales@o2o.kr', icon: 'M3.5 6.5h17v11h-17zM4 7l8 6.5L20 7' }, ] as const /** 오른쪽 아래 문의 버튼으로 여는 창: 운영사 소개와 전화·이메일 */ function ContactSheet({ onDone }: { onDone: () => void }) { return ( AIO2O

날씨각과 함께할까요?

날씨에 맞춘 광고, 지역 축제·행사 소개,
콘텐츠 협업 같은 제휴 문의를 받아요.
전화나 이메일로 편하게 알려 주세요.

날씨각은 주식회사 에이아이오투오가 만들어요

) } 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 reward = useShareReward() 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} · 날씨각` const url = share.url ?? SITE_URL // 고른 크기의 이미지를 미리 만들어 둔다. 누를 때 만들면 아이폰이 공유창을 막는다 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 }) reward() }, (e: unknown) => { console.error('[share] toss', e) setToast('보내지 못했어요. 한 번 더 눌러 주세요') }, ) return } if (navigator.canShare?.({ files: [file], text, url })) { const copied = navigator.clipboard?.writeText(url).then( () => true, (e: unknown) => { console.error('[share] copy link', e) return false }, ) navigator.share({ files: [file], title: share.title, text, url }).then( async () => { setToast((await copied) ? '보냈어요. 링크도 복사해 뒀어요' : '보냈어요') track('share', { content_type: 'image', item_id: share.title, method: 'share_sheet', ratio: SHARE_SIZES[size].ratio }) reward() }, (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} ${url}`).then( () => setToast('이미지를 내려받고 링크를 복사했어요'), () => setToast('이미지를 내려받았어요. 링크 복사는 막혀 있어요'), ) } return (
{SIZE_KEYS.map((k) => (