feat: 날씨 유형 테스트 — 질문 8개로 8유형, 결과별 주소·미리보기, 궁합·잘 맞는 각

- /type 에서 질문 8개에 답하면 날씨 유형 8개 중 하나가 나온다 (/type/{유형})
- 결과를 친구에게 보내면 그 결과의 주소가 가고, 미리보기(제목·설명·그림)가 유형마다 다르다
- 링크로 들어오면 그 결과가 그대로 보이고 '테스트 해 보기'로 이어진다
- 결과마다 다른 유형과의 궁합(찰떡·잘 맞아요·서로 달라서 재밌어요·삐걱삐걱)과
  오늘 잘 맞는 각 3개(풀 6개에서 날짜+유형 기준으로 고정)를 보여 준다
- 오늘 탭 아이콘 줄에 '날씨 유형' 추가, /type 첫 진입은 '날씨 불러오는 중' 덮개를 건너뜀
- GA4 이벤트 7개: type_landing, type_start, type_result, type_share, type_gak, type_match, type_to_today
- 프론트 테스트 추가 (frontend 에서 npm test)
- 유형 그림 8장과 미리보기 그림 9장은 임시 그림 (진짜 그림으로 교체 예정, TODO.md)
- 설계·계획 문서 추가, TODO.md 의 '4주 새 기능 동결' 행 삭제
This commit is contained in:
skkim committed 2026-11-24 08:33:10 +09:00
1 parent 3baa543313
commit 4fc61d6c02
34 files changed
+2221 -8

No files matched your search

+2
View File
@@ -11,6 +11,7 @@ import { SkyPage } from './b/SkyPage'
import { SunrisePage } from './b/SunrisePage'
import { TalkPage } from './b/TalkPage'
import { TodayPage } from './b/TodayPage'
import { TypePage } from './b/TypePage'
import { WeekPage } from './b/WeekPage'
export default function App() {
@@ -29,6 +30,7 @@ export default function App() {
<Route path="first-snow" element={<FirstSnowPage />} />
<Route path="sunrise" element={<SunrisePage />} />
<Route path="saju" element={<SajuPage />} />
<Route path="type/:slug?" element={<TypePage />} />
<Route path="talk" element={<TalkPage />} />
<Route path="shorts/:id?" element={<ShortsPage />} />
<Route path="game" element={<CloudMergePage />} />
+2 -1
View File
@@ -225,7 +225,8 @@ function FirstLoad() {
const { kind } = useSky()
const [started, setStarted] = useState(false)
const [done, setDone] = useState(false)
const [gone, setGone] = useState(false)
// 날씨 유형 테스트(/type)로 처음 들어오면 덮지 않는다: 날씨 데이터 없이도 바로 보이는 화면이고, 친구 링크로 처음 오는 곳이라 기다리게 하지 않는다
const [gone, setGone] = useState(() => /^\/type(\/|$)/.test(window.location.pathname))
// 받기 시작했다가 받는 게 없어지면 끝 (렌더 중에 바로 맞춘다)
if (fetching > 0 && !started) setStarted(true)
if (fetching === 0 && started && !done) setDone(true)
+301
View File
@@ -0,0 +1,301 @@
import { useEffect, useState, type ReactNode } from 'react'
import { Link, Navigate, useLocation, useNavigate, useParams } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import { listIndicesOptions } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'
import { SITE_URL } from '../api/setup'
import { track } from '../lib/analytics'
import { shareLink } from '../lib/platform'
import { cx } from '../lib/utils'
import { useRegion } from './regionContext'
import { useSheet } from './sheetContext'
import { TAP44 } from './ui'
import { LEVEL_NAMES, QUESTIONS, TYPES, dateKey, isSlug, loadMine, matchOf, pickGaks, resultOf, saveMine, seasonCodes, typeOf, type MatchLevel, type Slug } from './weatherType'
/** 질문 화면이 주소 기록(history)에 담아 두는 것. 답할 때마다 한 칸씩 쌓여 브라우저 뒤로 가기로 앞 질문에 돌아간다 */
type QuizState = { answers: number[]; from?: Slug; again?: boolean }
/** 결과 화면에 어떻게 왔는지. 바깥에서 주소로 바로 들어오면 없다 */
type ResultState = { mine?: boolean; from?: Slug; inApp?: boolean }
/** 유형 색: 카드 그림 뒤 하늘, 궁합표의 작은 카드 */
const TYPE_COLOR: Record<Slug, string> = {
sonagi: '#4f97e3',
bombyeot: '#f5c24a',
angae: '#a9a3d6',
baram: '#6fcdb5',
taeyang: '#ff8a3d',
cheonnun: '#f3a6c0',
gureum: '#b8c7dc',
beongae: '#f2d21f',
}
const LEVEL_CHIP: Record<MatchLevel, string> = {
best: 'bg-[#ffe7dc] text-[#b8401a]',
good: 'bg-[#dcecff] text-[#23599f]',
fun: 'bg-[#e3f5ea] text-[#1f7046]',
bad: 'bg-[#eceef4] text-[#4a5270]',
}
/** 크림색 카드 바탕. b-day: 밤 화면에서도 낮 색 그대로 (밤에는 글자색이 밝아져 밝은 카드 위에서 안 보인다) */
const CREAM = 'b-day bg-[#fffaf0]'
const FRAME = 'border-[#b9cfee]'
const BTN_INK = 'block w-full cursor-pointer rounded-[14px] bg-(--ink) py-3.5 text-center text-[15.5px] font-extrabold text-white'
const BTN_LINE = 'block w-full cursor-pointer rounded-[14px] border-[1.5px] border-(--ink) py-3 text-center text-[15.5px] font-extrabold text-(--ink)'
const typePath = (slug: Slug) => `/type/${slug}`
/** 이번에 페이지를 연 뒤 유입으로 센 유형 (뒤로 가기로 돌아와도 한 번만) */
const landed = new Set<Slug>()
/** 날씨 유형 테스트(/type 시작·질문, /type/유형 결과). 결과는 주소만으로 정해져 누가 열어도 같은 화면이다 */
export function TypePage() {
const { slug } = useParams()
const navigate = useNavigate()
const back = () => (window.history.state?.idx > 0 ? navigate(-1) : navigate('/'))
if (slug !== undefined && !isSlug(slug)) return <Navigate to="/type" replace />
return (
<div className="pb-8">
<div className="flex items-center gap-1 px-3 pt-1">
<button type="button" onClick={back} aria-label="뒤로" className={cx('relative grid size-9 shrink-0 cursor-pointer place-items-center rounded-full bg-white/80 text-[22px] font-bold shadow-[0_4px_10px_rgb(40_48_74/0.08)]', TAP44)}>
‹
</button>
<h2 className="m-0 px-1 font-batang text-[20px] font-bold">날씨 유형</h2>
</div>
{slug ? <Result key={slug} slug={slug} /> : <Quiz />}
</div>
)
}
/** 크림색 카드 틀 (오늘 타로 카드와 같은 결) */
function Card({ children, className }: { children: ReactNode; className?: string }) {
return (
<div className={cx('mx-[18px] mt-4 rounded-[22px] p-[9px] shadow-[0_12px_26px_rgb(40_48_74/0.2)]', CREAM, className)}>
<div className={cx('rounded-[15px] border-2 px-3.5 pt-3 pb-4 text-center', FRAME)}>{children}</div>
</div>
)
}
function Quiz() {
const navigate = useNavigate()
const state = useLocation().state as QuizState | null
const [mine] = useState(loadMine)
if (!state?.answers) {
return (
<>
<div className="relative mt-6 h-[216px]" aria-hidden="true">
{[-28, -14, 0, 14, 28].map((deg) => (
<i
key={deg}
className="absolute top-[18px] left-1/2 -ml-12 h-[146px] w-24 origin-[50%_135%] rounded-[13px] border-[5px] border-[#fffaf0] bg-[#2f6fc0] bg-[radial-gradient(circle_at_50%_50%,rgb(255_255_255/0.28)_0_9px,transparent_10px),repeating-linear-gradient(45deg,rgb(255_255_255/0.1)_0_6px,transparent_6px_12px)] shadow-[0_8px_16px_rgb(40_48_74/0.22)]"
style={{ transform: `rotate(${deg}deg)` }}
/>
))}
</div>
<div className="px-[22px] text-center">
<h3 className="m-0 font-batang text-[26px] leading-[1.3] font-bold text-balance">나는 무슨 날씨일까?</h3>
<p className="mt-2 font-bold text-(--ink2)">질문 {QUESTIONS.length}개에 답하면 내 날씨 카드가 한 장 나와요.</p>
</div>
<div className="mx-[18px] mt-8 flex flex-col gap-2.5">
<button type="button" onClick={() => navigate('/type', { state: { answers: [] } satisfies QuizState })} className={BTN_INK}>
시작하기
</button>
{mine && (
<Link to={typePath(mine)} state={{ mine: true, inApp: true } satisfies ResultState} className="block py-1 text-center text-[13.5px] font-extrabold text-(--ink2)">
내 카드 다시 보기 ›
</Link>
)}
</div>
</>
)
}
const { answers, from } = state
const step = Math.min(answers.length, QUESTIONS.length - 1)
const question = QUESTIONS[step]
const pick = (option: number) => {
const next = [...answers.slice(0, step), option]
if (step === 0) track('type_start', { from_type: from ?? 'none', again: state.again === true })
if (next.length < QUESTIONS.length) {
navigate('/type', { state: { ...state, answers: next } satisfies QuizState })
return
}
const result = resultOf(next)
saveMine(result)
track('type_result', { type: result, from_type: from ?? 'none' })
navigate(typePath(result), { state: { mine: true, from, inApp: true } satisfies ResultState })
}
return (
<section aria-label={`질문 ${step + 1}`}>
<div className="b-day mt-4 flex justify-center gap-[7px]" aria-hidden="true">
{QUESTIONS.map((q, i) => (
<i key={q.text} className={cx('h-[34px] w-6 rounded-md border-2', i < step ? 'border-[#fffaf0] bg-[#2f6fc0]' : i === step ? 'border-(--orange) bg-[#fffaf0]' : 'border-white/90 bg-white/55')} />
))}
</div>
<p className="mt-1.5 text-center text-[12.5px] font-extrabold text-(--ink2)">
{QUESTIONS.length}개 중 {step + 1}번째
</p>
<Card>
<div className="rounded-[110px_110px_12px_12px] bg-linear-to-b from-[#cfe5fd] to-[#f3f9ff] px-[18px] pt-11 pb-[22px]">
<h3 className="m-0 font-batang text-[21px] leading-[1.45] font-bold text-balance">{question.text}</h3>
</div>
</Card>
<div className="mx-[18px] mt-3.5 flex flex-col gap-[9px]">
{question.options.map((o, i) => (
<button key={o.text} type="button" onClick={() => pick(i)} className={cx('cursor-pointer rounded-xl border-[1.5px] px-[15px] py-3.5 text-left font-bold text-(--ink)', CREAM, FRAME)}>
{o.text}
</button>
))}
</div>
</section>
)
}
function Result({ slug }: { slug: Slug }) {
const navigate = useNavigate()
const state = useLocation().state as ResultState | null
const { region } = useRegion()
const { open } = useSheet()
const type = typeOf(slug)
const mine = state?.mine === true
const from = state?.from
const [notice, setNotice] = useState<{ text: string; url?: string } | null>(null)
// 바깥에서 이 주소로 바로 들어온 사람 — 친구가 보낸 링크
useEffect(() => {
if (state?.inApp || landed.has(slug)) return
landed.add(slug)
track('type_landing', { type: slug })
}, [slug, state?.inApp])
// 잘 맞는 각: 풀에서 오늘 3개. 각 목록을 받으면 제철인 것만, 못 받았으면 풀 전체에서 이름만
const indices = useQuery(listIndicesOptions({ query: { region: region.code } }))
const listed = indices.data ? [...(indices.data.top3 ?? []), ...(indices.data.items ?? [])] : undefined
const summaries = new Map(listed?.map((g) => [g.code, g]))
const gaks = pickGaks(slug, dateKey(), seasonCodes(listed)).map((code) => ({ code, name: type.gaks.find((g) => g.code === code)?.name ?? code, summary: summaries.get(code) }))
// 궁합표: 방금 보고 온 유형이 있으면 맨 위로
const others = TYPES.map((t) => t.slug)
const rows = from ? [from, ...others.filter((s) => s !== from)] : others
const url = `${SITE_URL}${typePath(slug)}`
const send = async () => {
const sent = await shareLink({ title: `${type.name} · 나는 무슨 날씨일까?`, path: typePath(slug), url, image: `${SITE_URL}/type/og/${slug}.png` })
if (sent === 'cancelled') return
if (sent === 'failed') {
setNotice({ text: '아래 주소를 길게 눌러 복사해 주세요.', url })
return
}
track('type_share', { type: slug, method: sent, mine })
setNotice(sent === 'copy' ? { text: '링크를 복사했어요. 친구에게 붙여 넣어 보내 주세요.' } : null)
}
return (
<article aria-label={type.name}>
<Card>
{mine && <p className="mb-2 text-[12.5px] font-extrabold text-(--ink2)">내 날씨 카드</p>}
{/* 그림은 정사각형으로 받아 4:3 아치에 꽉 채운다 (위아래가 조금 잘림). 그림이 뜨기 전에는 유형 색 하늘 */}
<div className="aspect-[4/3] overflow-hidden rounded-[130px_130px_12px_12px]" style={{ background: `linear-gradient(color-mix(in oklab, ${TYPE_COLOR[slug]} 45%, white), #f6fbff)` }}>
<img src={`/type/${slug}.webp`} alt="" width="640" height="640" className="size-full object-cover" decoding="async" />
</div>
<h3 className="mt-3 mb-0 font-batang text-[31px] leading-[1.2] font-bold">{type.name}</h3>
<p className="mt-0.5 font-extrabold text-[#2f6fc0]">{type.line}</p>
<div className="relative mx-7 my-3 h-0.5 bg-[#b9cfee]" aria-hidden="true">
<i className="absolute top-1/2 left-1/2 -m-1 size-2 rotate-45 border-2 border-[#b9cfee] bg-[#fffaf0]" />
</div>
<ul className="m-0 flex list-none flex-col gap-[5px] p-0 text-[14px] font-bold">
{type.traits.map((trait) => (
<li key={trait}>{trait}</li>
))}
</ul>
</Card>
<div className="mx-[18px] mt-[18px] flex flex-col gap-2.5">
<button type="button" onClick={send} className={BTN_INK}>
친구에게 보내기
</button>
<button type="button" onClick={() => navigate('/type', { state: { answers: [], from: mine ? undefined : slug, again: mine } satisfies QuizState })} className={BTN_LINE}>
{mine ? '다시 하기' : '테스트 해 보기'}
</button>
<div className="min-h-5 text-center text-[13px] font-bold" aria-live="polite">
{notice && <p className="m-0 text-[#1f7a4f]">{notice.text}</p>}
{notice?.url && <p className="b-day mt-1 mb-0 rounded-xl bg-white px-3 py-2 font-semibold break-all select-all">{notice.url}</p>}
</div>
</div>
{gaks.length > 0 && (
<section aria-label="잘 맞는 각">
<h3 className="mx-[18px] mt-3 mb-0 font-batang text-[18px] font-bold">
잘 맞는 각<small className="ml-1.5 font-sans text-[12.5px] font-bold text-(--ink2)">오늘 {region.name}</small>
</h3>
<ul className="mx-[18px] mt-2.5 mb-0 grid list-none grid-cols-3 gap-2 p-0">
{gaks.map(({ code, name, summary }) => {
const face = (
<span className={cx('block rounded-lg border-[1.5px] px-0.5 pt-2.5 pb-2 text-center', FRAME)}>
<b className="block font-batang text-[23px] leading-[1.1] tabular-nums">{summary ? summary.score : '·'}</b>
<span className="text-[12.5px] font-extrabold">{name}</span>
</span>
)
const box = cx('block w-full rounded-xl p-[5px] text-(--ink) shadow-[0_4px_10px_rgb(40_48_74/0.12)]', CREAM)
return (
<li key={code}>
{summary ? (
<button
type="button"
aria-label={`${name} ${summary.score}점`}
onClick={() => {
track('type_gak', { type: slug, index_code: code, score: summary.score })
open({ type: 'gak', indexId: summary.index_id })
}}
className={cx(box, 'cursor-pointer')}
>
{face}
</button>
) : (
<span className={box}>{face}</span>
)}
</li>
)
})}
</ul>
</section>
)}
<section aria-label="궁합">
<h3 className="mx-[18px] mt-[22px] mb-0 font-batang text-[18px] font-bold">{type.name}의 궁합</h3>
<ul className={cx('mx-[18px] mt-2.5 mb-0 list-none rounded-2xl px-3.5 py-1', CREAM)}>
{rows.map((other) => {
const match = matchOf(slug, other)
const name = typeOf(other).name
const row = (
<>
<i className="mt-0.5 h-[37px] w-[26px] rounded-md border-[2.5px] border-white shadow-[0_2px_5px_rgb(40_48_74/0.2)]" style={{ background: TYPE_COLOR[other] }} aria-hidden="true" />
<span className="min-w-0">
<span className="flex items-center justify-between gap-2">
<b className="font-batang text-[16px]">{other === slug ? `같은 ${name}끼리` : other === from ? `방금 본 ${name}과는` : name}</b>
<span className={cx('rounded-full px-[9px] py-0.5 text-[11.5px] font-extrabold whitespace-nowrap', LEVEL_CHIP[match.level])}>{LEVEL_NAMES[match.level]}</span>
</span>
<span className="mt-[3px] block text-[13.5px] text-(--ink2)">{match.text}</span>
</span>
</>
)
const cls = 'grid grid-cols-[26px_1fr] gap-2.5 py-[11px] text-left text-(--ink)'
return (
<li key={other} className="border-b-[1.5px] border-[#ece4d2] last:border-b-0">
{other === slug ? (
<div className={cls}>{row}</div>
) : (
<Link to={typePath(other)} state={{ inApp: true } satisfies ResultState} onClick={() => track('type_match', { type: slug, to_type: other, level: match.level })} className={cls}>
{row}
</Link>
)}
</li>
)
})}
</ul>
</section>
<Link to="/" onClick={() => track('type_to_today', { type: slug })} className="mt-5 block py-1 text-center text-[13.5px] font-extrabold text-(--ink2)">
오늘 날씨 보러 가기 ›
</Link>
</article>
)
}
+3
View File
@@ -9,6 +9,7 @@ import { sajuSeenToday } from './SajuPage'
import { useSunrise } from './sunrise'
import { useSheet } from './sheetContext'
import { Ic, Rail } from './ui'
import { showTypeDot } from './weatherType'
/** 오늘 탭 '내 각' 줄 자리 (아이콘에서 거기로 내려간다) */
export const MY_GAK_ID = 'my-gak'
@@ -38,6 +39,8 @@ export function TodayIcons() {
onClick: () => open({ type: 'tarot' }),
},
{ key: 'saju', label: '날씨 사주', icon: 'yin_yang', badge: sajuSeenToday() ? null : <Dot />, to: '/saju' },
// 날씨 유형 테스트: 이 기기에서 아직 안 해 봤으면 빨간 점
{ key: 'type', label: '날씨 유형', icon: 'rainbow', badge: showTypeDot() ? <Dot /> : null, to: '/type' },
{ key: 'game', label: '날씨 게임', icon: 'game', to: '/game' },
// 계절 지도 칸: 단풍 지도 → 첫눈 지도 → 해돋이 지도 순으로 한 번에 하나만 나온다
...(inSeason ? [{ key: 'foliage', label: '단풍 지도', icon: 'maple', to: '/foliage' }] : []),
+120
View File
@@ -0,0 +1,120 @@
import data from '../../seo/weather_type.json' with { type: 'json' }
/** 날씨 유형 테스트: 유형·질문·궁합 글(seo/weather_type.json)과 결과 계산. 화면·빌드·테스트(node --test)가 같이 쓰므로 React·DOM 없이 돈다 */
export type Slug = 'sonagi' | 'bombyeot' | 'angae' | 'baram' | 'taeyang' | 'cheonnun' | 'gureum' | 'beongae'
export type MatchLevel = 'best' | 'good' | 'fun' | 'bad'
export type WeatherType = { slug: Slug; name: string; line: string; traits: string[]; gaks: { code: string; name: string }[]; ogTitle: string; ogDescription: string }
export type Question = { text: string; options: { text: string; scores: Partial<Record<Slug, number>> }[] }
export type Match = { level: MatchLevel; text: string }
/** 표 순서가 곧 동점일 때 우선순위 */
export const TYPES = data.types as WeatherType[]
export const QUESTIONS = data.questions as Question[]
export const LEVEL_NAMES: Record<MatchLevel, string> = data.levelNames
const SLUGS = TYPES.map((t) => t.slug)
const pairKey = (a: string, b: string) => [a, b].sort().join('+')
const MATCHES = new Map(data.matches.map((m) => [pairKey(m.pair[0], m.pair[1]), { level: m.level as MatchLevel, text: m.text }]))
export function isSlug(s: string | undefined): s is Slug {
return SLUGS.some((slug) => slug === s)
}
export function typeOf(slug: Slug): WeatherType {
return TYPES[SLUGS.indexOf(slug)]
}
/** answers[i] = i번째 질문에서 고른 보기 번호. 점수 합이 가장 큰 유형, 동점이면 마지막 질문부터 거슬러 올라가 그 보기 점수가 높은 유형, 끝까지 같으면 표의 위쪽 유형 */
export function resultOf(answers: number[], questions: Question[] = QUESTIONS): Slug {
const picked = questions.map((q, i) => q.options[answers[i]]?.scores ?? {})
const total = (slug: Slug) => picked.reduce((sum, scores) => sum + (scores[slug] ?? 0), 0)
const top = Math.max(...SLUGS.map(total))
let tied = SLUGS.filter((slug) => total(slug) === top)
for (let i = picked.length - 1; i >= 0 && tied.length > 1; i--) {
const best = Math.max(...tied.map((slug) => picked[i][slug] ?? 0))
tied = tied.filter((slug) => (picked[i][slug] ?? 0) === best)
}
return tied[0]
}
/** 두 유형의 궁합. 순서와 상관없이 같은 쌍을 돌려준다 */
export function matchOf(a: Slug, b: Slug): Match {
return MATCHES.get(pairKey(a, b))!
}
/** 한국 시간 기준 'YYYY-MM-DD'. 보는 사람의 시간대와 상관없이 같은 날이면 같은 값 */
export function dateKey(now: Date = new Date()): string {
return new Date(now.getTime() + 9 * 60 * 60 * 1000).toISOString().slice(0, 10)
}
/** 글자를 32비트 숫자로 (FNV-1a) */
function hash(text: string): number {
let h = 0x811c9dc5
for (let i = 0; i < text.length; i++) {
h ^= text.charCodeAt(i)
h = Math.imul(h, 0x01000193)
}
return h >>> 0
}
/** 씨앗 하나로 0~1 숫자를 차례로 만든다 (mulberry32). 씨앗이 같으면 늘 같은 순서 */
function seeded(seed: number): () => number {
let a = seed
return () => {
a = (a + 0x6d2b79f5) | 0
let t = Math.imul(a ^ (a >>> 15), 1 | a)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
/**
* 그 유형의 각 풀에서 3개를 뽑는다. 날짜와 유형이 같으면 누가 열어도 같은 3개(보낸 사람과 받은 사람이 같은 화면을 보게).
* inSeason: 지금 제철인 각 code. 각 목록을 못 받았으면 null 로 주고, 그러면 풀 전체에서 뽑는다. 제철인 각이 3개보다 적으면 있는 만큼만.
* 풀 전체를 먼저 섞고 그 순서에서 제철인 것을 고른다 — 각 목록을 받기 전과 받은 뒤의 3개가 되도록 같게 (제철이 아닌 각이 끼었을 때만 바뀐다)
*/
export function pickGaks(slug: Slug, day: string, inSeason: ReadonlySet<string> | null): string[] {
const pool = typeOf(slug).gaks.map((g) => g.code)
const random = seeded(hash(`${day}:${slug}`))
for (let i = pool.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1))
;[pool[i], pool[j]] = [pool[j], pool[i]]
}
return pool.filter((code) => !inSeason || inSeason.has(code)).slice(0, 3)
}
const MINE_KEY = 'nalssigak.b.weatherType'
/** 이 기기에서 마지막으로 나온 내 유형. 저장소를 못 쓰거나 값이 없으면 null */
export function loadMine(): Slug | null {
try {
const saved = localStorage.getItem(MINE_KEY) ?? undefined
return isSlug(saved) ? saved : null
} catch {
// 저장소를 못 쓰는 환경(개인정보 보호 창 등)에서는 한 적 없는 것으로 본다
return null
}
}
export function saveMine(slug: Slug): void {
try {
localStorage.setItem(MINE_KEY, slug)
} catch (e) {
console.warn('[type] 내 유형을 저장하지 못함', e)
}
}
/** 각 목록에서 지금 제철인 code. 목록을 못 받았거나 비어 있으면 null (제철을 모르니 풀 전체에서 뽑게) */
export function seasonCodes(items: { code: string; in_season?: boolean }[] | undefined): Set<string> | null {
if (!items?.length) return null
return new Set(items.filter((g) => g.in_season !== false).map((g) => g.code))
}
/** 오늘 탭 아이콘의 빨간 점: 이 기기에서 아직 테스트를 안 해 봤는지. 저장소를 못 쓰면 점을 보이지 않는다 (영영 안 꺼지는 점이 되지 않게) */
export function showTypeDot(): boolean {
try {
return !isSlug(localStorage.getItem(MINE_KEY) ?? undefined)
} catch {
return false
}
}
+32
View File
@@ -0,0 +1,32 @@
/** 주소만 보내는 공유. 그림 파일을 붙이지 않아 받은 메신저가 그 주소의 미리보기를 띄운다. 브라우저를 인자로 받아 테스트(node --test)에서도 돈다 */
type Nav = {
share?: (data: { title: string; url: string }) => Promise<void>
clipboard?: { writeText: (text: string) => Promise<void> }
}
/** 주소를 클립보드에 복사한다 */
export async function copyLink(nav: Nav, url: string): Promise<'copy' | 'failed'> {
try {
if (!nav.clipboard) throw new Error('클립보드를 쓸 수 없는 브라우저')
await nav.clipboard.writeText(url)
return 'copy'
} catch (e) {
console.warn('[share] 주소를 복사하지 못함', e)
return 'failed'
}
}
/** 브라우저 공유창으로 제목과 주소를 보낸다. 사용자가 공유창을 닫으면 cancelled, 공유창이 없거나 오류면 주소를 복사한다 */
export async function sendLink(nav: Nav, title: string, url: string): Promise<'share_sheet' | 'copy' | 'cancelled' | 'failed'> {
if (nav.share) {
try {
await nav.share({ title, url })
return 'share_sheet'
} catch (e) {
// 사용자가 공유창을 그냥 닫은 것은 실패가 아니다
if (e instanceof Error && e.name === 'AbortError') return 'cancelled'
console.warn('[share] 공유창으로 보내지 못해 주소를 복사함', e)
}
}
return copyLink(nav, url)
}
+30
View File
@@ -1,3 +1,5 @@
import { copyLink, sendLink } from './linkShare'
/** 웹/앱인토스/날씨각 안드로이드 앱(웹뷰) 차이를 모으는 곳. 토스 SDK 는 토스 빌드(`vite build --mode toss`)에서만 불러온다 */
export const IS_TOSS = import.meta.env.MODE === 'toss'
@@ -33,6 +35,34 @@ export async function tossShare(image: Blob, fileName: string, title: string): P
return saved ? 'saved' : 'link-only'
}
/** 토스: 미니앱의 그 화면(path)을 여는 토스 링크를 만들어 공유창으로 보낸다. 미리보기 그림(ogImageUrl)은 토스 안드로이드 5.240.0·iOS 5.239.0 이상에서만 바뀐다 */
async function tossShareLink(title: string, path: string, image: string): Promise<void> {
const { Share } = await sdk()
const link = await Share.createLink({ path: `${TOSS_APP}${path}`, ogImageUrl: image })
await Share.sendMessage({ message: `${title} · 날씨각 ${link}` })
}
export type LinkShared = 'share_sheet' | 'copy' | 'toss' | 'cancelled' | 'failed'
/**
* 그림 파일 없이 주소만 보낸다 (받은 메신저가 그 주소의 미리보기를 띄우게).
* 웹은 공유창·없으면 주소 복사, 앱은 주소 복사(앱 공유창은 그림만 넘긴다), 토스는 미니앱의 그 화면을 여는 토스 링크.
* path 는 '/type/sonagi' 처럼 우리 화면 경로, url 은 그 화면의 웹 주소, image 는 미리보기 그림의 https 주소
*/
export async function shareLink(link: { title: string; path: string; url: string; image: string }): Promise<LinkShared> {
if (IS_TOSS) {
try {
await tossShareLink(link.title, link.path, link.image)
return 'toss'
} catch (e) {
console.warn('[share] 토스 링크를 보내지 못함', e)
return 'failed'
}
}
if (IS_APP) return copyLink(navigator, link.url)
return sendLink(navigator, link.title, link.url)
}
/** 토스: 토스 로그인 창을 띄우고 서버로 보낼 인가 코드를 받는다 */
export async function tossLogin() {
const { TossAuth } = await sdk()