feat: 시안 B 화면을 기본 화면으로, Hey API로 백엔드 연결
- 예전 화면(/, /a)과 목업 데이터를 지우고 시안 B 를 / 로 - @hey-api/openapi-ts 로 타입·TanStack Query 함수 생성, 토큰·401 갱신 처리 - 공유는 기본 공유창, 없으면 링크 복사 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e134295ce5
commit
f8b47f064a
147 files changed
+12350
No files matched your search
@@ -0,0 +1,24 @@
|
||||
import { BrowserRouter, Route, Routes } from 'react-router'
|
||||
import { BLayout } from './b/BLayout'
|
||||
import { GakPage } from './b/GakPage'
|
||||
import { SeasonPage } from './b/SeasonPage'
|
||||
import { SkyPage } from './b/SkyPage'
|
||||
import { TodayPage } from './b/TodayPage'
|
||||
import { WeekPage } from './b/WeekPage'
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
<Route element={<BLayout />}>
|
||||
<Route index element={<TodayPage />} />
|
||||
<Route path="gak" element={<GakPage />} />
|
||||
<Route path="sky" element={<SkyPage />} />
|
||||
<Route path="week" element={<WeekPage />} />
|
||||
<Route path="season" element={<SeasonPage />} />
|
||||
<Route path="*" element={<TodayPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// 로그인 토큰 저장소: localStorage + 메모리, 바뀌면 구독자에게 알린다
|
||||
const ACCESS_KEY = 'nalssigak.accessToken'
|
||||
const REFRESH_KEY = 'nalssigak.refreshToken'
|
||||
|
||||
function readStored(key: string): string | null {
|
||||
try {
|
||||
return localStorage.getItem(key)
|
||||
} catch {
|
||||
// 사파리 프라이빗 모드 등에서 저장소 접근이 막히면 로그인 안 한 상태로 시작한다
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeStored(key: string, value: string | null) {
|
||||
try {
|
||||
if (value) localStorage.setItem(key, value)
|
||||
else localStorage.removeItem(key)
|
||||
} catch {
|
||||
// 저장이 막혀도 이번 방문 동안은 메모리 토큰으로 계속 쓴다
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
let accessToken = readStored(ACCESS_KEY)
|
||||
const listeners = new Set<(reason: 'change' | 'required') => void>()
|
||||
|
||||
/** 토큰이 바뀌거나(로그인·로그아웃) 로그인이 필요할 때 알림을 받는다 */
|
||||
export function subscribeAuth(fn: (reason: 'change' | 'required') => void) {
|
||||
listeners.add(fn)
|
||||
return () => {
|
||||
listeners.delete(fn)
|
||||
}
|
||||
}
|
||||
|
||||
const emit = (reason: 'change' | 'required') => listeners.forEach((fn) => fn(reason))
|
||||
|
||||
export function getAccessToken() {
|
||||
return accessToken
|
||||
}
|
||||
|
||||
export function setTokens(access: string | null, refreshToken?: string | null) {
|
||||
accessToken = access
|
||||
writeStored(ACCESS_KEY, access)
|
||||
if (refreshToken !== undefined) writeStored(REFRESH_KEY, refreshToken)
|
||||
emit('change')
|
||||
}
|
||||
|
||||
export function clearTokens() {
|
||||
setTokens(null, null)
|
||||
}
|
||||
|
||||
export function getRefreshToken() {
|
||||
return readStored(REFRESH_KEY)
|
||||
}
|
||||
|
||||
export const emitAuthRequired = () => emit('required')
|
||||
@@ -0,0 +1,676 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query';
|
||||
|
||||
import { client } from '../client.gen';
|
||||
import { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWeatherNow, getWeatherToday, getWeek, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost } from '../sdk.gen';
|
||||
import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse } from '../types.gen';
|
||||
|
||||
export type QueryKey<TOptions extends Options> = [
|
||||
Pick<TOptions, 'baseUrl' | 'body' | 'headers' | 'path' | 'query'> & {
|
||||
_id: string;
|
||||
_infinite?: boolean;
|
||||
tags?: ReadonlyArray<string>;
|
||||
}
|
||||
];
|
||||
|
||||
const createQueryKey = <TOptions extends Options>(id: string, options?: TOptions, infinite?: boolean, tags?: ReadonlyArray<string>): [
|
||||
QueryKey<TOptions>[0]
|
||||
] => {
|
||||
const params: QueryKey<TOptions>[0] = { _id: id, baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl } as QueryKey<TOptions>[0];
|
||||
if (infinite) {
|
||||
params._infinite = infinite;
|
||||
}
|
||||
if (tags) {
|
||||
params.tags = tags;
|
||||
}
|
||||
if (options?.body) {
|
||||
params.body = options.body;
|
||||
}
|
||||
if (options?.headers) {
|
||||
params.headers = options.headers;
|
||||
}
|
||||
if (options?.path) {
|
||||
params.path = options.path;
|
||||
}
|
||||
if (options?.query) {
|
||||
params.query = options.query;
|
||||
}
|
||||
return [params];
|
||||
};
|
||||
|
||||
export const listRegionsQueryKey = (options?: Options<ListRegionsData>) => createQueryKey('listRegions', options);
|
||||
|
||||
/**
|
||||
* 구 목록
|
||||
*/
|
||||
export const listRegionsOptions = (options?: Options<ListRegionsData>) => queryOptions<ListRegionsResponse, ListRegionsError, ListRegionsResponse, ReturnType<typeof listRegionsQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listRegions({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listRegionsQueryKey(options)
|
||||
});
|
||||
|
||||
export const nearestRegionQueryKey = (options: Options<NearestRegionData>) => createQueryKey('nearestRegion', options);
|
||||
|
||||
/**
|
||||
* 위치에서 가장 가까운 구
|
||||
*/
|
||||
export const nearestRegionOptions = (options: Options<NearestRegionData>) => queryOptions<NearestRegionResponse, NearestRegionError, NearestRegionResponse, ReturnType<typeof nearestRegionQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await nearestRegion({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: nearestRegionQueryKey(options)
|
||||
});
|
||||
|
||||
export const getWeatherTodayQueryKey = (options: Options<GetWeatherTodayData>) => createQueryKey('getWeatherToday', options);
|
||||
|
||||
/**
|
||||
* 오늘 3시간 칸 날씨
|
||||
*/
|
||||
export const getWeatherTodayOptions = (options: Options<GetWeatherTodayData>) => queryOptions<GetWeatherTodayResponse, GetWeatherTodayError, GetWeatherTodayResponse, ReturnType<typeof getWeatherTodayQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getWeatherToday({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getWeatherTodayQueryKey(options)
|
||||
});
|
||||
|
||||
export const getWeatherNowQueryKey = (options: Options<GetWeatherNowData>) => createQueryKey('getWeatherNow', options);
|
||||
|
||||
/**
|
||||
* 지금 비 올까: 2시간 비, 내일 출퇴근, 미세먼지, 특보
|
||||
*/
|
||||
export const getWeatherNowOptions = (options: Options<GetWeatherNowData>) => queryOptions<GetWeatherNowResponse, GetWeatherNowError, GetWeatherNowResponse, ReturnType<typeof getWeatherNowQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getWeatherNow({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getWeatherNowQueryKey(options)
|
||||
});
|
||||
|
||||
export const getSkyQueryKey = (options: Options<GetSkyData>) => createQueryKey('getSky', options);
|
||||
|
||||
/**
|
||||
* 노을·일출 점수, 3컷, 가까운 명소, 앞으로 3일
|
||||
*/
|
||||
export const getSkyOptions = (options: Options<GetSkyData>) => queryOptions<GetSkyResponse, GetSkyError, GetSkyResponse, ReturnType<typeof getSkyQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getSky({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getSkyQueryKey(options)
|
||||
});
|
||||
|
||||
export const getSkyRankingQueryKey = (options?: Options<GetSkyRankingData>) => createQueryKey('getSkyRanking', options);
|
||||
|
||||
/**
|
||||
* 전국 노을 순위 (대표 30곳)
|
||||
*/
|
||||
export const getSkyRankingOptions = (options?: Options<GetSkyRankingData>) => queryOptions<GetSkyRankingResponse, DefaultError, GetSkyRankingResponse, ReturnType<typeof getSkyRankingQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getSkyRanking({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getSkyRankingQueryKey(options)
|
||||
});
|
||||
|
||||
export const listIndicesQueryKey = (options: Options<ListIndicesData>) => createQueryKey('listIndices', options);
|
||||
|
||||
/**
|
||||
* 지수 목록 (점수순, 1~3위, 오늘 날씨 점수)
|
||||
*/
|
||||
export const listIndicesOptions = (options: Options<ListIndicesData>) => queryOptions<ListIndicesResponse, ListIndicesError, ListIndicesResponse, ReturnType<typeof listIndicesQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listIndices({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listIndicesQueryKey(options)
|
||||
});
|
||||
|
||||
export const getIndexQueryKey = (options: Options<GetIndexData>) => createQueryKey('getIndex', options);
|
||||
|
||||
/**
|
||||
* 지수 계산 근거
|
||||
*/
|
||||
export const getIndexOptions = (options: Options<GetIndexData>) => queryOptions<GetIndexResponse, GetIndexError, GetIndexResponse, ReturnType<typeof getIndexQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getIndex({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getIndexQueryKey(options)
|
||||
});
|
||||
|
||||
export const getWeekQueryKey = (options: Options<GetWeekData>) => createQueryKey('getWeek', options);
|
||||
|
||||
/**
|
||||
* 7일 날씨와 그날 추천
|
||||
*/
|
||||
export const getWeekOptions = (options: Options<GetWeekData>) => queryOptions<GetWeekResponse, GetWeekError, GetWeekResponse, ReturnType<typeof getWeekQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getWeek({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getWeekQueryKey(options)
|
||||
});
|
||||
|
||||
export const listPlacesQueryKey = (options: Options<ListPlacesData>) => createQueryKey('listPlaces', options);
|
||||
|
||||
/**
|
||||
* 날씨 맞춤 데이트 명소
|
||||
*/
|
||||
export const listPlacesOptions = (options: Options<ListPlacesData>) => queryOptions<ListPlacesResponse, ListPlacesError, ListPlacesResponse, ReturnType<typeof listPlacesQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listPlaces({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listPlacesQueryKey(options)
|
||||
});
|
||||
|
||||
export const listEventsQueryKey = (options: Options<ListEventsData>) => createQueryKey('listEvents', options);
|
||||
|
||||
/**
|
||||
* 앞으로 30일 축제·행사
|
||||
*/
|
||||
export const listEventsOptions = (options: Options<ListEventsData>) => queryOptions<ListEventsResponse, ListEventsError, ListEventsResponse, ReturnType<typeof listEventsQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listEvents({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listEventsQueryKey(options)
|
||||
});
|
||||
|
||||
export const getSeasonWeekQueryKey = (options?: Options<GetSeasonWeekData>) => createQueryKey('getSeasonWeek', options);
|
||||
|
||||
/**
|
||||
* 이번 주 계절 책: 시, 절기, 계절 소식
|
||||
*/
|
||||
export const getSeasonWeekOptions = (options?: Options<GetSeasonWeekData>) => queryOptions<GetSeasonWeekResponse, DefaultError, GetSeasonWeekResponse, ReturnType<typeof getSeasonWeekQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getSeasonWeek({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getSeasonWeekQueryKey(options)
|
||||
});
|
||||
|
||||
export const listArticlesQueryKey = (options?: Options<ListArticlesData>) => createQueryKey('listArticles', options);
|
||||
|
||||
/**
|
||||
* 읽을거리 목록
|
||||
*/
|
||||
export const listArticlesOptions = (options?: Options<ListArticlesData>) => queryOptions<ListArticlesResponse, ListArticlesError, ListArticlesResponse, ReturnType<typeof listArticlesQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listArticles({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listArticlesQueryKey(options)
|
||||
});
|
||||
|
||||
export const getArticleQueryKey = (options: Options<GetArticleData>) => createQueryKey('getArticle', options);
|
||||
|
||||
/**
|
||||
* 읽을거리 본문
|
||||
*/
|
||||
export const getArticleOptions = (options: Options<GetArticleData>) => queryOptions<GetArticleResponse, GetArticleError, GetArticleResponse, ReturnType<typeof getArticleQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getArticle({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getArticleQueryKey(options)
|
||||
});
|
||||
|
||||
export const getFeedQueryKey = (options: Options<GetFeedData>) => createQueryKey('getFeed', options);
|
||||
|
||||
/**
|
||||
* 메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠
|
||||
*/
|
||||
export const getFeedOptions = (options: Options<GetFeedData>) => queryOptions<GetFeedResponse, GetFeedError, GetFeedResponse, ReturnType<typeof getFeedQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getFeed({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getFeedQueryKey(options)
|
||||
});
|
||||
|
||||
export const getPostQueryKey = (options: Options<GetPostData>) => createQueryKey('getPost', options);
|
||||
|
||||
/**
|
||||
* 포스트 하나 (공유 링크로 들어왔을 때)
|
||||
*/
|
||||
export const getPostOptions = (options: Options<GetPostData>) => queryOptions<GetPostResponse, GetPostError, GetPostResponse, ReturnType<typeof getPostQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await getPost({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: getPostQueryKey(options)
|
||||
});
|
||||
|
||||
/**
|
||||
* 회원가입 (아이디 영문 소문자·숫자·_ 4~20자, 비밀번호 8자 이상, 닉네임 2~12자)
|
||||
*/
|
||||
export const signupMutation = (options?: Partial<Options<SignupData>>): UseMutationOptions<SignupResponse, SignupError, Options<SignupData>> => {
|
||||
const mutationOptions: UseMutationOptions<SignupResponse, SignupError, Options<SignupData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await signup({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 로그인
|
||||
*/
|
||||
export const loginMutation = (options?: Partial<Options<LoginData>>): UseMutationOptions<LoginResponse, LoginError, Options<LoginData>> => {
|
||||
const mutationOptions: UseMutationOptions<LoginResponse, LoginError, Options<LoginData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await login({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 토큰 재발급
|
||||
*/
|
||||
export const refreshMutation = (options?: Partial<Options<RefreshData>>): UseMutationOptions<RefreshResponse, RefreshError, Options<RefreshData>> => {
|
||||
const mutationOptions: UseMutationOptions<RefreshResponse, RefreshError, Options<RefreshData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await refresh({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const meQueryKey = (options?: Options<MeData>) => createQueryKey('me', options);
|
||||
|
||||
/**
|
||||
* 내 정보
|
||||
*/
|
||||
export const meOptions = (options?: Options<MeData>) => queryOptions<MeResponse, MeError, MeResponse, ReturnType<typeof meQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await me({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: meQueryKey(options)
|
||||
});
|
||||
|
||||
/**
|
||||
* 좋아요 취소
|
||||
*/
|
||||
export const unlikePostMutation = (options?: Partial<Options<UnlikePostData>>): UseMutationOptions<UnlikePostResponse, UnlikePostError, Options<UnlikePostData>> => {
|
||||
const mutationOptions: UseMutationOptions<UnlikePostResponse, UnlikePostError, Options<UnlikePostData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await unlikePost({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 좋아요
|
||||
*/
|
||||
export const likePostMutation = (options?: Partial<Options<LikePostData>>): UseMutationOptions<LikePostResponse, LikePostError, Options<LikePostData>> => {
|
||||
const mutationOptions: UseMutationOptions<LikePostResponse, LikePostError, Options<LikePostData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await likePost({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 저장 취소
|
||||
*/
|
||||
export const unsavePostMutation = (options?: Partial<Options<UnsavePostData>>): UseMutationOptions<UnsavePostResponse, UnsavePostError, Options<UnsavePostData>> => {
|
||||
const mutationOptions: UseMutationOptions<UnsavePostResponse, UnsavePostError, Options<UnsavePostData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await unsavePost({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 저장
|
||||
*/
|
||||
export const savePostMutation = (options?: Partial<Options<SavePostData>>): UseMutationOptions<SavePostResponse, SavePostError, Options<SavePostData>> => {
|
||||
const mutationOptions: UseMutationOptions<SavePostResponse, SavePostError, Options<SavePostData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await savePost({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const listSavedQueryKey = (options?: Options<ListSavedData>) => createQueryKey('listSaved', options);
|
||||
|
||||
/**
|
||||
* 내가 저장한 포스트
|
||||
*/
|
||||
export const listSavedOptions = (options?: Options<ListSavedData>) => queryOptions<ListSavedResponse, ListSavedError, ListSavedResponse, ReturnType<typeof listSavedQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listSaved({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listSavedQueryKey(options)
|
||||
});
|
||||
|
||||
const createInfiniteParams = <K extends Pick<QueryKey<Options>[0], 'body' | 'headers' | 'path' | 'query'>>(queryKey: QueryKey<Options>, page: K) => {
|
||||
const params = { ...queryKey[0] };
|
||||
if (page.body) {
|
||||
params.body = {
|
||||
...queryKey[0].body as any,
|
||||
...page.body as any
|
||||
};
|
||||
}
|
||||
if (page.headers) {
|
||||
params.headers = {
|
||||
...queryKey[0].headers,
|
||||
...page.headers
|
||||
};
|
||||
}
|
||||
if (page.path) {
|
||||
params.path = {
|
||||
...queryKey[0].path as any,
|
||||
...page.path as any
|
||||
};
|
||||
}
|
||||
if (page.query) {
|
||||
params.query = {
|
||||
...queryKey[0].query as any,
|
||||
...page.query as any
|
||||
};
|
||||
}
|
||||
return params as unknown as typeof page;
|
||||
};
|
||||
|
||||
export const listSavedInfiniteQueryKey = (options?: Options<ListSavedData>): QueryKey<Options<ListSavedData>> => createQueryKey('listSaved', options, true);
|
||||
|
||||
/**
|
||||
* 내가 저장한 포스트
|
||||
*/
|
||||
export const listSavedInfiniteOptions = (options?: Options<ListSavedData>) => {
|
||||
const opts = infiniteQueryOptions<ListSavedResponse, ListSavedError, InfiniteData<ListSavedResponse>, QueryKey<Options<ListSavedData>>, number | null | Pick<QueryKey<Options<ListSavedData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
|
||||
// @ts-ignore
|
||||
{
|
||||
queryFn: async ({ pageParam, queryKey, signal }) => {
|
||||
// @ts-ignore
|
||||
const page: Pick<QueryKey<Options<ListSavedData>>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : {
|
||||
query: {
|
||||
cursor: pageParam
|
||||
}
|
||||
};
|
||||
const params = createInfiniteParams(queryKey, page);
|
||||
const { data } = await listSaved({
|
||||
...options,
|
||||
...params,
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listSavedInfiniteQueryKey(options)
|
||||
});
|
||||
return opts as Omit<typeof opts, 'initialData'>;
|
||||
};
|
||||
|
||||
export const listCommentsQueryKey = (options: Options<ListCommentsData>) => createQueryKey('listComments', options);
|
||||
|
||||
/**
|
||||
* 댓글 목록 (로그인 없이 보기)
|
||||
*/
|
||||
export const listCommentsOptions = (options: Options<ListCommentsData>) => queryOptions<ListCommentsResponse, ListCommentsError, ListCommentsResponse, ReturnType<typeof listCommentsQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await listComments({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listCommentsQueryKey(options)
|
||||
});
|
||||
|
||||
export const listCommentsInfiniteQueryKey = (options: Options<ListCommentsData>): QueryKey<Options<ListCommentsData>> => createQueryKey('listComments', options, true);
|
||||
|
||||
/**
|
||||
* 댓글 목록 (로그인 없이 보기)
|
||||
*/
|
||||
export const listCommentsInfiniteOptions = (options: Options<ListCommentsData>) => {
|
||||
const opts = infiniteQueryOptions<ListCommentsResponse, ListCommentsError, InfiniteData<ListCommentsResponse>, QueryKey<Options<ListCommentsData>>, number | null | Pick<QueryKey<Options<ListCommentsData>>[0], 'body' | 'headers' | 'path' | 'query'>>(
|
||||
// @ts-ignore
|
||||
{
|
||||
queryFn: async ({ pageParam, queryKey, signal }) => {
|
||||
// @ts-ignore
|
||||
const page: Pick<QueryKey<Options<ListCommentsData>>[0], 'body' | 'headers' | 'path' | 'query'> = typeof pageParam === 'object' ? pageParam : {
|
||||
query: {
|
||||
cursor: pageParam
|
||||
}
|
||||
};
|
||||
const params = createInfiniteParams(queryKey, page);
|
||||
const { data } = await listComments({
|
||||
...options,
|
||||
...params,
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: listCommentsInfiniteQueryKey(options)
|
||||
});
|
||||
return opts as Omit<typeof opts, 'initialData'>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 댓글 쓰기 (60자)
|
||||
*/
|
||||
export const addCommentMutation = (options?: Partial<Options<AddCommentData>>): UseMutationOptions<AddCommentResponse, AddCommentError, Options<AddCommentData>> => {
|
||||
const mutationOptions: UseMutationOptions<AddCommentResponse, AddCommentError, Options<AddCommentData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await addComment({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 내 댓글 지우기
|
||||
*/
|
||||
export const deleteCommentMutation = (options?: Partial<Options<DeleteCommentData>>): UseMutationOptions<DeleteCommentResponse, DeleteCommentError, Options<DeleteCommentData>> => {
|
||||
const mutationOptions: UseMutationOptions<DeleteCommentResponse, DeleteCommentError, Options<DeleteCommentData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await deleteComment({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 댓글 좋아요 취소
|
||||
*/
|
||||
export const unlikeCommentMutation = (options?: Partial<Options<UnlikeCommentData>>): UseMutationOptions<UnlikeCommentResponse, UnlikeCommentError, Options<UnlikeCommentData>> => {
|
||||
const mutationOptions: UseMutationOptions<UnlikeCommentResponse, UnlikeCommentError, Options<UnlikeCommentData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await unlikeComment({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
/**
|
||||
* 댓글 좋아요
|
||||
*/
|
||||
export const likeCommentMutation = (options?: Partial<Options<LikeCommentData>>): UseMutationOptions<LikeCommentResponse, LikeCommentError, Options<LikeCommentData>> => {
|
||||
const mutationOptions: UseMutationOptions<LikeCommentResponse, LikeCommentError, Options<LikeCommentData>> = {
|
||||
mutationFn: async (fnOptions) => {
|
||||
const { data } = await likeComment({
|
||||
...options,
|
||||
...fnOptions,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
}
|
||||
};
|
||||
return mutationOptions;
|
||||
};
|
||||
|
||||
export const healthzHealthzGetQueryKey = (options?: Options<HealthzHealthzGetData>) => createQueryKey('healthzHealthzGet', options);
|
||||
|
||||
/**
|
||||
* 헬스체크
|
||||
*/
|
||||
export const healthzHealthzGetOptions = (options?: Options<HealthzHealthzGetData>) => queryOptions<HealthzHealthzGetResponse, DefaultError, HealthzHealthzGetResponse, ReturnType<typeof healthzHealthzGetQueryKey>>({
|
||||
queryFn: async ({ queryKey, signal }) => {
|
||||
const { data } = await healthzHealthzGet({
|
||||
...options,
|
||||
...queryKey[0],
|
||||
signal,
|
||||
throwOnError: true
|
||||
});
|
||||
return data;
|
||||
},
|
||||
queryKey: healthzHealthzGetQueryKey(options)
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { type Client, type ClientOptions, type Config, createClient, createConfig } from './client';
|
||||
import type { ClientOptions as ClientOptions2 } from './types.gen';
|
||||
|
||||
/**
|
||||
* The `createClientConfig()` function will be called on client initialization
|
||||
* and the returned object will become the client's initial configuration.
|
||||
*
|
||||
* You may want to initialize your client this way instead of calling
|
||||
* `setConfig()`. This is useful for example if you're using Next.js
|
||||
* to ensure your client always has the correct values.
|
||||
*/
|
||||
export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
|
||||
|
||||
export const client: Client = createClient(createConfig<ClientOptions2>({ baseUrl: 'http://localhost:9810', throwOnError: true }));
|
||||
@@ -0,0 +1,277 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { createSseClient } from '../core/serverSentEvents.gen';
|
||||
import type { HttpMethod } from '../core/types.gen';
|
||||
import { getValidRequestBody } from '../core/utils.gen';
|
||||
import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen';
|
||||
import {
|
||||
buildUrl,
|
||||
createConfig,
|
||||
createInterceptors,
|
||||
getParseAs,
|
||||
mergeConfigs,
|
||||
mergeHeaders,
|
||||
setAuthParams,
|
||||
} from './utils.gen';
|
||||
|
||||
type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
|
||||
body?: any;
|
||||
headers: ReturnType<typeof mergeHeaders>;
|
||||
};
|
||||
|
||||
export const createClient = (config: Config = {}): Client => {
|
||||
let _config = mergeConfigs(createConfig(), config);
|
||||
|
||||
const getConfig = (): Config => ({ ..._config });
|
||||
|
||||
const setConfig = (config: Config): Config => {
|
||||
_config = mergeConfigs(_config, config);
|
||||
return getConfig();
|
||||
};
|
||||
|
||||
const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();
|
||||
|
||||
const beforeRequest = async <
|
||||
TData = unknown,
|
||||
TResponseStyle extends 'data' | 'fields' = 'fields',
|
||||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
>(
|
||||
options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,
|
||||
) => {
|
||||
const opts = {
|
||||
..._config,
|
||||
...options,
|
||||
fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
|
||||
headers: mergeHeaders(_config.headers, options.headers),
|
||||
serializedBody: undefined as string | undefined,
|
||||
};
|
||||
|
||||
if (opts.security) {
|
||||
await setAuthParams(opts);
|
||||
}
|
||||
|
||||
if (opts.requestValidator) {
|
||||
await opts.requestValidator(opts);
|
||||
}
|
||||
|
||||
if (opts.body !== undefined && opts.bodySerializer) {
|
||||
opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;
|
||||
}
|
||||
|
||||
// remove Content-Type header if body is empty to avoid sending invalid requests
|
||||
if (opts.body === undefined || opts.serializedBody === '') {
|
||||
opts.headers.delete('Content-Type');
|
||||
}
|
||||
|
||||
const resolvedOpts = opts as typeof opts &
|
||||
ResolvedRequestOptions<TResponseStyle, ThrowOnError, Url>;
|
||||
const url = buildUrl(resolvedOpts);
|
||||
|
||||
return { opts: resolvedOpts, url };
|
||||
};
|
||||
|
||||
const request: Client['request'] = async (options) => {
|
||||
const throwOnError = options.throwOnError ?? _config.throwOnError;
|
||||
const responseStyle = options.responseStyle ?? _config.responseStyle;
|
||||
|
||||
let request: Request | undefined;
|
||||
let response: Response | undefined;
|
||||
|
||||
try {
|
||||
const { opts, url } = await beforeRequest(options);
|
||||
const requestInit: ReqInit = {
|
||||
redirect: 'follow',
|
||||
...opts,
|
||||
body: getValidRequestBody(opts),
|
||||
};
|
||||
|
||||
request = new Request(url, requestInit);
|
||||
|
||||
for (const fn of interceptors.request.fns) {
|
||||
if (fn) {
|
||||
request = await fn(request, opts);
|
||||
}
|
||||
}
|
||||
|
||||
// fetch must be assigned here, otherwise it would throw the error:
|
||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||
const _fetch = opts.fetch!;
|
||||
|
||||
response = await _fetch(request);
|
||||
|
||||
for (const fn of interceptors.response.fns) {
|
||||
if (fn) {
|
||||
response = await fn(response, request, opts);
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
request,
|
||||
response,
|
||||
};
|
||||
|
||||
if (response.ok) {
|
||||
const parseAs =
|
||||
(opts.parseAs === 'auto'
|
||||
? getParseAs(response.headers.get('Content-Type'))
|
||||
: opts.parseAs) ?? 'json';
|
||||
|
||||
if (response.status === 204 || response.headers.get('Content-Length') === '0') {
|
||||
let emptyData: any;
|
||||
switch (parseAs) {
|
||||
case 'arrayBuffer':
|
||||
case 'blob':
|
||||
case 'text':
|
||||
emptyData = await response[parseAs]();
|
||||
break;
|
||||
case 'formData':
|
||||
emptyData = new FormData();
|
||||
break;
|
||||
case 'stream':
|
||||
emptyData = response.body;
|
||||
break;
|
||||
case 'json':
|
||||
default:
|
||||
emptyData = {};
|
||||
break;
|
||||
}
|
||||
return opts.responseStyle === 'data'
|
||||
? emptyData
|
||||
: {
|
||||
data: emptyData,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
let data: any;
|
||||
switch (parseAs) {
|
||||
case 'arrayBuffer':
|
||||
case 'blob':
|
||||
case 'formData':
|
||||
case 'text':
|
||||
data = await response[parseAs]();
|
||||
break;
|
||||
case 'json': {
|
||||
// Some servers return 200 with no Content-Length and empty body.
|
||||
// response.json() would throw; read as text and parse if non-empty.
|
||||
const text = await response.text();
|
||||
data = text ? JSON.parse(text) : {};
|
||||
break;
|
||||
}
|
||||
case 'stream':
|
||||
return opts.responseStyle === 'data'
|
||||
? response.body
|
||||
: {
|
||||
data: response.body,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
if (parseAs === 'json') {
|
||||
if (opts.responseValidator) {
|
||||
await opts.responseValidator(data);
|
||||
}
|
||||
|
||||
if (opts.responseTransformer) {
|
||||
data = await opts.responseTransformer(data);
|
||||
}
|
||||
}
|
||||
|
||||
return opts.responseStyle === 'data'
|
||||
? data
|
||||
: {
|
||||
data,
|
||||
...result,
|
||||
};
|
||||
}
|
||||
|
||||
const textError = await response.text();
|
||||
let jsonError: unknown;
|
||||
|
||||
try {
|
||||
jsonError = JSON.parse(textError);
|
||||
} catch {
|
||||
// noop
|
||||
}
|
||||
|
||||
throw jsonError ?? textError;
|
||||
} catch (error) {
|
||||
let finalError = error;
|
||||
|
||||
for (const fn of interceptors.error.fns) {
|
||||
if (fn) {
|
||||
finalError = await fn(finalError, response, request, options as ResolvedRequestOptions);
|
||||
}
|
||||
}
|
||||
|
||||
finalError = finalError || {};
|
||||
|
||||
if (throwOnError) {
|
||||
throw finalError;
|
||||
}
|
||||
|
||||
// TODO: we probably want to return error and improve types
|
||||
return responseStyle === 'data'
|
||||
? undefined
|
||||
: {
|
||||
error: finalError,
|
||||
request,
|
||||
response,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
|
||||
request({ ...options, method });
|
||||
|
||||
const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
|
||||
const { opts, url } = await beforeRequest(options);
|
||||
return createSseClient({
|
||||
...opts,
|
||||
body: opts.body as BodyInit | null | undefined,
|
||||
method,
|
||||
onRequest: async (url, init) => {
|
||||
let request = new Request(url, init);
|
||||
for (const fn of interceptors.request.fns) {
|
||||
if (fn) {
|
||||
request = await fn(request, opts);
|
||||
}
|
||||
}
|
||||
return request;
|
||||
},
|
||||
serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,
|
||||
url,
|
||||
});
|
||||
};
|
||||
|
||||
const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });
|
||||
|
||||
return {
|
||||
buildUrl: _buildUrl,
|
||||
connect: makeMethodFn('CONNECT'),
|
||||
delete: makeMethodFn('DELETE'),
|
||||
get: makeMethodFn('GET'),
|
||||
getConfig,
|
||||
head: makeMethodFn('HEAD'),
|
||||
interceptors,
|
||||
options: makeMethodFn('OPTIONS'),
|
||||
patch: makeMethodFn('PATCH'),
|
||||
post: makeMethodFn('POST'),
|
||||
put: makeMethodFn('PUT'),
|
||||
request,
|
||||
setConfig,
|
||||
sse: {
|
||||
connect: makeSseFn('CONNECT'),
|
||||
delete: makeSseFn('DELETE'),
|
||||
get: makeSseFn('GET'),
|
||||
head: makeSseFn('HEAD'),
|
||||
options: makeSseFn('OPTIONS'),
|
||||
patch: makeSseFn('PATCH'),
|
||||
post: makeSseFn('POST'),
|
||||
put: makeSseFn('PUT'),
|
||||
trace: makeSseFn('TRACE'),
|
||||
},
|
||||
trace: makeMethodFn('TRACE'),
|
||||
} as Client;
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type { Auth } from '../core/auth.gen';
|
||||
export type { QuerySerializerOptions } from '../core/bodySerializer.gen';
|
||||
export {
|
||||
formDataBodySerializer,
|
||||
jsonBodySerializer,
|
||||
urlSearchParamsBodySerializer,
|
||||
} from '../core/bodySerializer.gen';
|
||||
export { buildClientParams } from '../core/params.gen';
|
||||
export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen';
|
||||
export type { ServerSentEventsResult } from '../core/serverSentEvents.gen';
|
||||
export type { ClientMeta } from '../core/types.gen';
|
||||
export { createClient } from './client.gen';
|
||||
export type {
|
||||
Client,
|
||||
ClientOptions,
|
||||
Config,
|
||||
CreateClientConfig,
|
||||
Options,
|
||||
RequestOptions,
|
||||
RequestResult,
|
||||
ResolvedRequestOptions,
|
||||
ResponseStyle,
|
||||
TDataShape,
|
||||
} from './types.gen';
|
||||
export { createConfig, mergeHeaders } from './utils.gen';
|
||||
@@ -0,0 +1,218 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Auth } from '../core/auth.gen';
|
||||
import type {
|
||||
ServerSentEventsOptions,
|
||||
ServerSentEventsResult,
|
||||
} from '../core/serverSentEvents.gen';
|
||||
import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen';
|
||||
import type { Middleware } from './utils.gen';
|
||||
|
||||
export type ResponseStyle = 'data' | 'fields';
|
||||
|
||||
export interface Config<T extends ClientOptions = ClientOptions>
|
||||
extends Omit<RequestInit, 'body' | 'headers' | 'method'>, CoreConfig {
|
||||
/**
|
||||
* Base URL for all requests made by this client.
|
||||
*/
|
||||
baseUrl?: T['baseUrl'];
|
||||
/**
|
||||
* Fetch API implementation. You can use this option to provide a custom
|
||||
* fetch instance.
|
||||
*
|
||||
* @default globalThis.fetch
|
||||
*/
|
||||
fetch?: typeof fetch;
|
||||
/**
|
||||
* Please don't use the Fetch client for Next.js applications. The `next`
|
||||
* options won't have any effect.
|
||||
*
|
||||
* Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
|
||||
*/
|
||||
next?: never;
|
||||
/**
|
||||
* Return the response data parsed in a specified format. By default, `auto`
|
||||
* will infer the appropriate method from the `Content-Type` response header.
|
||||
* You can override this behavior with any of the {@link Body} methods.
|
||||
* Select `stream` if you don't want to parse response data at all.
|
||||
*
|
||||
* @default 'auto'
|
||||
*/
|
||||
parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text';
|
||||
/**
|
||||
* Should we return only data or multiple fields (data, error, response, etc.)?
|
||||
*
|
||||
* @default 'fields'
|
||||
*/
|
||||
responseStyle?: ResponseStyle;
|
||||
/**
|
||||
* Throw an error instead of returning it in the response?
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
throwOnError?: T['throwOnError'];
|
||||
}
|
||||
|
||||
export interface RequestOptions<
|
||||
TData = unknown,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
>
|
||||
extends
|
||||
Config<{
|
||||
responseStyle: TResponseStyle;
|
||||
throwOnError: ThrowOnError;
|
||||
}>,
|
||||
Pick<
|
||||
ServerSentEventsOptions<TData>,
|
||||
| 'onRequest'
|
||||
| 'onSseError'
|
||||
| 'onSseEvent'
|
||||
| 'sseDefaultRetryDelay'
|
||||
| 'sseMaxRetryAttempts'
|
||||
| 'sseMaxRetryDelay'
|
||||
> {
|
||||
/**
|
||||
* Any body that you want to add to your request.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
|
||||
*/
|
||||
body?: unknown;
|
||||
path?: Record<string, unknown>;
|
||||
query?: Record<string, unknown>;
|
||||
/**
|
||||
* Security mechanism(s) to use for the request.
|
||||
*/
|
||||
security?: ReadonlyArray<Auth>;
|
||||
url: Url;
|
||||
}
|
||||
|
||||
export interface ResolvedRequestOptions<
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
ThrowOnError extends boolean = boolean,
|
||||
Url extends string = string,
|
||||
> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
|
||||
headers: Headers;
|
||||
serializedBody?: string;
|
||||
}
|
||||
|
||||
export type RequestResult<
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = boolean,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
> = ThrowOnError extends true
|
||||
? Promise<
|
||||
TResponseStyle extends 'data'
|
||||
? TData extends Record<string, unknown>
|
||||
? TData[keyof TData]
|
||||
: TData
|
||||
: {
|
||||
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
|
||||
request: Request;
|
||||
response: Response;
|
||||
}
|
||||
>
|
||||
: Promise<
|
||||
TResponseStyle extends 'data'
|
||||
? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined
|
||||
: (
|
||||
| {
|
||||
data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
|
||||
error: undefined;
|
||||
}
|
||||
| {
|
||||
data: undefined;
|
||||
error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
|
||||
}
|
||||
) & {
|
||||
/** request may be undefined, because error may be from building the request object itself */
|
||||
request?: Request;
|
||||
/** response may be undefined, because error may be from building the request object itself or from a network error */
|
||||
response?: Response;
|
||||
}
|
||||
>;
|
||||
|
||||
export interface ClientOptions {
|
||||
baseUrl?: string;
|
||||
responseStyle?: ResponseStyle;
|
||||
throwOnError?: boolean;
|
||||
}
|
||||
|
||||
type MethodFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
|
||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
||||
|
||||
type SseFn = <
|
||||
TData = unknown,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
_TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
>(
|
||||
options: Omit<RequestOptions<never, TResponseStyle, ThrowOnError>, 'method'>,
|
||||
) => Promise<ServerSentEventsResult<TData>>;
|
||||
|
||||
type RequestFn = <
|
||||
TData = unknown,
|
||||
TError = unknown,
|
||||
ThrowOnError extends boolean = false,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
>(
|
||||
options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> &
|
||||
Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>,
|
||||
) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
|
||||
|
||||
type BuildUrlFn = <
|
||||
TData extends {
|
||||
body?: unknown;
|
||||
path?: Record<string, unknown>;
|
||||
query?: Record<string, unknown>;
|
||||
url: string;
|
||||
},
|
||||
>(
|
||||
options: TData & Options<TData>,
|
||||
) => string;
|
||||
|
||||
export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
|
||||
interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
|
||||
};
|
||||
|
||||
/**
|
||||
* The `createClientConfig()` function will be called on client initialization
|
||||
* and the returned object will become the client's initial configuration.
|
||||
*
|
||||
* You may want to initialize your client this way instead of calling
|
||||
* `setConfig()`. This is useful for example if you're using Next.js
|
||||
* to ensure your client always has the correct values.
|
||||
*/
|
||||
export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
|
||||
override?: Config<ClientOptions & T>,
|
||||
) => Config<Required<ClientOptions> & T>;
|
||||
|
||||
export interface TDataShape {
|
||||
body?: unknown;
|
||||
headers?: unknown;
|
||||
path?: unknown;
|
||||
query?: unknown;
|
||||
url: string;
|
||||
}
|
||||
|
||||
type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
|
||||
|
||||
export type Options<
|
||||
TData extends TDataShape = TDataShape,
|
||||
ThrowOnError extends boolean = boolean,
|
||||
TResponse = unknown,
|
||||
TResponseStyle extends ResponseStyle = 'fields',
|
||||
> = OmitKeys<
|
||||
RequestOptions<TResponse, TResponseStyle, ThrowOnError>,
|
||||
'body' | 'path' | 'query' | 'url'
|
||||
> &
|
||||
([TData] extends [never] ? unknown : Omit<TData, 'url'>);
|
||||
@@ -0,0 +1,316 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { getAuthToken } from '../core/auth.gen';
|
||||
import type { QuerySerializerOptions } from '../core/bodySerializer.gen';
|
||||
import { jsonBodySerializer } from '../core/bodySerializer.gen';
|
||||
import {
|
||||
serializeArrayParam,
|
||||
serializeObjectParam,
|
||||
serializePrimitiveParam,
|
||||
} from '../core/pathSerializer.gen';
|
||||
import { getUrl } from '../core/utils.gen';
|
||||
import type { Client, ClientOptions, Config, RequestOptions } from './types.gen';
|
||||
|
||||
export const createQuerySerializer = <T = unknown>({
|
||||
parameters = {},
|
||||
...args
|
||||
}: QuerySerializerOptions = {}): ((queryParams: T) => string) => {
|
||||
const querySerializer = (queryParams: T): string => {
|
||||
const search: string[] = [];
|
||||
if (queryParams && typeof queryParams === 'object') {
|
||||
for (const name in queryParams) {
|
||||
const value = queryParams[name];
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const options = parameters[name] || args;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const serializedArray = serializeArrayParam({
|
||||
allowReserved: options.allowReserved,
|
||||
explode: true,
|
||||
name,
|
||||
style: 'form',
|
||||
value,
|
||||
...options.array,
|
||||
});
|
||||
if (serializedArray) search.push(serializedArray);
|
||||
} else if (typeof value === 'object') {
|
||||
const serializedObject = serializeObjectParam({
|
||||
allowReserved: options.allowReserved,
|
||||
explode: true,
|
||||
name,
|
||||
style: 'deepObject',
|
||||
value: value as Record<string, unknown>,
|
||||
...options.object,
|
||||
});
|
||||
if (serializedObject) search.push(serializedObject);
|
||||
} else {
|
||||
const serializedPrimitive = serializePrimitiveParam({
|
||||
allowReserved: options.allowReserved,
|
||||
name,
|
||||
value: value as string,
|
||||
});
|
||||
if (serializedPrimitive) search.push(serializedPrimitive);
|
||||
}
|
||||
}
|
||||
}
|
||||
return search.join('&');
|
||||
};
|
||||
return querySerializer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Infers parseAs value from provided Content-Type header.
|
||||
*/
|
||||
export const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {
|
||||
if (!contentType) {
|
||||
// If no Content-Type header is provided, the best we can do is return the raw response body,
|
||||
// which is effectively the same as the 'stream' option.
|
||||
return 'stream';
|
||||
}
|
||||
|
||||
const cleanContent = contentType.split(';')[0]?.trim();
|
||||
|
||||
if (!cleanContent) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {
|
||||
return 'json';
|
||||
}
|
||||
|
||||
if (cleanContent === 'multipart/form-data') {
|
||||
return 'formData';
|
||||
}
|
||||
|
||||
if (
|
||||
['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))
|
||||
) {
|
||||
return 'blob';
|
||||
}
|
||||
|
||||
if (cleanContent.startsWith('text/')) {
|
||||
return 'text';
|
||||
}
|
||||
|
||||
return;
|
||||
};
|
||||
|
||||
const checkForExistence = (
|
||||
options: Pick<RequestOptions, 'auth' | 'query'> & {
|
||||
headers: Headers;
|
||||
},
|
||||
name?: string,
|
||||
): boolean => {
|
||||
if (!name) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
options.headers.has(name) ||
|
||||
options.query?.[name] ||
|
||||
options.headers.get('Cookie')?.includes(`${name}=`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
export async function setAuthParams(
|
||||
options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {
|
||||
headers: Headers;
|
||||
},
|
||||
): Promise<void> {
|
||||
for (const auth of options.security ?? []) {
|
||||
if (checkForExistence(options, auth.name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const token = await getAuthToken(auth, options.auth);
|
||||
|
||||
if (!token) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = auth.name ?? 'Authorization';
|
||||
|
||||
switch (auth.in) {
|
||||
case 'query':
|
||||
if (!options.query) {
|
||||
options.query = {};
|
||||
}
|
||||
options.query[name] = token;
|
||||
break;
|
||||
case 'cookie':
|
||||
options.headers.append('Cookie', `${name}=${token}`);
|
||||
break;
|
||||
case 'header':
|
||||
default:
|
||||
options.headers.set(name, token);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const buildUrl: Client['buildUrl'] = (options) =>
|
||||
getUrl({
|
||||
baseUrl: options.baseUrl as string,
|
||||
path: options.path,
|
||||
query: options.query,
|
||||
querySerializer:
|
||||
typeof options.querySerializer === 'function'
|
||||
? options.querySerializer
|
||||
: createQuerySerializer(options.querySerializer),
|
||||
url: options.url,
|
||||
});
|
||||
|
||||
export const mergeConfigs = (a: Config, b: Config): Config => {
|
||||
const config = { ...a, ...b };
|
||||
if (config.baseUrl?.endsWith('/')) {
|
||||
config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
|
||||
}
|
||||
config.headers = mergeHeaders(a.headers, b.headers);
|
||||
return config;
|
||||
};
|
||||
|
||||
const headersEntries = (headers: Headers): Array<[string, string]> => {
|
||||
const entries: Array<[string, string]> = [];
|
||||
headers.forEach((value, key) => {
|
||||
entries.push([key, value]);
|
||||
});
|
||||
return entries;
|
||||
};
|
||||
|
||||
export const mergeHeaders = (
|
||||
...headers: Array<Required<Config>['headers'] | undefined>
|
||||
): Headers => {
|
||||
const mergedHeaders = new Headers();
|
||||
for (const header of headers) {
|
||||
if (!header) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
|
||||
|
||||
for (const [key, value] of iterator) {
|
||||
if (value === null) {
|
||||
mergedHeaders.delete(key);
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const v of value) {
|
||||
mergedHeaders.append(key, v as string);
|
||||
}
|
||||
} else if (value !== undefined) {
|
||||
// assume object headers are meant to be JSON stringified, i.e., their
|
||||
// content value in OpenAPI specification is 'application/json'
|
||||
mergedHeaders.set(
|
||||
key,
|
||||
typeof value === 'object' ? JSON.stringify(value) : (value as string),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return mergedHeaders;
|
||||
};
|
||||
|
||||
type ErrInterceptor<Err, Res, Req, Options> = (
|
||||
error: Err,
|
||||
/** response may be undefined due to a network error where no response object is produced */
|
||||
response: Res | undefined,
|
||||
/** request may be undefined, because error may be from building the request object itself */
|
||||
request: Req | undefined,
|
||||
options: Options,
|
||||
) => Err | Promise<Err>;
|
||||
|
||||
type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
|
||||
|
||||
type ResInterceptor<Res, Req, Options> = (
|
||||
response: Res,
|
||||
request: Req,
|
||||
options: Options,
|
||||
) => Res | Promise<Res>;
|
||||
|
||||
class Interceptors<Interceptor> {
|
||||
fns: Array<Interceptor | null> = [];
|
||||
|
||||
clear(): void {
|
||||
this.fns = [];
|
||||
}
|
||||
|
||||
eject(id: number | Interceptor): void {
|
||||
const index = this.getInterceptorIndex(id);
|
||||
if (this.fns[index]) {
|
||||
this.fns[index] = null;
|
||||
}
|
||||
}
|
||||
|
||||
exists(id: number | Interceptor): boolean {
|
||||
const index = this.getInterceptorIndex(id);
|
||||
return Boolean(this.fns[index]);
|
||||
}
|
||||
|
||||
getInterceptorIndex(id: number | Interceptor): number {
|
||||
if (typeof id === 'number') {
|
||||
return this.fns[id] ? id : -1;
|
||||
}
|
||||
return this.fns.indexOf(id);
|
||||
}
|
||||
|
||||
update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {
|
||||
const index = this.getInterceptorIndex(id);
|
||||
if (this.fns[index]) {
|
||||
this.fns[index] = fn;
|
||||
return id;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
use(fn: Interceptor): number {
|
||||
this.fns.push(fn);
|
||||
return this.fns.length - 1;
|
||||
}
|
||||
}
|
||||
|
||||
export interface Middleware<Req, Res, Err, Options> {
|
||||
error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
|
||||
request: Interceptors<ReqInterceptor<Req, Options>>;
|
||||
response: Interceptors<ResInterceptor<Res, Req, Options>>;
|
||||
}
|
||||
|
||||
export const createInterceptors = <Req, Res, Err, Options>(): Middleware<
|
||||
Req,
|
||||
Res,
|
||||
Err,
|
||||
Options
|
||||
> => ({
|
||||
error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
|
||||
request: new Interceptors<ReqInterceptor<Req, Options>>(),
|
||||
response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
|
||||
});
|
||||
|
||||
const defaultQuerySerializer = createQuerySerializer({
|
||||
allowReserved: false,
|
||||
array: {
|
||||
explode: true,
|
||||
style: 'form',
|
||||
},
|
||||
object: {
|
||||
explode: true,
|
||||
style: 'deepObject',
|
||||
},
|
||||
});
|
||||
|
||||
const defaultHeaders = {
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
|
||||
export const createConfig = <T extends ClientOptions = ClientOptions>(
|
||||
override: Config<Omit<ClientOptions, keyof T> & T> = {},
|
||||
): Config<Omit<ClientOptions, keyof T> & T> => ({
|
||||
...jsonBodySerializer,
|
||||
headers: defaultHeaders,
|
||||
parseAs: 'auto',
|
||||
querySerializer: defaultQuerySerializer,
|
||||
...override,
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export type AuthToken = string | undefined;
|
||||
|
||||
export interface Auth {
|
||||
/**
|
||||
* Which part of the request do we use to send the auth?
|
||||
*
|
||||
* @default 'header'
|
||||
*/
|
||||
in?: 'header' | 'query' | 'cookie';
|
||||
/**
|
||||
* A unique identifier for the security scheme.
|
||||
*
|
||||
* Defined only when there are multiple security schemes whose `Auth`
|
||||
* shape would otherwise be identical.
|
||||
*/
|
||||
key?: string;
|
||||
/**
|
||||
* Header or query parameter name.
|
||||
*
|
||||
* @default 'Authorization'
|
||||
*/
|
||||
name?: string;
|
||||
scheme?: 'basic' | 'bearer';
|
||||
type: 'apiKey' | 'http';
|
||||
}
|
||||
|
||||
export const getAuthToken = async (
|
||||
auth: Auth,
|
||||
callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
|
||||
): Promise<string | undefined> => {
|
||||
const token = typeof callback === 'function' ? await callback(auth) : callback;
|
||||
|
||||
if (!token) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (auth.scheme === 'bearer') {
|
||||
return `Bearer ${token}`;
|
||||
}
|
||||
|
||||
if (auth.scheme === 'basic') {
|
||||
return `Basic ${btoa(token)}`;
|
||||
}
|
||||
|
||||
return token;
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen';
|
||||
|
||||
export type QuerySerializer = (query: Record<string, unknown>) => string;
|
||||
|
||||
export type BodySerializer = (body: unknown) => unknown;
|
||||
|
||||
type QuerySerializerOptionsObject = {
|
||||
allowReserved?: boolean;
|
||||
array?: Partial<SerializerOptions<ArrayStyle>>;
|
||||
object?: Partial<SerializerOptions<ObjectStyle>>;
|
||||
};
|
||||
|
||||
export type QuerySerializerOptions = QuerySerializerOptionsObject & {
|
||||
/**
|
||||
* Per-parameter serialization overrides. When provided, these settings
|
||||
* override the global array/object settings for specific parameter names.
|
||||
*/
|
||||
parameters?: Record<string, QuerySerializerOptionsObject>;
|
||||
};
|
||||
|
||||
const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {
|
||||
if (typeof value === 'string' || value instanceof Blob) {
|
||||
data.append(key, value);
|
||||
} else if (value instanceof Date) {
|
||||
data.append(key, value.toISOString());
|
||||
} else {
|
||||
data.append(key, JSON.stringify(value));
|
||||
}
|
||||
};
|
||||
|
||||
const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {
|
||||
if (typeof value === 'string') {
|
||||
data.append(key, value);
|
||||
} else {
|
||||
data.append(key, JSON.stringify(value));
|
||||
}
|
||||
};
|
||||
|
||||
export const formDataBodySerializer = {
|
||||
bodySerializer: (body: unknown): FormData => {
|
||||
const data = new FormData();
|
||||
|
||||
Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v) => serializeFormDataPair(data, key, v));
|
||||
} else {
|
||||
serializeFormDataPair(data, key, value);
|
||||
}
|
||||
});
|
||||
|
||||
return data;
|
||||
},
|
||||
};
|
||||
|
||||
export const jsonBodySerializer = {
|
||||
bodySerializer: (body: unknown): string =>
|
||||
JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),
|
||||
};
|
||||
|
||||
export const urlSearchParamsBodySerializer = {
|
||||
bodySerializer: (body: unknown): string => {
|
||||
const data = new URLSearchParams();
|
||||
|
||||
Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
|
||||
} else {
|
||||
serializeUrlSearchParamsPair(data, key, value);
|
||||
}
|
||||
});
|
||||
|
||||
return data.toString();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,178 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
type Slot = 'body' | 'headers' | 'path' | 'query';
|
||||
|
||||
export type Field =
|
||||
| {
|
||||
in: Exclude<Slot, 'body'>;
|
||||
/**
|
||||
* Field name. This is the name we want the user to see and use.
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* Field mapped name. This is the name we want to use in the request.
|
||||
* If omitted, we use the same value as `key`.
|
||||
*/
|
||||
map?: string;
|
||||
}
|
||||
| {
|
||||
in: Extract<Slot, 'body'>;
|
||||
/**
|
||||
* Key isn't required for bodies.
|
||||
*/
|
||||
key?: string;
|
||||
map?: string;
|
||||
}
|
||||
| {
|
||||
/**
|
||||
* Field name. This is the name we want the user to see and use.
|
||||
*/
|
||||
key: string;
|
||||
/**
|
||||
* Field mapped name. This is the name we want to use in the request.
|
||||
* If `in` is omitted, `map` aliases `key` to the transport layer.
|
||||
*/
|
||||
map: Slot;
|
||||
};
|
||||
|
||||
export interface Fields {
|
||||
allowExtra?: Partial<Record<Slot, boolean>>;
|
||||
args?: ReadonlyArray<Field>;
|
||||
}
|
||||
|
||||
export type FieldsConfig = ReadonlyArray<Field | Fields>;
|
||||
|
||||
const extraPrefixesMap: Record<string, Slot> = {
|
||||
$body_: 'body',
|
||||
$headers_: 'headers',
|
||||
$path_: 'path',
|
||||
$query_: 'query',
|
||||
};
|
||||
const extraPrefixes = Object.entries(extraPrefixesMap);
|
||||
|
||||
type KeyMap = Map<
|
||||
string,
|
||||
| {
|
||||
in: Slot;
|
||||
map?: string;
|
||||
}
|
||||
| {
|
||||
in?: never;
|
||||
map: Slot;
|
||||
}
|
||||
>;
|
||||
|
||||
function buildKeyMap(fields: FieldsConfig, map?: KeyMap): KeyMap {
|
||||
if (!map) {
|
||||
map = new Map();
|
||||
}
|
||||
|
||||
for (const config of fields) {
|
||||
if ('in' in config) {
|
||||
if (config.key) {
|
||||
map.set(config.key, {
|
||||
in: config.in,
|
||||
map: config.map,
|
||||
});
|
||||
}
|
||||
} else if ('key' in config) {
|
||||
map.set(config.key, {
|
||||
map: config.map,
|
||||
});
|
||||
} else if (config.args) {
|
||||
buildKeyMap(config.args, map);
|
||||
}
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
interface Params {
|
||||
body?: unknown;
|
||||
headers: Record<string, unknown>;
|
||||
path: Record<string, unknown>;
|
||||
query: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function stripEmptySlots(params: Params): void {
|
||||
for (const [slot, value] of Object.entries(params)) {
|
||||
if (slot === 'body') continue;
|
||||
if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {
|
||||
delete params[slot as Slot];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function buildClientParams(args: ReadonlyArray<unknown>, fields: FieldsConfig): Params {
|
||||
const params: Params = {
|
||||
headers: Object.create(null),
|
||||
path: Object.create(null),
|
||||
query: Object.create(null),
|
||||
};
|
||||
|
||||
const map = buildKeyMap(fields);
|
||||
|
||||
function writeSlot(slot: Slot, key: string, value: unknown): void {
|
||||
let record = params[slot] as Record<string, unknown> | undefined;
|
||||
if (record === undefined) {
|
||||
record = Object.create(null) as Record<string, unknown>;
|
||||
params[slot] = record;
|
||||
}
|
||||
record[key] = value;
|
||||
}
|
||||
|
||||
let config: FieldsConfig[number] | undefined;
|
||||
|
||||
for (const [index, arg] of args.entries()) {
|
||||
if (fields[index]) {
|
||||
config = fields[index];
|
||||
}
|
||||
|
||||
if (!config) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ('in' in config) {
|
||||
if (config.key) {
|
||||
const field = map.get(config.key)!;
|
||||
const name = field.map || config.key;
|
||||
if (field.in) {
|
||||
writeSlot(field.in, name, arg);
|
||||
}
|
||||
} else {
|
||||
params.body = arg;
|
||||
}
|
||||
} else {
|
||||
for (const [key, value] of Object.entries(arg ?? {})) {
|
||||
const field = map.get(key);
|
||||
|
||||
if (field) {
|
||||
if (field.in) {
|
||||
const name = field.map || key;
|
||||
writeSlot(field.in, name, value);
|
||||
} else {
|
||||
params[field.map] = value;
|
||||
}
|
||||
} else {
|
||||
const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));
|
||||
|
||||
if (extra) {
|
||||
const [prefix, slot] = extra;
|
||||
writeSlot(slot, key.slice(prefix.length), value);
|
||||
} else if ('allowExtra' in config && config.allowExtra) {
|
||||
for (const [slot, allowed] of Object.entries(config.allowExtra)) {
|
||||
if (allowed) {
|
||||
writeSlot(slot as Slot, key, value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stripEmptySlots(params);
|
||||
|
||||
return params;
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}
|
||||
|
||||
interface SerializePrimitiveOptions {
|
||||
allowReserved?: boolean;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface SerializerOptions<T> {
|
||||
/**
|
||||
* @default true
|
||||
*/
|
||||
explode: boolean;
|
||||
style: T;
|
||||
}
|
||||
|
||||
export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
|
||||
export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
|
||||
type MatrixStyle = 'label' | 'matrix' | 'simple';
|
||||
export type ObjectStyle = 'form' | 'deepObject';
|
||||
type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
|
||||
|
||||
interface SerializePrimitiveParam extends SerializePrimitiveOptions {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export const separatorArrayExplode = (style: ArraySeparatorStyle): '.' | ';' | ',' | '&' => {
|
||||
switch (style) {
|
||||
case 'label':
|
||||
return '.';
|
||||
case 'matrix':
|
||||
return ';';
|
||||
case 'simple':
|
||||
return ',';
|
||||
default:
|
||||
return '&';
|
||||
}
|
||||
};
|
||||
|
||||
export const separatorArrayNoExplode = (style: ArraySeparatorStyle): ',' | '|' | '%20' => {
|
||||
switch (style) {
|
||||
case 'form':
|
||||
return ',';
|
||||
case 'pipeDelimited':
|
||||
return '|';
|
||||
case 'spaceDelimited':
|
||||
return '%20';
|
||||
default:
|
||||
return ',';
|
||||
}
|
||||
};
|
||||
|
||||
export const separatorObjectExplode = (style: ObjectSeparatorStyle): '.' | ';' | ',' | '&' => {
|
||||
switch (style) {
|
||||
case 'label':
|
||||
return '.';
|
||||
case 'matrix':
|
||||
return ';';
|
||||
case 'simple':
|
||||
return ',';
|
||||
default:
|
||||
return '&';
|
||||
}
|
||||
};
|
||||
|
||||
export const serializeArrayParam = ({
|
||||
allowReserved,
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value,
|
||||
}: SerializeOptions<ArraySeparatorStyle> & {
|
||||
value: unknown[];
|
||||
}): string => {
|
||||
if (!explode) {
|
||||
const joinedValues = (
|
||||
allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
|
||||
).join(separatorArrayNoExplode(style));
|
||||
switch (style) {
|
||||
case 'label':
|
||||
return `.${joinedValues}`;
|
||||
case 'matrix':
|
||||
return `;${name}=${joinedValues}`;
|
||||
case 'simple':
|
||||
return joinedValues;
|
||||
default:
|
||||
return `${name}=${joinedValues}`;
|
||||
}
|
||||
}
|
||||
|
||||
const separator = separatorArrayExplode(style);
|
||||
const joinedValues = value
|
||||
.map((v) => {
|
||||
if (style === 'label' || style === 'simple') {
|
||||
return allowReserved ? v : encodeURIComponent(v as string);
|
||||
}
|
||||
|
||||
return serializePrimitiveParam({
|
||||
allowReserved,
|
||||
name,
|
||||
value: v as string,
|
||||
});
|
||||
})
|
||||
.join(separator);
|
||||
return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
|
||||
};
|
||||
|
||||
export const serializePrimitiveParam = ({
|
||||
allowReserved,
|
||||
name,
|
||||
value,
|
||||
}: SerializePrimitiveParam): string => {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
throw new Error(
|
||||
'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',
|
||||
);
|
||||
}
|
||||
|
||||
return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
|
||||
};
|
||||
|
||||
export const serializeObjectParam = ({
|
||||
allowReserved,
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value,
|
||||
valueOnly,
|
||||
}: SerializeOptions<ObjectSeparatorStyle> & {
|
||||
value: Record<string, unknown> | Date;
|
||||
valueOnly?: boolean;
|
||||
}): string => {
|
||||
if (value instanceof Date) {
|
||||
return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
|
||||
}
|
||||
|
||||
if (style !== 'deepObject' && !explode) {
|
||||
let values: string[] = [];
|
||||
Object.entries(value).forEach(([key, v]) => {
|
||||
values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];
|
||||
});
|
||||
const joinedValues = values.join(',');
|
||||
switch (style) {
|
||||
case 'form':
|
||||
return `${name}=${joinedValues}`;
|
||||
case 'label':
|
||||
return `.${joinedValues}`;
|
||||
case 'matrix':
|
||||
return `;${name}=${joinedValues}`;
|
||||
default:
|
||||
return joinedValues;
|
||||
}
|
||||
}
|
||||
|
||||
const separator = separatorObjectExplode(style);
|
||||
const joinedValues = Object.entries(value)
|
||||
.map(([key, v]) =>
|
||||
serializePrimitiveParam({
|
||||
allowReserved,
|
||||
name: style === 'deepObject' ? `${name}[${key}]` : key,
|
||||
value: v as string,
|
||||
}),
|
||||
)
|
||||
.join(separator);
|
||||
return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
|
||||
};
|
||||
@@ -0,0 +1,117 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
/**
|
||||
* JSON-friendly union that mirrors what Pinia Colada can hash.
|
||||
*/
|
||||
export type JsonValue =
|
||||
| null
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| JsonValue[]
|
||||
| { [key: string]: JsonValue };
|
||||
|
||||
/**
|
||||
* Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
|
||||
*/
|
||||
export const queryKeyJsonReplacer = (_key: string, value: unknown): unknown | undefined => {
|
||||
if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof value === 'bigint') {
|
||||
return value.toString();
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString();
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
/**
|
||||
* Safely stringifies a value and parses it back into a JsonValue.
|
||||
*/
|
||||
export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => {
|
||||
try {
|
||||
const json = JSON.stringify(input, queryKeyJsonReplacer);
|
||||
if (json === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return JSON.parse(json) as JsonValue;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Detects plain objects (including objects with a null prototype).
|
||||
*/
|
||||
const isPlainObject = (value: unknown): value is Record<string, unknown> => {
|
||||
if (value === null || typeof value !== 'object') {
|
||||
return false;
|
||||
}
|
||||
const prototype = Object.getPrototypeOf(value as object);
|
||||
return prototype === Object.prototype || prototype === null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Turns URLSearchParams into a sorted JSON object for deterministic keys.
|
||||
*/
|
||||
const serializeSearchParams = (params: URLSearchParams): JsonValue => {
|
||||
const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b));
|
||||
const result: Record<string, JsonValue> = {};
|
||||
|
||||
for (const [key, value] of entries) {
|
||||
const existing = result[key];
|
||||
if (existing === undefined) {
|
||||
result[key] = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(existing)) {
|
||||
(existing as string[]).push(value);
|
||||
} else {
|
||||
result[key] = [existing, value];
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Normalizes any accepted value into a JSON-friendly shape for query keys.
|
||||
*/
|
||||
export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => {
|
||||
if (value === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof value === 'bigint') {
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
return value.toISOString();
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return stringifyToJsonValue(value);
|
||||
}
|
||||
|
||||
if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
|
||||
return serializeSearchParams(value);
|
||||
}
|
||||
|
||||
if (isPlainObject(value)) {
|
||||
return stringifyToJsonValue(value);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
};
|
||||
@@ -0,0 +1,242 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Config } from './types.gen';
|
||||
|
||||
export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &
|
||||
Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
|
||||
/**
|
||||
* Fetch API implementation. You can use this option to provide a custom
|
||||
* fetch instance.
|
||||
*
|
||||
* @default globalThis.fetch
|
||||
*/
|
||||
fetch?: typeof fetch;
|
||||
/**
|
||||
* Implementing clients can call request interceptors inside this hook.
|
||||
*/
|
||||
onRequest?: (url: string, init: RequestInit) => Promise<Request>;
|
||||
/**
|
||||
* Callback invoked when a network or parsing error occurs during streaming.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @param error The error that occurred.
|
||||
*/
|
||||
onSseError?: (error: unknown) => void;
|
||||
/**
|
||||
* Callback invoked when an event is streamed from the server.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @param event Event streamed from the server.
|
||||
* @returns Nothing (void).
|
||||
*/
|
||||
onSseEvent?: (event: StreamEvent<TData>) => void;
|
||||
serializedBody?: RequestInit['body'];
|
||||
/**
|
||||
* Default retry delay in milliseconds.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @default 3000
|
||||
*/
|
||||
sseDefaultRetryDelay?: number;
|
||||
/**
|
||||
* Maximum number of retry attempts before giving up.
|
||||
*/
|
||||
sseMaxRetryAttempts?: number;
|
||||
/**
|
||||
* Maximum retry delay in milliseconds.
|
||||
*
|
||||
* Applies only when exponential backoff is used.
|
||||
*
|
||||
* This option applies only if the endpoint returns a stream of events.
|
||||
*
|
||||
* @default 30000
|
||||
*/
|
||||
sseMaxRetryDelay?: number;
|
||||
/**
|
||||
* Optional sleep function for retry backoff.
|
||||
*
|
||||
* Defaults to using `setTimeout`.
|
||||
*/
|
||||
sseSleepFn?: (ms: number) => Promise<void>;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export interface StreamEvent<TData = unknown> {
|
||||
data: TData;
|
||||
event?: string;
|
||||
id?: string;
|
||||
retry?: number;
|
||||
}
|
||||
|
||||
export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
|
||||
stream: AsyncGenerator<
|
||||
TData extends Record<string, unknown> ? TData[keyof TData] : TData,
|
||||
TReturn,
|
||||
TNext
|
||||
>;
|
||||
};
|
||||
|
||||
export function createSseClient<TData = unknown>({
|
||||
onRequest,
|
||||
onSseError,
|
||||
onSseEvent,
|
||||
responseTransformer,
|
||||
responseValidator,
|
||||
sseDefaultRetryDelay,
|
||||
sseMaxRetryAttempts,
|
||||
sseMaxRetryDelay,
|
||||
sseSleepFn,
|
||||
url,
|
||||
...options
|
||||
}: ServerSentEventsOptions): ServerSentEventsResult<TData> {
|
||||
let lastEventId: string | undefined;
|
||||
|
||||
const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
|
||||
|
||||
const createStream = async function* () {
|
||||
let retryDelay: number = sseDefaultRetryDelay ?? 3000;
|
||||
let attempt = 0;
|
||||
const signal = options.signal ?? new AbortController().signal;
|
||||
|
||||
while (true) {
|
||||
if (signal.aborted) break;
|
||||
|
||||
attempt++;
|
||||
|
||||
const headers =
|
||||
options.headers instanceof Headers
|
||||
? options.headers
|
||||
: new Headers(options.headers as Record<string, string> | undefined);
|
||||
|
||||
if (lastEventId !== undefined) {
|
||||
headers.set('Last-Event-ID', lastEventId);
|
||||
}
|
||||
|
||||
try {
|
||||
const requestInit: RequestInit = {
|
||||
redirect: 'follow',
|
||||
...options,
|
||||
body: options.serializedBody,
|
||||
headers,
|
||||
signal,
|
||||
};
|
||||
let request = new Request(url, requestInit);
|
||||
if (onRequest) {
|
||||
request = await onRequest(url, requestInit);
|
||||
}
|
||||
// fetch must be assigned here, otherwise it would throw the error:
|
||||
// TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
|
||||
const _fetch = options.fetch ?? globalThis.fetch;
|
||||
const response = await _fetch(request);
|
||||
|
||||
if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
|
||||
|
||||
if (!response.body) throw new Error('No body in SSE response');
|
||||
|
||||
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
|
||||
|
||||
let buffer = '';
|
||||
|
||||
const abortHandler = () => {
|
||||
try {
|
||||
reader.cancel();
|
||||
} catch {
|
||||
// noop
|
||||
}
|
||||
};
|
||||
|
||||
signal.addEventListener('abort', abortHandler);
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += value;
|
||||
buffer = buffer.replace(/\r\n?/g, '\n'); // normalize line endings
|
||||
|
||||
const chunks = buffer.split('\n\n');
|
||||
buffer = chunks.pop() ?? '';
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const lines = chunk.split('\n');
|
||||
const dataLines: Array<string> = [];
|
||||
let eventName: string | undefined;
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data:')) {
|
||||
dataLines.push(line.replace(/^data:\s*/, ''));
|
||||
} else if (line.startsWith('event:')) {
|
||||
eventName = line.replace(/^event:\s*/, '');
|
||||
} else if (line.startsWith('id:')) {
|
||||
lastEventId = line.replace(/^id:\s*/, '');
|
||||
} else if (line.startsWith('retry:')) {
|
||||
const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10);
|
||||
if (!Number.isNaN(parsed)) {
|
||||
retryDelay = parsed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let data: unknown;
|
||||
let parsedJson = false;
|
||||
|
||||
if (dataLines.length) {
|
||||
const rawData = dataLines.join('\n');
|
||||
try {
|
||||
data = JSON.parse(rawData);
|
||||
parsedJson = true;
|
||||
} catch {
|
||||
data = rawData;
|
||||
}
|
||||
}
|
||||
|
||||
if (parsedJson) {
|
||||
if (responseValidator) {
|
||||
await responseValidator(data);
|
||||
}
|
||||
|
||||
if (responseTransformer) {
|
||||
data = await responseTransformer(data);
|
||||
}
|
||||
}
|
||||
|
||||
onSseEvent?.({
|
||||
data,
|
||||
event: eventName,
|
||||
id: lastEventId,
|
||||
retry: retryDelay,
|
||||
});
|
||||
|
||||
if (dataLines.length) {
|
||||
yield data as any;
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
signal.removeEventListener('abort', abortHandler);
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
break; // exit loop on normal completion
|
||||
} catch (error) {
|
||||
// connection failed or aborted; retry after delay
|
||||
onSseError?.(error);
|
||||
|
||||
if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
|
||||
break; // stop after firing error
|
||||
}
|
||||
|
||||
// exponential backoff: double retry each attempt, cap at 30s
|
||||
const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
|
||||
await sleep(backoff);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const stream = createStream();
|
||||
|
||||
return { stream };
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Auth, AuthToken } from './auth.gen';
|
||||
import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen';
|
||||
|
||||
export type HttpMethod =
|
||||
| 'connect'
|
||||
| 'delete'
|
||||
| 'get'
|
||||
| 'head'
|
||||
| 'options'
|
||||
| 'patch'
|
||||
| 'post'
|
||||
| 'put'
|
||||
| 'trace';
|
||||
|
||||
export type Client<
|
||||
RequestFn = never,
|
||||
Config = unknown,
|
||||
MethodFn = never,
|
||||
BuildUrlFn = never,
|
||||
SseFn = never,
|
||||
> = {
|
||||
/**
|
||||
* Returns the final request URL.
|
||||
*/
|
||||
buildUrl: BuildUrlFn;
|
||||
getConfig: () => Config;
|
||||
request: RequestFn;
|
||||
setConfig: (config: Config) => Config;
|
||||
} & {
|
||||
[K in HttpMethod]: MethodFn;
|
||||
} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } });
|
||||
|
||||
export interface Config {
|
||||
/**
|
||||
* Auth token or a function returning auth token. The resolved value will be
|
||||
* added to the request payload as defined by its `security` array.
|
||||
*/
|
||||
auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
|
||||
/**
|
||||
* A function for serializing request body parameter. By default,
|
||||
* {@link JSON.stringify()} will be used.
|
||||
*/
|
||||
bodySerializer?: BodySerializer | null;
|
||||
/**
|
||||
* An object containing any HTTP headers that you want to pre-populate your
|
||||
* `Headers` object with.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
|
||||
*/
|
||||
headers?:
|
||||
| RequestInit['headers']
|
||||
| Record<
|
||||
string,
|
||||
string | number | boolean | (string | number | boolean)[] | null | undefined | unknown
|
||||
>;
|
||||
/**
|
||||
* The request method.
|
||||
*
|
||||
* {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
|
||||
*/
|
||||
method?: Uppercase<HttpMethod>;
|
||||
/**
|
||||
* A function for serializing request query parameters. By default, arrays
|
||||
* will be exploded in form style, objects will be exploded in deepObject
|
||||
* style, and reserved characters are percent-encoded.
|
||||
*
|
||||
* This method will have no effect if the native `paramsSerializer()` Axios
|
||||
* API function is used.
|
||||
*
|
||||
* {@link https://swagger.io/docs/specification/serialization/#query View examples}
|
||||
*/
|
||||
querySerializer?: QuerySerializer | QuerySerializerOptions;
|
||||
/**
|
||||
* A function validating request data. This is useful if you want to ensure
|
||||
* the request conforms to the desired shape, so it can be safely sent to
|
||||
* the server.
|
||||
*/
|
||||
requestValidator?: (data: unknown) => Promise<unknown>;
|
||||
/**
|
||||
* A function transforming response data before it's returned. This is useful
|
||||
* for post-processing data, e.g., converting ISO strings into Date objects.
|
||||
*/
|
||||
responseTransformer?: (data: unknown) => Promise<unknown>;
|
||||
/**
|
||||
* A function validating response data. This is useful if you want to ensure
|
||||
* the response conforms to the desired shape, so it can be safely passed to
|
||||
* the transformers and returned to the user.
|
||||
*/
|
||||
responseValidator?: (data: unknown) => Promise<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Arbitrary metadata passed through the `meta` request option.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
export interface ClientMeta {}
|
||||
|
||||
type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
|
||||
? true
|
||||
: [T] extends [never | undefined]
|
||||
? [undefined] extends [T]
|
||||
? false
|
||||
: true
|
||||
: false;
|
||||
|
||||
export type OmitNever<T extends Record<string, unknown>> = {
|
||||
[K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
|
||||
};
|
||||
@@ -0,0 +1,140 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { BodySerializer, QuerySerializer } from './bodySerializer.gen';
|
||||
import {
|
||||
type ArraySeparatorStyle,
|
||||
serializeArrayParam,
|
||||
serializeObjectParam,
|
||||
serializePrimitiveParam,
|
||||
} from './pathSerializer.gen';
|
||||
|
||||
export interface PathSerializer {
|
||||
path: Record<string, unknown>;
|
||||
url: string;
|
||||
}
|
||||
|
||||
export const PATH_PARAM_RE: RegExp = /\{[^{}]+\}/g;
|
||||
|
||||
export const defaultPathSerializer = ({ path, url: _url }: PathSerializer): string => {
|
||||
let url = _url;
|
||||
const matches = _url.match(PATH_PARAM_RE);
|
||||
if (matches) {
|
||||
for (const match of matches) {
|
||||
let explode = false;
|
||||
let name = match.substring(1, match.length - 1);
|
||||
let style: ArraySeparatorStyle = 'simple';
|
||||
|
||||
if (name.endsWith('*')) {
|
||||
explode = true;
|
||||
name = name.substring(0, name.length - 1);
|
||||
}
|
||||
|
||||
if (name.startsWith('.')) {
|
||||
name = name.substring(1);
|
||||
style = 'label';
|
||||
} else if (name.startsWith(';')) {
|
||||
name = name.substring(1);
|
||||
style = 'matrix';
|
||||
}
|
||||
|
||||
const value = path[name];
|
||||
|
||||
if (value === undefined || value === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
url = url.replace(
|
||||
match,
|
||||
serializeObjectParam({
|
||||
explode,
|
||||
name,
|
||||
style,
|
||||
value: value as Record<string, unknown>,
|
||||
valueOnly: true,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (style === 'matrix') {
|
||||
url = url.replace(
|
||||
match,
|
||||
`;${serializePrimitiveParam({
|
||||
name,
|
||||
value: value as string,
|
||||
})}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const replaceValue = encodeURIComponent(
|
||||
style === 'label' ? `.${value as string}` : (value as string),
|
||||
);
|
||||
url = url.replace(match, replaceValue);
|
||||
}
|
||||
}
|
||||
return url;
|
||||
};
|
||||
|
||||
export const getUrl = ({
|
||||
baseUrl,
|
||||
path,
|
||||
query,
|
||||
querySerializer,
|
||||
url: _url,
|
||||
}: {
|
||||
baseUrl?: string;
|
||||
path?: Record<string, unknown>;
|
||||
query?: Record<string, unknown>;
|
||||
querySerializer: QuerySerializer;
|
||||
url: string;
|
||||
}): string => {
|
||||
const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
|
||||
let url = (baseUrl ?? '') + pathUrl;
|
||||
if (path) {
|
||||
url = defaultPathSerializer({ path, url });
|
||||
}
|
||||
let search = query ? querySerializer(query) : '';
|
||||
if (search.startsWith('?')) {
|
||||
search = search.substring(1);
|
||||
}
|
||||
if (search) {
|
||||
url += `?${search}`;
|
||||
}
|
||||
return url;
|
||||
};
|
||||
|
||||
export function getValidRequestBody(options: {
|
||||
body?: unknown;
|
||||
bodySerializer?: BodySerializer | null;
|
||||
serializedBody?: unknown;
|
||||
}): unknown {
|
||||
const hasBody = options.body !== undefined;
|
||||
const isSerializedBody = hasBody && options.bodySerializer;
|
||||
|
||||
if (isSerializedBody) {
|
||||
if ('serializedBody' in options) {
|
||||
const hasSerializedBody =
|
||||
options.serializedBody !== undefined && options.serializedBody !== '';
|
||||
|
||||
return hasSerializedBody ? options.serializedBody : null;
|
||||
}
|
||||
|
||||
// not all clients implement a serializedBody property (i.e., client-axios)
|
||||
return options.body !== '' ? options.body : null;
|
||||
}
|
||||
|
||||
// plain/text body
|
||||
if (hasBody) {
|
||||
return options.body;
|
||||
}
|
||||
|
||||
// no body was provided
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
export { addComment, deleteComment, getArticle, getFeed, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWeatherNow, getWeatherToday, getWeek, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyScoreData, SkyType, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WeatherSlot, type WeekDay, type WeekSlide } from './types.gen';
|
||||
@@ -0,0 +1,202 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
|
||||
import { client } from './client.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses } from './types.gen';
|
||||
|
||||
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
|
||||
/**
|
||||
* You can provide a client instance returned by `createClient()` instead of
|
||||
* individual options. This might be also useful if you want to implement a
|
||||
* custom client.
|
||||
*/
|
||||
client?: Client;
|
||||
/**
|
||||
* You can pass arbitrary values through the `meta` object. This can be
|
||||
* used to access values that aren't defined as part of the SDK function.
|
||||
*/
|
||||
meta?: keyof ClientMeta extends never ? Record<string, unknown> : ClientMeta;
|
||||
};
|
||||
|
||||
/**
|
||||
* 구 목록
|
||||
*/
|
||||
export const listRegions = <ThrowOnError extends boolean = true>(options?: Options<ListRegionsData, ThrowOnError>): RequestResult<ListRegionsResponses, ListRegionsErrors, ThrowOnError> => (options?.client ?? client).get<ListRegionsResponses, ListRegionsErrors, ThrowOnError>({ url: '/v1/region/list', ...options });
|
||||
|
||||
/**
|
||||
* 위치에서 가장 가까운 구
|
||||
*/
|
||||
export const nearestRegion = <ThrowOnError extends boolean = true>(options: Options<NearestRegionData, ThrowOnError>): RequestResult<NearestRegionResponses, NearestRegionErrors, ThrowOnError> => (options.client ?? client).get<NearestRegionResponses, NearestRegionErrors, ThrowOnError>({ url: '/v1/region/nearest', ...options });
|
||||
|
||||
/**
|
||||
* 오늘 3시간 칸 날씨
|
||||
*/
|
||||
export const getWeatherToday = <ThrowOnError extends boolean = true>(options: Options<GetWeatherTodayData, ThrowOnError>): RequestResult<GetWeatherTodayResponses, GetWeatherTodayErrors, ThrowOnError> => (options.client ?? client).get<GetWeatherTodayResponses, GetWeatherTodayErrors, ThrowOnError>({ url: '/v1/weather/today', ...options });
|
||||
|
||||
/**
|
||||
* 지금 비 올까: 2시간 비, 내일 출퇴근, 미세먼지, 특보
|
||||
*/
|
||||
export const getWeatherNow = <ThrowOnError extends boolean = true>(options: Options<GetWeatherNowData, ThrowOnError>): RequestResult<GetWeatherNowResponses, GetWeatherNowErrors, ThrowOnError> => (options.client ?? client).get<GetWeatherNowResponses, GetWeatherNowErrors, ThrowOnError>({ url: '/v1/weather/now', ...options });
|
||||
|
||||
/**
|
||||
* 노을·일출 점수, 3컷, 가까운 명소, 앞으로 3일
|
||||
*/
|
||||
export const getSky = <ThrowOnError extends boolean = true>(options: Options<GetSkyData, ThrowOnError>): RequestResult<GetSkyResponses, GetSkyErrors, ThrowOnError> => (options.client ?? client).get<GetSkyResponses, GetSkyErrors, ThrowOnError>({ url: '/v1/sky', ...options });
|
||||
|
||||
/**
|
||||
* 전국 노을 순위 (대표 30곳)
|
||||
*/
|
||||
export const getSkyRanking = <ThrowOnError extends boolean = true>(options?: Options<GetSkyRankingData, ThrowOnError>): RequestResult<GetSkyRankingResponses, unknown, ThrowOnError> => (options?.client ?? client).get<GetSkyRankingResponses, unknown, ThrowOnError>({ url: '/v1/sky/ranking', ...options });
|
||||
|
||||
/**
|
||||
* 지수 목록 (점수순, 1~3위, 오늘 날씨 점수)
|
||||
*/
|
||||
export const listIndices = <ThrowOnError extends boolean = true>(options: Options<ListIndicesData, ThrowOnError>): RequestResult<ListIndicesResponses, ListIndicesErrors, ThrowOnError> => (options.client ?? client).get<ListIndicesResponses, ListIndicesErrors, ThrowOnError>({ url: '/v1/index/list', ...options });
|
||||
|
||||
/**
|
||||
* 지수 계산 근거
|
||||
*/
|
||||
export const getIndex = <ThrowOnError extends boolean = true>(options: Options<GetIndexData, ThrowOnError>): RequestResult<GetIndexResponses, GetIndexErrors, ThrowOnError> => (options.client ?? client).get<GetIndexResponses, GetIndexErrors, ThrowOnError>({ url: '/v1/index/{index_id}', ...options });
|
||||
|
||||
/**
|
||||
* 7일 날씨와 그날 추천
|
||||
*/
|
||||
export const getWeek = <ThrowOnError extends boolean = true>(options: Options<GetWeekData, ThrowOnError>): RequestResult<GetWeekResponses, GetWeekErrors, ThrowOnError> => (options.client ?? client).get<GetWeekResponses, GetWeekErrors, ThrowOnError>({ url: '/v1/week', ...options });
|
||||
|
||||
/**
|
||||
* 날씨 맞춤 데이트 명소
|
||||
*/
|
||||
export const listPlaces = <ThrowOnError extends boolean = true>(options: Options<ListPlacesData, ThrowOnError>): RequestResult<ListPlacesResponses, ListPlacesErrors, ThrowOnError> => (options.client ?? client).get<ListPlacesResponses, ListPlacesErrors, ThrowOnError>({ url: '/v1/week/place/list', ...options });
|
||||
|
||||
/**
|
||||
* 앞으로 30일 축제·행사
|
||||
*/
|
||||
export const listEvents = <ThrowOnError extends boolean = true>(options: Options<ListEventsData, ThrowOnError>): RequestResult<ListEventsResponses, ListEventsErrors, ThrowOnError> => (options.client ?? client).get<ListEventsResponses, ListEventsErrors, ThrowOnError>({ url: '/v1/week/event/list', ...options });
|
||||
|
||||
/**
|
||||
* 이번 주 계절 책: 시, 절기, 계절 소식
|
||||
*/
|
||||
export const getSeasonWeek = <ThrowOnError extends boolean = true>(options?: Options<GetSeasonWeekData, ThrowOnError>): RequestResult<GetSeasonWeekResponses, unknown, ThrowOnError> => (options?.client ?? client).get<GetSeasonWeekResponses, unknown, ThrowOnError>({ url: '/v1/season/week', ...options });
|
||||
|
||||
/**
|
||||
* 읽을거리 목록
|
||||
*/
|
||||
export const listArticles = <ThrowOnError extends boolean = true>(options?: Options<ListArticlesData, ThrowOnError>): RequestResult<ListArticlesResponses, ListArticlesErrors, ThrowOnError> => (options?.client ?? client).get<ListArticlesResponses, ListArticlesErrors, ThrowOnError>({ url: '/v1/season/article/list', ...options });
|
||||
|
||||
/**
|
||||
* 읽을거리 본문
|
||||
*/
|
||||
export const getArticle = <ThrowOnError extends boolean = true>(options: Options<GetArticleData, ThrowOnError>): RequestResult<GetArticleResponses, GetArticleErrors, ThrowOnError> => (options.client ?? client).get<GetArticleResponses, GetArticleErrors, ThrowOnError>({ url: '/v1/season/article/{article_id}', ...options });
|
||||
|
||||
/**
|
||||
* 메인 피드: 하늘 영역, 오늘의 각, 오늘 포스트 전부, 띠
|
||||
*/
|
||||
export const getFeed = <ThrowOnError extends boolean = true>(options: Options<GetFeedData, ThrowOnError>): RequestResult<GetFeedResponses, GetFeedErrors, ThrowOnError> => (options.client ?? client).get<GetFeedResponses, GetFeedErrors, ThrowOnError>({ url: '/v1/feed', ...options });
|
||||
|
||||
/**
|
||||
* 포스트 하나 (공유 링크로 들어왔을 때)
|
||||
*/
|
||||
export const getPost = <ThrowOnError extends boolean = true>(options: Options<GetPostData, ThrowOnError>): RequestResult<GetPostResponses, GetPostErrors, ThrowOnError> => (options.client ?? client).get<GetPostResponses, GetPostErrors, ThrowOnError>({ url: '/v1/feed/post/{post_id}', ...options });
|
||||
|
||||
/**
|
||||
* 회원가입 (아이디 영문 소문자·숫자·_ 4~20자, 비밀번호 8자 이상, 닉네임 2~12자)
|
||||
*/
|
||||
export const signup = <ThrowOnError extends boolean = true>(options: Options<SignupData, ThrowOnError>): RequestResult<SignupResponses, SignupErrors, ThrowOnError> => (options.client ?? client).post<SignupResponses, SignupErrors, ThrowOnError>({
|
||||
url: '/v1/auth/signup',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 로그인
|
||||
*/
|
||||
export const login = <ThrowOnError extends boolean = true>(options: Options<LoginData, ThrowOnError>): RequestResult<LoginResponses, LoginErrors, ThrowOnError> => (options.client ?? client).post<LoginResponses, LoginErrors, ThrowOnError>({
|
||||
url: '/v1/auth/login',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 토큰 재발급
|
||||
*/
|
||||
export const refresh = <ThrowOnError extends boolean = true>(options: Options<RefreshData, ThrowOnError>): RequestResult<RefreshResponses, RefreshErrors, ThrowOnError> => (options.client ?? client).post<RefreshResponses, RefreshErrors, ThrowOnError>({
|
||||
url: '/v1/auth/refresh',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 내 정보
|
||||
*/
|
||||
export const me = <ThrowOnError extends boolean = true>(options?: Options<MeData, ThrowOnError>): RequestResult<MeResponses, MeErrors, ThrowOnError> => (options?.client ?? client).get<MeResponses, MeErrors, ThrowOnError>({ url: '/v1/auth/me', ...options });
|
||||
|
||||
/**
|
||||
* 좋아요 취소
|
||||
*/
|
||||
export const unlikePost = <ThrowOnError extends boolean = true>(options: Options<UnlikePostData, ThrowOnError>): RequestResult<UnlikePostResponses, UnlikePostErrors, ThrowOnError> => (options.client ?? client).delete<UnlikePostResponses, UnlikePostErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 좋아요
|
||||
*/
|
||||
export const likePost = <ThrowOnError extends boolean = true>(options: Options<LikePostData, ThrowOnError>): RequestResult<LikePostResponses, LikePostErrors, ThrowOnError> => (options.client ?? client).post<LikePostResponses, LikePostErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 저장 취소
|
||||
*/
|
||||
export const unsavePost = <ThrowOnError extends boolean = true>(options: Options<UnsavePostData, ThrowOnError>): RequestResult<UnsavePostResponses, UnsavePostErrors, ThrowOnError> => (options.client ?? client).delete<UnsavePostResponses, UnsavePostErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/save', ...options });
|
||||
|
||||
/**
|
||||
* 저장
|
||||
*/
|
||||
export const savePost = <ThrowOnError extends boolean = true>(options: Options<SavePostData, ThrowOnError>): RequestResult<SavePostResponses, SavePostErrors, ThrowOnError> => (options.client ?? client).post<SavePostResponses, SavePostErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/save', ...options });
|
||||
|
||||
/**
|
||||
* 내가 저장한 포스트
|
||||
*/
|
||||
export const listSaved = <ThrowOnError extends boolean = true>(options?: Options<ListSavedData, ThrowOnError>): RequestResult<ListSavedResponses, ListSavedErrors, ThrowOnError> => (options?.client ?? client).get<ListSavedResponses, ListSavedErrors, ThrowOnError>({ url: '/v1/reaction/save/list', ...options });
|
||||
|
||||
/**
|
||||
* 댓글 목록 (로그인 없이 보기)
|
||||
*/
|
||||
export const listComments = <ThrowOnError extends boolean = true>(options: Options<ListCommentsData, ThrowOnError>): RequestResult<ListCommentsResponses, ListCommentsErrors, ThrowOnError> => (options.client ?? client).get<ListCommentsResponses, ListCommentsErrors, ThrowOnError>({ url: '/v1/reaction/post/{post_id}/comment/list', ...options });
|
||||
|
||||
/**
|
||||
* 댓글 쓰기 (60자)
|
||||
*/
|
||||
export const addComment = <ThrowOnError extends boolean = true>(options: Options<AddCommentData, ThrowOnError>): RequestResult<AddCommentResponses, AddCommentErrors, ThrowOnError> => (options.client ?? client).post<AddCommentResponses, AddCommentErrors, ThrowOnError>({
|
||||
url: '/v1/reaction/post/{post_id}/comment',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 내 댓글 지우기
|
||||
*/
|
||||
export const deleteComment = <ThrowOnError extends boolean = true>(options: Options<DeleteCommentData, ThrowOnError>): RequestResult<DeleteCommentResponses, DeleteCommentErrors, ThrowOnError> => (options.client ?? client).delete<DeleteCommentResponses, DeleteCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}', ...options });
|
||||
|
||||
/**
|
||||
* 댓글 좋아요 취소
|
||||
*/
|
||||
export const unlikeComment = <ThrowOnError extends boolean = true>(options: Options<UnlikeCommentData, ThrowOnError>): RequestResult<UnlikeCommentResponses, UnlikeCommentErrors, ThrowOnError> => (options.client ?? client).delete<UnlikeCommentResponses, UnlikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 댓글 좋아요
|
||||
*/
|
||||
export const likeComment = <ThrowOnError extends boolean = true>(options: Options<LikeCommentData, ThrowOnError>): RequestResult<LikeCommentResponses, LikeCommentErrors, ThrowOnError> => (options.client ?? client).post<LikeCommentResponses, LikeCommentErrors, ThrowOnError>({ url: '/v1/reaction/comment/{comment_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 헬스체크
|
||||
*/
|
||||
export const healthzHealthzGet = <ThrowOnError extends boolean = true>(options?: Options<HealthzHealthzGetData, ThrowOnError>): RequestResult<HealthzHealthzGetResponses, unknown, ThrowOnError> => (options?.client ?? client).get<HealthzHealthzGetResponses, unknown, ThrowOnError>({ url: '/healthz', ...options });
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,48 @@
|
||||
import { client } from './client/client.gen'
|
||||
import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setTokens } from './auth'
|
||||
|
||||
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
||||
|
||||
// 401이 한꺼번에 와도 갱신은 한 번만
|
||||
let refreshing: Promise<boolean> | null = null
|
||||
|
||||
function refreshTokens(): Promise<boolean> {
|
||||
refreshing ??= (async () => {
|
||||
const token = getRefreshToken()
|
||||
if (!token) return false
|
||||
const res = await fetch(`${API_BASE_URL}/v1/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: token }) })
|
||||
const body = res.ok ? await res.json() : null
|
||||
if (!body?.result?.success || !body.access_token) return false
|
||||
setTokens(body.access_token, body.refresh_token ?? token)
|
||||
return true
|
||||
})()
|
||||
.catch(() => false)
|
||||
.finally(() => {
|
||||
refreshing = null
|
||||
})
|
||||
return refreshing
|
||||
}
|
||||
|
||||
/** 401이면 토큰을 한 번 갱신해 같은 요청을 다시 보내고, 안 되면 토큰을 지우고 로그인 창을 띄운다 */
|
||||
async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
const request = input instanceof Request && !init ? input : new Request(input, init)
|
||||
const retry = request.clone()
|
||||
const response = await fetch(request)
|
||||
if (response.status !== 401 || new URL(request.url).pathname.startsWith('/v1/auth/')) return response
|
||||
if (request.headers.has('Authorization') && (await refreshTokens())) {
|
||||
retry.headers.set('Authorization', `Bearer ${getAccessToken()}`)
|
||||
const again = await fetch(retry)
|
||||
if (again.status !== 401) return again
|
||||
}
|
||||
if (getAccessToken()) clearTokens()
|
||||
emitAuthRequired()
|
||||
return response
|
||||
}
|
||||
|
||||
client.setConfig({ baseUrl: API_BASE_URL, throwOnError: true, fetch: authFetch })
|
||||
|
||||
client.interceptors.request.use((request) => {
|
||||
const token = getAccessToken()
|
||||
if (token) request.headers.set('Authorization', `Bearer ${token}`)
|
||||
return request
|
||||
})
|
||||
@@ -0,0 +1,80 @@
|
||||
import { useEffect } from 'react'
|
||||
import { NavLink, Outlet, useLocation } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import './b.css'
|
||||
import { AuthProvider } from './auth'
|
||||
import { RegionProvider } from './region'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { SheetProvider } from './Sheets'
|
||||
import { PinIcon, TabIcon } from './svg'
|
||||
|
||||
const TABS = [
|
||||
{ to: '/', key: 'today', label: '오늘', title: null },
|
||||
{ to: '/gak', key: 'gak', label: '각', title: '오늘의 각' },
|
||||
{ to: '/sky', key: 'sky', label: '노을', title: '노을' },
|
||||
{ to: '/week', key: 'week', label: '주말·행사', title: '주말·행사' },
|
||||
{ to: '/season', key: 'season', label: '계절·상식', title: '계절·상식' },
|
||||
] as const
|
||||
|
||||
function TopBar() {
|
||||
const { pathname } = useLocation()
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const tab = TABS.find((t) => t.to !== '/' && pathname.startsWith(t.to))
|
||||
|
||||
return (
|
||||
<header className="sticky top-0 z-20 flex h-[54px] items-center justify-between gap-2.5 bg-[rgb(247_251_255/0.9)] px-4 backdrop-blur-md">
|
||||
{tab?.title ? <h1 className="font-jua text-[22px] font-normal">{tab.title}</h1> : <h1 className="font-jua text-[25px] font-normal text-(--orange)">날씨각</h1>}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => open({ type: 'region' })}
|
||||
aria-label={`위치 바꾸기, 지금 ${region.name}`}
|
||||
className="flex cursor-pointer items-center gap-1 rounded-full bg-white px-3 py-1.5 text-[13.5px] font-bold shadow-[inset_0_-4px_0_var(--shade),0_6px_12px_rgb(40_48_74/0.07)]"
|
||||
>
|
||||
<PinIcon className="size-3.5" />
|
||||
{region.name}
|
||||
</button>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
function Shell() {
|
||||
const { pathname } = useLocation()
|
||||
useEffect(() => {
|
||||
window.scrollTo({ top: 0 })
|
||||
}, [pathname])
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-(--outer) text-(--ink)">
|
||||
<div className="relative mx-auto min-h-dvh max-w-[440px] overflow-x-clip bg-(--page) pb-[calc(70px+env(safe-area-inset-bottom,0px))]">
|
||||
<TopBar />
|
||||
<main>
|
||||
<Outlet />
|
||||
</main>
|
||||
<nav aria-label="주요 메뉴" className="fixed bottom-0 left-1/2 z-30 grid w-full max-w-[440px] -translate-x-1/2 grid-cols-5 border-t border-(--line) bg-white/96 px-1 pt-[7px] pb-[calc(8px+env(safe-area-inset-bottom,0px))] backdrop-blur-[10px]">
|
||||
{TABS.map((t) => (
|
||||
<NavLink key={t.key} to={t.to} end={t.to === '/'} className={({ isActive }) => cx('flex flex-col items-center gap-0.5 text-[11px] font-extrabold', isActive ? 'text-(--ink) [&_svg]:stroke-[2.4]' : 'text-(--ink3) [&_svg]:stroke-[1.9]')}>
|
||||
<TabIcon name={t.key} className="size-[25px]" />
|
||||
{t.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function BLayout() {
|
||||
return (
|
||||
<div className="b-app">
|
||||
<AuthProvider>
|
||||
<RegionProvider>
|
||||
<SheetProvider>
|
||||
<Shell />
|
||||
</SheetProvider>
|
||||
</RegionProvider>
|
||||
</AuthProvider>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { listArticlesOptions, listIndicesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { ArticleCategory, IndexCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { MEDALS } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, Sec, StateBox } from './ui'
|
||||
|
||||
type Cat = 'all' | 'out' | 'food' | 'home' | 'life' | 'core'
|
||||
|
||||
const CATS = [
|
||||
['all', '전체'],
|
||||
['out', '밖에서 놀기'],
|
||||
['food', '먹고 마시기'],
|
||||
['home', '집안일'],
|
||||
['life', '생활 고민'],
|
||||
['core', '가을 각'],
|
||||
] as const
|
||||
|
||||
const CAT_PARAM: Partial<Record<Cat, IndexCategory>> = { out: IndexCategory.OUTSIDE, food: IndexCategory.FOOD, home: IndexCategory.HOME, life: IndexCategory.LIFE }
|
||||
|
||||
export function GakPage() {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const [cat, setCat] = useState<Cat>('all')
|
||||
const q = useQuery(listIndicesOptions({ query: { region: region.code, category: CAT_PARAM[cat], core: cat === 'core' ? true : undefined } }))
|
||||
const top = q.data?.top3 ?? []
|
||||
const items = q.data?.items ?? []
|
||||
const day = q.data?.day?.split('-').map(Number)
|
||||
const howto = useQuery(listArticlesOptions({ query: { category: ArticleCategory.GAK } })).data?.articles?.find((a) => a.code === 'howgak')
|
||||
|
||||
return (
|
||||
<section aria-label="각">
|
||||
<Sec title="오늘 1~3위" sub={`${day ? `${day[1]}월 ${day[2]}일 기준 · ` : ''}${region.name} · 칸 아래 막대는 오늘·내일·모레 점수`} />
|
||||
{top.length === 3 && (
|
||||
<div className="grid grid-cols-[1fr_1.15fr_1fr] items-end gap-1.5 px-3 pt-3">
|
||||
{[1, 0, 2].map((k) => {
|
||||
const g = top[k]
|
||||
return (
|
||||
<button
|
||||
key={g.index_id}
|
||||
type="button"
|
||||
onClick={() => open({ type: 'gak', indexId: g.index_id })}
|
||||
className={cx('flex cursor-pointer flex-col items-center rounded-3xl px-1.5 text-center shadow-[inset_0_-6px_0_var(--shade)]', k === 0 ? 'bg-[linear-gradient(180deg,#fff1c4,#fff)] py-4' : 'bg-white py-3')}
|
||||
>
|
||||
<span className="relative">
|
||||
<Ic name={g.icon} className={cx('drop-shadow-[0_10px_12px_rgb(40_48_74/0.15)]', k === 0 ? 'w-20' : 'w-[62px]')} />
|
||||
<Ic name={MEDALS[k]} className="absolute -top-1.5 -left-3 w-7" />
|
||||
</span>
|
||||
<b className="mt-1.5 font-jua text-base font-normal">
|
||||
{k + 1}위 {g.name}
|
||||
</b>
|
||||
<em className="font-bagel text-[30px] leading-[1.05] text-(--orange) not-italic">{g.score}</em>
|
||||
<small className="text-[11.5px] font-semibold text-(--ink2)">{g.summary}</small>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<Chips items={CATS} value={cat} onChange={setCat} label="분야" />
|
||||
<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty={q.isSuccess && !items.length ? '이 분야는 오늘 계산된 각이 없어요.' : undefined} />
|
||||
<div className="grid grid-cols-3 gap-2 p-3">
|
||||
{items.map((g) => {
|
||||
const trend = g.trend ?? []
|
||||
const mx = Math.max(1, ...trend.map((t) => t.score))
|
||||
return (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={`${g.rank}위 ${g.name} ${g.score}점`} className="relative flex cursor-pointer flex-col items-center rounded-[22px] bg-white px-1.5 pt-3 pb-2.5 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<span className="absolute top-[7px] left-[9px] font-jua text-[13px] text-(--ink3)">{g.rank}</span>
|
||||
{g.is_core && <span className="absolute top-2 right-2 text-[10.5px] font-extrabold text-[#1f9d62]">가을</span>}
|
||||
<Ic name={g.icon} className="w-[50px]" />
|
||||
<b className="mt-1 font-jua text-[15px] font-normal">{g.name}</b>
|
||||
<em className={cx('font-bagel text-[22px] leading-[1.1] not-italic', g.score < 50 ? 'text-(--ink3)' : 'text-(--orange)')}>{g.score}</em>
|
||||
<span className="mt-1 flex h-[18px] items-end gap-[3px]" aria-hidden="true">
|
||||
{trend.map((t, j) => (
|
||||
<i key={t.day} className={cx('w-[9px] rounded-[3px]', j ? 'bg-[#dbe4ef]' : 'bg-(--orange)')} style={{ height: Math.max(4, (t.score / mx) * 18) }} />
|
||||
))}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{howto && (
|
||||
<button type="button" onClick={() => open({ type: 'article', articleId: howto.article_id })} className="mx-3 mt-1.5 flex w-[calc(100%-24px)] cursor-pointer items-center gap-3 rounded-[22px] bg-[#ece7ff] p-3.5 text-left">
|
||||
<Ic name="bulb" className="w-11" />
|
||||
<span>
|
||||
<b className="block font-jua text-[17px] font-normal">각 점수는 어떻게 매길까?</b>
|
||||
<small className="text-[12.5px] font-semibold text-(--ink2)">기온·비·바람·습도·공기·시간대 6가지로 계산해요</small>
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import { useRef, useState, type MouseEvent, type ReactNode } from 'react'
|
||||
import { PostType, SlotTone, type GakSlide, type HoursSlide, type PostData, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { ago, cardBg, clockShort, fall } from './lib'
|
||||
import type { SlideBg } from './types'
|
||||
import { deg } from './weatherText'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { likePostMutation, savePostMutation, unlikePostMutation, unsavePostMutation } from '../api/client/@tanstack/react-query.gen'
|
||||
import { useAuth } from './authContext'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { CommentIcon, HeartIcon, MoreIcon, SaveIcon, SendIcon } from './svg'
|
||||
import { Ic, Rows } from './ui'
|
||||
|
||||
const ACCOUNTS: Record<PostType, readonly [string, string]> = {
|
||||
[PostType.WEATHER]: ['오늘 날씨', 'sun'],
|
||||
[PostType.GAK]: ['오늘의 각', 'rabbit'],
|
||||
[PostType.SUNSET]: ['노을', 'sunset'],
|
||||
[PostType.SEASON]: ['계절 소식', 'maple'],
|
||||
[PostType.EVENT]: ['행사', 'fireworks'],
|
||||
[PostType.TIP]: ['날씨 상식', 'bulb'],
|
||||
[PostType.WEEK]: ['주말 추천', 'calendar'],
|
||||
}
|
||||
|
||||
type Slide = HoursSlide | RowsSlide | GakSlide | SunsetSlide | WeekSlide
|
||||
|
||||
const GAK_BG: SlideBg[] = ['butter', 'peach', 'lilac']
|
||||
const ROW_ICON_BG: Record<string, SlideBg> = { umbrella: 'lilac', vent: 'mint', sunset: 'peach', thermo: 'sky', maple: 'peach' }
|
||||
|
||||
/** 배경색은 API에 없어 글 종류·아이콘으로 고른다 */
|
||||
function slideBg(post: PostData, slide: Slide): SlideBg {
|
||||
if (slide.kind === 'hours') return 'sky'
|
||||
if (slide.kind === 'sunset') return 'dusk'
|
||||
if (slide.kind === 'week') return 'mint'
|
||||
if (slide.kind === 'gak') return GAK_BG[post.post_id % GAK_BG.length]
|
||||
if (post.post_type === PostType.EVENT) return 'night'
|
||||
if (post.post_type === PostType.TIP) return 'sky'
|
||||
return ROW_ICON_BG[slide.icon] ?? cardBg(slide.icon, post.post_id)
|
||||
}
|
||||
|
||||
const DARK = new Set<SlideBg>(['dusk', 'night'])
|
||||
|
||||
function Lines({ text }: { text: string }) {
|
||||
return text.split('\n').map((t, i) => (
|
||||
<span key={i}>
|
||||
{i > 0 && <br />}
|
||||
{t}
|
||||
</span>
|
||||
))
|
||||
}
|
||||
|
||||
function Eyebrow({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <p className={cx('m-0 text-[13px] font-extrabold opacity-75', className)}>{children}</p>
|
||||
}
|
||||
|
||||
function Big({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <p className={cx('mt-1.5 font-jua text-[29px] leading-tight', className)}>{children}</p>
|
||||
}
|
||||
|
||||
function Pic({ name, className }: { name: string; className?: string }) {
|
||||
return (
|
||||
<span className={cx('b-fall pointer-events-none absolute top-[30%] right-3.5 w-[42%]', className)} style={fall('.1s', '5s')}>
|
||||
<Ic name={name} className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
const slideBase = 'relative flex h-full w-full shrink-0 snap-start flex-col px-5 py-[22px]'
|
||||
|
||||
function SlideView({ slide, bg }: { slide: Slide; bg: SlideBg }) {
|
||||
const { open } = useSheet()
|
||||
if (slide.kind === 'hours')
|
||||
return (
|
||||
<div className={cx(slideBase, 'b-bg-sky')}>
|
||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||
<Big>
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<div className="mt-3.5 grid flex-1 grid-cols-4 gap-2">
|
||||
{slide.hours.map((h) => (
|
||||
<div
|
||||
key={h.label}
|
||||
className={cx(
|
||||
'flex flex-col items-center justify-between rounded-[18px] px-1 pt-2.5 pb-[9px] text-xs font-bold text-(--ink2)',
|
||||
h.tone === SlotTone.NIGHT ? 'bg-[#e3e7ff] shadow-[inset_0_-5px_0_#c7cff5]' : h.tone === SlotTone.SUNSET ? 'bg-[#ffe3d2] shadow-[inset_0_-5px_0_#ffc19f]' : 'bg-white shadow-[inset_0_-5px_0_var(--shade)]',
|
||||
)}
|
||||
>
|
||||
<span>{h.label}</span>
|
||||
<Ic name={h.icon} className="w-[34px]" />
|
||||
<b className="font-bagel text-[21px] font-normal text-(--ink)">{deg(h.temp_c)}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
if (slide.kind === 'gak')
|
||||
return (
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)}>
|
||||
<Eyebrow>오늘의 각 · {slide.rank}위</Eyebrow>
|
||||
<Big>{slide.line}</Big>
|
||||
<Pic name={slide.code} />
|
||||
<b className="mt-auto font-bagel text-[82px] leading-[0.9] font-normal text-(--orange)">{slide.score}</b>
|
||||
<p className="m-0 font-jua text-[29px] leading-tight">{slide.name}</p>
|
||||
<Eyebrow className="mt-1">{slide.summary}</Eyebrow>
|
||||
<button type="button" onClick={() => open({ type: 'gak', indexId: slide.index_id })} className="mt-3 cursor-pointer self-start rounded-full bg-(--orange) px-4 py-[9px] font-jua text-[15px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)]">
|
||||
계산 근거 보기 ⬡
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
if (slide.kind === 'sunset')
|
||||
return (
|
||||
<div className={cx(slideBase, 'b-bg-dusk')}>
|
||||
<Eyebrow className="opacity-90">{slide.eyebrow}</Eyebrow>
|
||||
<Big>
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<b className="mt-2 font-bagel text-[62px] leading-[0.9] font-normal">{slide.score}</b>
|
||||
<div className="mt-3 flex flex-1 flex-col gap-2">
|
||||
{slide.cuts.map((c, i) => (
|
||||
<div key={c.kind} className={cx('b-skyline relative flex-1 overflow-hidden rounded-2xl px-3 py-2 font-bagel text-[21px] text-white', `b-cut-${Math.min(i + 1, 3)}`)}>
|
||||
<span className="relative z-[1]">
|
||||
{clockShort(c.at)}
|
||||
<small className="ml-2 font-jua text-sm">{c.label}</small>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
if (slide.kind === 'week')
|
||||
return (
|
||||
<div className={cx(slideBase, 'b-bg-mint')}>
|
||||
<Eyebrow>{slide.eyebrow}</Eyebrow>
|
||||
<Big>
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<div className="mt-auto grid grid-cols-2 gap-2.5">
|
||||
{slide.days.map((d) => (
|
||||
<div key={d.day} className="rounded-[18px] bg-white/80 px-3 py-2.5 shadow-[inset_0_-5px_0_rgb(217_229_244/0.9)]">
|
||||
<Ic name={d.icon} className="w-[38px]" />
|
||||
<b className="block font-jua text-lg font-normal">
|
||||
{d.weekday} {d.day.split('-').slice(1).map(Number).join('.')}
|
||||
</b>
|
||||
<small className="text-[12.5px] font-bold text-(--ink2)">{d.text}</small>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
return (
|
||||
<div className={cx(slideBase, `b-bg-${bg}`)}>
|
||||
<Eyebrow className={DARK.has(bg) ? 'opacity-85' : undefined}>{slide.eyebrow}</Eyebrow>
|
||||
<Big className="relative z-[1]">
|
||||
<Lines text={slide.line} />
|
||||
</Big>
|
||||
<Pic name={slide.icon} className="w-[36%]" />
|
||||
<Rows rows={slide.rows ?? []} dark={DARK.has(bg)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type PostProps = { post: PostData }
|
||||
|
||||
/** 인스타식 게시물: 옆으로 넘기는 슬라이드, 두 번 눌러 좋아요 */
|
||||
export function PostCard({ post }: PostProps) {
|
||||
const { open } = useSheet()
|
||||
const { region } = useRegion()
|
||||
const { loggedIn } = useAuth()
|
||||
const [liked, setLiked] = useState(!!post.liked)
|
||||
const [likeCount, setLikeCount] = useState(post.like_count)
|
||||
const [saved, setSaved] = useState(!!post.saved)
|
||||
const like = useMutation(likePostMutation())
|
||||
const unlike = useMutation(unlikePostMutation())
|
||||
const save = useMutation(savePostMutation())
|
||||
const unsave = useMutation(unsavePostMutation())
|
||||
const [index, setIndex] = useState(0)
|
||||
const [pop, setPop] = useState(0)
|
||||
const lastTap = useRef(0)
|
||||
const [account, avatar] = ACCOUNTS[post.post_type]
|
||||
const n = post.slides.length
|
||||
const bgs = post.slides.map((sl) => slideBg(post, sl))
|
||||
const accountName = post.post_type === PostType.EVENT ? `${region.name.split(' ')[0]} ${account}` : account
|
||||
const share = () => open({ type: 'share', share: { title: post.title, icon: post.icon, bg: bgs[0] ?? 'sky', messages: post.share_messages ?? [] } })
|
||||
const comments = () => open({ type: 'comments', postId: post.post_id })
|
||||
|
||||
// 화면을 먼저 바꾸고, 실패하면 되돌린다
|
||||
const setLike = (next: boolean) => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
if (next === liked) return
|
||||
setLiked(next)
|
||||
setLikeCount((n) => n + (next ? 1 : -1))
|
||||
;(next ? like : unlike).mutate(
|
||||
{ path: { post_id: post.post_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (res.liked != null) setLiked(res.liked)
|
||||
if (res.like_count != null) setLikeCount(res.like_count)
|
||||
},
|
||||
onError: () => {
|
||||
setLiked(!next)
|
||||
setLikeCount((n) => n + (next ? -1 : 1))
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const toggleSave = () => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const next = !saved
|
||||
setSaved(next)
|
||||
;(next ? save : unsave).mutate(
|
||||
{ path: { post_id: post.post_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
if (res.saved != null) setSaved(res.saved)
|
||||
},
|
||||
onError: () => setSaved(!next),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const onTap = (e: MouseEvent<HTMLDivElement>) => {
|
||||
if ((e.target as HTMLElement).closest('button')) return
|
||||
const now = Date.now()
|
||||
if (now - lastTap.current < 320) {
|
||||
setLike(true)
|
||||
if (loggedIn) setPop((p) => p + 1)
|
||||
}
|
||||
lastTap.current = now
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="mt-3.5 border-y border-(--line) bg-white" aria-label={post.title}>
|
||||
<div className="flex items-center gap-2.5 px-3 py-2.5">
|
||||
<span className="b-ring size-[34px] shrink-0 rounded-full p-0.5">
|
||||
<i className="grid size-full place-items-center rounded-full bg-white">
|
||||
<Ic name={avatar} className="w-[22px]" />
|
||||
</i>
|
||||
</span>
|
||||
<span>
|
||||
<b className="block text-sm leading-tight font-extrabold">날씨각</b>
|
||||
<small className="text-xs font-semibold text-(--ink2)">{accountName}</small>
|
||||
</span>
|
||||
<button type="button" onClick={share} aria-label="더 보기" className="ml-auto grid size-7 cursor-pointer place-items-center text-(--ink)">
|
||||
<MoreIcon />
|
||||
</button>
|
||||
</div>
|
||||
<div className="relative aspect-[4/5] overflow-hidden" onClick={onTap}>
|
||||
{n > 1 && (
|
||||
<span className="absolute top-3 right-3 z-[2] rounded-full bg-[rgb(30_36_56/0.55)] px-[9px] py-[3px] text-xs font-extrabold text-white" aria-hidden="true">
|
||||
{index + 1}/{n}
|
||||
</span>
|
||||
)}
|
||||
<div
|
||||
className="b-noscroll flex h-full snap-x snap-mandatory overflow-x-auto"
|
||||
onScroll={(e) => setIndex(Math.round(e.currentTarget.scrollLeft / e.currentTarget.clientWidth))}
|
||||
tabIndex={n > 1 ? 0 : undefined}
|
||||
aria-label={n > 1 ? `슬라이드 ${n}장, 옆으로 넘겨 보세요` : undefined}
|
||||
role={n > 1 ? 'region' : undefined}
|
||||
>
|
||||
{post.slides.map((s, i) => (
|
||||
<SlideView key={i} slide={s} bg={bgs[i]} />
|
||||
))}
|
||||
</div>
|
||||
{pop > 0 && (
|
||||
<svg key={pop} className="b-heart-pop pointer-events-none absolute top-1/2 left-1/2 z-[4] -mt-12 -ml-12 w-24 opacity-0" viewBox="0 0 24 24" fill="#fff" aria-hidden="true">
|
||||
<path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" />
|
||||
</svg>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative flex items-center gap-3.5 px-3 pt-2.5 pb-1 [&_svg]:size-[26px] [&_svg]:stroke-[1.9]">
|
||||
<button type="button" onClick={() => setLike(!liked)} aria-pressed={liked} aria-label="좋아요" className="grid size-7 cursor-pointer place-items-center">
|
||||
<HeartIcon className={liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink)'} />
|
||||
</button>
|
||||
<button type="button" onClick={comments} aria-label="댓글 보기" className="grid size-7 cursor-pointer place-items-center">
|
||||
<CommentIcon className="fill-none stroke-(--ink) [stroke-linejoin:round]" />
|
||||
</button>
|
||||
<button type="button" onClick={share} aria-label="보내기" className="grid size-7 cursor-pointer place-items-center">
|
||||
<SendIcon className="fill-none stroke-(--ink) [stroke-linecap:round] [stroke-linejoin:round]" />
|
||||
</button>
|
||||
{n > 1 && (
|
||||
<span className="absolute left-1/2 flex -translate-x-1/2 gap-1" aria-hidden="true">
|
||||
{post.slides.map((_, k) => (
|
||||
<i key={k} className={cx('size-1.5 rounded-full', k === index ? 'bg-(--rain)' : 'bg-[#cfd8e6]')} />
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
<button type="button" onClick={toggleSave} aria-pressed={saved} aria-label="저장" className="ml-auto grid size-7 cursor-pointer place-items-center">
|
||||
<SaveIcon className={cx('stroke-(--ink) [stroke-linejoin:round]', saved ? 'fill-(--ink)' : 'fill-none')} />
|
||||
</button>
|
||||
</div>
|
||||
<p className="px-3 py-0.5 text-sm font-extrabold">좋아요 {likeCount.toLocaleString()}개</p>
|
||||
<p className="px-3 py-0.5 text-sm">
|
||||
<b className="mr-[5px] font-extrabold">날씨각</b>
|
||||
{post.caption}
|
||||
</p>
|
||||
<button type="button" onClick={comments} className="block cursor-pointer px-3 pt-[3px] text-sm font-semibold text-(--ink3)">
|
||||
{post.comment_count ? `댓글 ${post.comment_count}개 모두 보기` : '첫 댓글 남기기'}
|
||||
</button>
|
||||
<p className="px-3 pt-1 pb-3 text-[11.5px] font-semibold text-(--ink3)">{ago(post.published_at)}</p>
|
||||
</article>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getSeasonWeekOptions, listArticlesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { ArticleCategory } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { ARTICLE_CAT, cardBg, fall, shortDay } from './lib'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Chips, Ic, StateBox } from './ui'
|
||||
|
||||
const CATS = [
|
||||
['all', '전체'],
|
||||
['season', '계절 소식'],
|
||||
['tip', '날씨 상식'],
|
||||
['gak', '각 원리'],
|
||||
] as const
|
||||
|
||||
const CAT_PARAM = { season: ArticleCategory.SEASON, tip: ArticleCategory.TIP, gak: ArticleCategory.GAK } as const
|
||||
|
||||
export function SeasonPage() {
|
||||
const { open } = useSheet()
|
||||
const [cat, setCat] = useState<(typeof CATS)[number][0]>('all')
|
||||
const week = useQuery(getSeasonWeekOptions())
|
||||
const arts = useQuery(listArticlesOptions(cat === 'all' ? undefined : { query: { category: CAT_PARAM[cat] } }))
|
||||
const w = week.data
|
||||
const list = arts.data?.articles ?? []
|
||||
const progress = Math.round((w?.progress ?? 0) * 100)
|
||||
|
||||
return (
|
||||
<section aria-label="계절·상식">
|
||||
{w?.headline ? (
|
||||
<button type="button" onClick={() => open({ type: 'seasonWeek' })} className="relative mx-3 mt-3 flex min-h-[250px] w-[calc(100%-24px)] cursor-pointer flex-col overflow-hidden rounded-[28px] bg-[linear-gradient(180deg,#ffd2bb,#fff2ea)] p-5 text-left">
|
||||
<p className="m-0 text-[13px] font-extrabold opacity-75">이번 주 특집 · {w.week}번째 주</p>
|
||||
<p className="mt-1 max-w-[62%] font-jua text-[29px] leading-tight">{w.headline}</p>
|
||||
<span className="b-fall pointer-events-none absolute top-[18%] right-3.5 w-[38%]" style={fall('.1s')}>
|
||||
<Ic name="maple" className="w-full drop-shadow-[0_16px_18px_rgb(40_48_74/0.18)]" />
|
||||
</span>
|
||||
{(w.poem_lines ?? []).length > 0 && (
|
||||
<p className="mt-auto max-w-[72%] pt-3 font-batang text-[22px] leading-[1.7]">
|
||||
{w.poem_lines?.map((l, i) => (
|
||||
<span key={l}>
|
||||
{i > 0 && <br />}
|
||||
{l}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
)}
|
||||
{w.term_now && w.term_next && (
|
||||
<div className={cx('max-w-[70%]', (w.poem_lines ?? []).length ? 'mt-2.5' : 'mt-auto')}>
|
||||
<div className="flex justify-between text-xs font-extrabold text-(--ink2)">
|
||||
<span>
|
||||
{w.term_now.name} {shortDay(w.term_now.day)}
|
||||
</span>
|
||||
<span>
|
||||
{w.term_next.name} {shortDay(w.term_next.day)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 h-[7px] overflow-hidden rounded-full bg-[rgb(40_48_74/0.1)]" role="img" aria-label={`다음 절기까지 ${progress}% 지났어요`}>
|
||||
<s className="block h-full bg-(--orange)" style={{ width: `${progress}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
) : (
|
||||
<StateBox loading={week.isPending} error={week.error} onRetry={() => week.refetch()} empty="이번 주 특집이 아직 없어요." />
|
||||
)}
|
||||
<Chips items={CATS} value={cat} onChange={setCat} label="분류" />
|
||||
<div className="mt-1.5">
|
||||
<StateBox loading={arts.isPending} error={arts.error} onRetry={() => arts.refetch()} empty={arts.isSuccess && !list.length ? '읽을거리가 아직 없어요.' : undefined} />
|
||||
{list.map((a) => (
|
||||
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="grid w-full cursor-pointer grid-cols-[1fr_84px] items-center gap-3 border-b-[1.5px] border-(--line) px-4 py-3.5 text-left">
|
||||
<span>
|
||||
<span className={cx('text-xs font-extrabold', ARTICLE_CAT[a.category]?.[1])}>{ARTICLE_CAT[a.category]?.[0]}</span>
|
||||
<b className="mt-0.5 block font-jua text-[17.5px] leading-snug font-normal">{a.title}</b>
|
||||
<small className="mt-1 block text-xs font-semibold text-(--ink3)">{a.read_minutes}분 읽기</small>
|
||||
</span>
|
||||
<span className={cx('grid h-[84px] place-items-center rounded-[18px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-[54px]" />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
import { useMutation, useQuery, useQueryClient } 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,
|
||||
listCommentsQueryKey,
|
||||
listCommentsOptions,
|
||||
listRegionsOptions,
|
||||
loginMutation,
|
||||
signupMutation,
|
||||
unlikeCommentMutation,
|
||||
} from '../api/client/@tanstack/react-query.gen'
|
||||
import type { CommentData, Factor, ResAuth, ResIndexDetail } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { useAuth } from './authContext'
|
||||
import { ago, ARTICLE_CAT, articleMeta, cardBg, dayLabel, shortDay } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { SheetContext, useSheet, type SharePayload, type SheetState } from './sheetContext'
|
||||
import { HeartIcon } from './svg'
|
||||
import { Ic, StateBox } from './ui'
|
||||
|
||||
export function SheetProvider({ children }: { children: ReactNode }) {
|
||||
const [state, setState] = useState<SheetState>(null)
|
||||
const open = useCallback((s: Exclude<SheetState, null>) => setState(s), [])
|
||||
const close = useCallback(() => setState(null), [])
|
||||
const api = useMemo(() => ({ open, close }), [open, close])
|
||||
|
||||
// 로그인이 필요한 요청이 401을 받으면 로그인 창을 띄운다
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'required' && setState({ type: 'login' })), [])
|
||||
|
||||
return (
|
||||
<SheetContext value={api}>
|
||||
{children}
|
||||
<SheetHost state={state} onClose={close} />
|
||||
</SheetContext>
|
||||
)
|
||||
}
|
||||
|
||||
const TITLES = { article: '읽을거리', seasonWeek: '이번 주 특집', share: '보내기', comments: '댓글', login: '로그인', region: '지역 바꾸기' } as const
|
||||
|
||||
/** 아래에서 올라오는 창: 네이티브 <dialog>라 ESC·포커스 가두기·포커스 되돌리기가 기본으로 된다 */
|
||||
function SheetHost({ state, onClose }: { state: SheetState; onClose: () => void }) {
|
||||
const ref = useRef<HTMLDialogElement>(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 title = !state ? '' : state.type === 'gak' ? gakTitle : state.type === 'article' ? articleTitle || TITLES.article : TITLES[state.type]
|
||||
|
||||
return (
|
||||
<dialog
|
||||
ref={ref}
|
||||
aria-label={title}
|
||||
onClose={onClose}
|
||||
onClick={(e) => {
|
||||
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 && (
|
||||
<div className="b-sheet flex max-h-[86dvh] flex-col rounded-t-[22px] bg-white">
|
||||
<div className="relative border-b border-(--line) px-4 pt-2 pb-2.5 text-center">
|
||||
<div className="mx-auto mb-2.5 h-1 w-10 rounded-full bg-[#d5dce7]" aria-hidden="true" />
|
||||
<h3 className="m-0 text-[15px] font-extrabold">{title}</h3>
|
||||
<button type="button" onClick={onClose} aria-label="닫기" className="absolute right-3 bottom-2 grid size-[30px] cursor-pointer place-items-center text-xl text-(--ink2)">
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
{state.type === 'gak' && <GakSheet indexId={state.indexId} onTitle={setGakTitle} />}
|
||||
{state.type === 'article' && <ArticleSheet articleId={state.articleId} onTitle={setArticleTitle} />}
|
||||
{state.type === 'seasonWeek' && <SeasonWeekSheet />}
|
||||
{state.type === 'share' && <ShareSheet share={state.share} />}
|
||||
{state.type === 'comments' && <CommentsSheet postId={state.postId} />}
|
||||
{state.type === 'login' && <LoginSheet onDone={onClose} />}
|
||||
{state.type === 'region' && <RegionSheet onDone={onClose} />}
|
||||
</div>
|
||||
)}
|
||||
</dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function Body({ children, className }: { children: ReactNode; className?: string }) {
|
||||
return <div className={cx('flex-1 overflow-auto px-4 pt-3.5 pb-[18px]', className)}>{children}</div>
|
||||
}
|
||||
|
||||
/* ---------- 각 계산 근거 ---------- */
|
||||
function Radar({ name, factors, size = 250 }: { name: string; factors: Factor[]; size?: number }) {
|
||||
const c = size / 2
|
||||
const r = size / 2 - 34
|
||||
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 (
|
||||
<svg className="mx-auto mt-2 block w-full max-w-[250px]" viewBox={`0 0 ${size} ${size}`} role="img" aria-label={`${name} 요소별 점수`}>
|
||||
{[0.25, 0.5, 0.75, 1].map((v) => (
|
||||
<polygon key={v} points={ring(v)} fill={v === 1 ? '#f7f9fc' : 'none'} stroke="#d9e2ef" strokeWidth="1.5" />
|
||||
))}
|
||||
{factors.map((f, i) => (
|
||||
<line key={f.axis} x1={c} y1={c} x2={pt(i, 1)[0]} y2={pt(i, 1)[1]} stroke="#e3e9f2" strokeWidth="1.5" />
|
||||
))}
|
||||
<polygon points={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) => (
|
||||
<circle key={f.axis} cx={pt(i, f.value / 100)[0]} cy={pt(i, f.value / 100)[1]} r="4.5" fill="#fff" stroke="#ff7a45" strokeWidth="2.5" />
|
||||
))}
|
||||
{factors.map((f, i) => (
|
||||
<text key={f.axis} x={pt(i, 1.2)[0]} y={pt(i, 1.2)[1]} textAnchor="middle" dominantBaseline="middle" fontFamily="Jua,sans-serif" fontSize="14" fill="#28304a">
|
||||
{f.label}
|
||||
</text>
|
||||
))}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
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])
|
||||
|
||||
if (!g) return <Body>{<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty="이 각의 계산 근거가 아직 없어요." className="mx-0" />}</Body>
|
||||
const factors = d.factors ?? []
|
||||
return (
|
||||
<Body>
|
||||
<div className="flex items-center gap-3">
|
||||
<Ic name={g.icon} className="w-[58px]" />
|
||||
<div>
|
||||
<h4 className="m-0 font-jua text-[22px] font-normal">{g.name}</h4>
|
||||
{d.description && <p className="mt-0.5 text-[13.5px] font-semibold text-(--ink2)">{d.description}</p>}
|
||||
</div>
|
||||
<b className="ml-auto font-bagel text-[42px] font-normal text-(--orange)">{g.score}</b>
|
||||
</div>
|
||||
{factors.length > 2 && <Radar name={g.name} factors={factors} />}
|
||||
{g.trend && g.trend.length > 0 && (
|
||||
<div className="mt-2.5 grid grid-cols-3 gap-2">
|
||||
{g.trend.map((t, j) => (
|
||||
<div key={t.day} className="rounded-2xl bg-[#f3f6fb] p-2.5 text-center">
|
||||
<small className="text-xs font-extrabold text-(--ink2)">{dayLabel(t.day, j)}</small>
|
||||
<b className="block font-bagel text-2xl font-normal text-(--orange)">{t.score}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-3.5 flex flex-col gap-2.5">
|
||||
{factors.map((f) => (
|
||||
<div key={f.axis} className="grid grid-cols-[50px_1fr_52px] items-center gap-x-2.5 text-[13.5px] font-bold">
|
||||
<span>{f.label}</span>
|
||||
<i className="block h-[9px] overflow-hidden rounded-full bg-[#e3eaf4]">
|
||||
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,var(--orange))]" style={{ width: `${f.value}%` }} />
|
||||
</i>
|
||||
<em className="text-right text-xs text-(--ink2) not-italic">비중 {f.weight}%</em>
|
||||
<p className="col-start-2 col-end-4 -mt-0.5 text-[12.5px] font-semibold text-(--ink2)">{f.note}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3.5 flex flex-col gap-1.5 text-[13px] font-semibold text-(--ink2)">
|
||||
{d.zero_reason && (
|
||||
<span>
|
||||
<b className="text-(--heart)">오늘 0점인 이유:</b> {d.zero_reason}
|
||||
</span>
|
||||
)}
|
||||
{d.zero_rules && (
|
||||
<span>
|
||||
<b className="text-(--ink)">바로 0점:</b> {d.zero_rules}
|
||||
</span>
|
||||
)}
|
||||
{d.limit && (
|
||||
<span>
|
||||
<b className="text-(--ink)">반영 못 한 것:</b> {d.limit}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 읽을거리 ---------- */
|
||||
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])
|
||||
|
||||
if (!a) return <Body>{<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty="글을 찾지 못했어요." className="mx-0" />}</Body>
|
||||
return (
|
||||
<Body>
|
||||
<div className={cx('mb-3.5 grid h-[150px] place-items-center rounded-[20px]', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-24" />
|
||||
</div>
|
||||
<p className="text-[13px] font-extrabold text-(--ink2)">{articleMeta(a)}</p>
|
||||
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">{a.title}</h4>
|
||||
{(q.data?.body ?? []).map((t) => (
|
||||
<p key={t} className="mb-2.5 text-[15px] leading-[1.7]">
|
||||
{t}
|
||||
</p>
|
||||
))}
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 이번 주 특집 ---------- */
|
||||
function SeasonWeekSheet() {
|
||||
const { open } = useSheet()
|
||||
const q = useQuery(getSeasonWeekOptions())
|
||||
const w = q.data
|
||||
if (!w?.headline) return <Body>{<StateBox loading={q.isPending} error={q.error} onRetry={() => q.refetch()} empty="이번 주 특집이 아직 없어요." className="mx-0" />}</Body>
|
||||
return (
|
||||
<Body>
|
||||
<div className="mb-3.5 grid h-[150px] place-items-center rounded-[20px] b-bg-peach">
|
||||
<Ic name="maple" className="w-24" />
|
||||
</div>
|
||||
<p className="text-[13px] font-extrabold text-(--ink2)">이번 주 특집 · {w.week}번째 주</p>
|
||||
<h4 className="mt-1.5 mb-2.5 font-jua text-2xl leading-tight font-normal">{w.headline}</h4>
|
||||
{(w.poem_lines ?? []).length > 0 && (
|
||||
<p className="mb-2.5 font-batang text-[17px] leading-[1.7]">
|
||||
{w.poem_lines?.join(' ')}
|
||||
{w.author && <small className="block font-sans text-xs font-semibold text-(--ink3)">{w.author}</small>}
|
||||
</p>
|
||||
)}
|
||||
{w.term_now && w.term_next && (
|
||||
<p className="mb-2.5 text-[15px] leading-[1.7]">
|
||||
지금 절기는 {w.term_now.name}({shortDay(w.term_now.day)}), 다음 절기는 {w.term_next.name}({shortDay(w.term_next.day)})예요.
|
||||
</p>
|
||||
)}
|
||||
{(w.news ?? []).map((n) => (
|
||||
<button key={n.code} type="button" onClick={() => open({ type: 'article', articleId: n.article_id })} className="flex w-full cursor-pointer items-center gap-2.5 border-b-[1.5px] border-(--line) py-2.5 text-left font-jua text-base">
|
||||
<Ic name={n.icon} className="w-8" />
|
||||
{n.title}
|
||||
</button>
|
||||
))}
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 보내기 ---------- */
|
||||
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} — ${share.title} · 날씨각`
|
||||
|
||||
// 휴대폰 기본 공유창. 없거나 실패하면 링크 복사로 대신한다.
|
||||
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 (
|
||||
<Body>
|
||||
<div className={cx('flex items-center gap-3 rounded-[20px] p-3.5', `b-bg-${share.bg}`)}>
|
||||
<Ic name={share.icon} className="w-[58px]" />
|
||||
<div>
|
||||
<b className="block font-jua text-[19px] font-normal">{share.title}</b>
|
||||
<small className="font-bold opacity-80">날씨각 · {region.name}</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-col gap-1.5" role="radiogroup" aria-label="함께 보낼 말">
|
||||
{opts.map((o, k) => (
|
||||
<label key={o} className="flex cursor-pointer items-center gap-2.5 rounded-[14px] bg-[#f3f6fb] px-3 py-2.5 font-semibold">
|
||||
<input type="radio" name="share-msg" checked={pick === k} onChange={() => setPick(k)} className="accent-(--orange)" />
|
||||
{o}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{isMine && (
|
||||
<textarea
|
||||
value={mine}
|
||||
onChange={(e) => setMine(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={80}
|
||||
placeholder="예: 오늘 한강 갈래? 🌇"
|
||||
aria-label="보낼 말 직접 쓰기"
|
||||
className="mt-1.5 w-full resize-none rounded-[14px] border border-[#dfe5ee] px-3 py-2.5"
|
||||
/>
|
||||
)}
|
||||
<div className="mt-3.5 grid grid-cols-2 gap-2">
|
||||
<button type="button" onClick={shareNative} className="cursor-pointer rounded-[16px] bg-(--orange-deep) py-3 font-jua text-base text-white">
|
||||
공유하기
|
||||
</button>
|
||||
<button type="button" onClick={copy} className="cursor-pointer rounded-[16px] bg-(--ink) py-3 font-jua text-base text-white">
|
||||
링크 복사
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-3 min-h-5 text-center text-[13px] font-bold text-[#1f9d62]" aria-live="polite">
|
||||
{toast}
|
||||
</p>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 댓글 ---------- */
|
||||
const AV_COLORS = ['#ff8e4e', '#4f97e3', '#1f9d62', '#7a5cd6', '#d6457a', '#c2471b']
|
||||
const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']
|
||||
|
||||
function CommentRow({ c, index, postId }: { c: CommentData; index: number; postId: number }) {
|
||||
const { region } = useRegion()
|
||||
const { loggedIn } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const queryClient = useQueryClient()
|
||||
const [liked, setLiked] = useState(c.liked)
|
||||
const [count, setCount] = useState(c.like_count)
|
||||
const like = useMutation(likeCommentMutation())
|
||||
const unlike = useMutation(unlikeCommentMutation())
|
||||
const remove = useMutation(deleteCommentMutation())
|
||||
|
||||
const toggle = () => {
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const next = !liked
|
||||
setLiked(next)
|
||||
setCount((n) => n + (next ? 1 : -1))
|
||||
;(next ? like : unlike).mutate(
|
||||
{ path: { comment_id: c.comment_id } },
|
||||
{
|
||||
onSuccess: (res) => {
|
||||
setLiked(!!res.liked)
|
||||
if (res.like_count != null) setCount(res.like_count)
|
||||
},
|
||||
onError: () => {
|
||||
setLiked(!next)
|
||||
setCount(c.like_count)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const del = () =>
|
||||
remove.mutate(
|
||||
{ path: { comment_id: c.comment_id } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: listCommentsQueryKey({ path: { post_id: postId } }) })
|
||||
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-[34px_1fr_24px] items-start gap-2.5 py-2">
|
||||
<span className="grid size-[34px] place-items-center rounded-full text-[13px] font-extrabold text-white" style={{ background: AV_COLORS[(c.nickname.charCodeAt(0) + index) % AV_COLORS.length] }} aria-hidden="true">
|
||||
{c.nickname[0]}
|
||||
</span>
|
||||
<div>
|
||||
<p className="m-0 text-sm">
|
||||
<b className="mr-1.5 font-extrabold">{c.nickname}</b>
|
||||
{c.body}
|
||||
</p>
|
||||
<small className="mt-0.5 block text-xs font-bold text-(--ink3)">
|
||||
{ago(c.created_at)} · 좋아요 {count}개
|
||||
{c.mine && (
|
||||
<>
|
||||
{' · '}
|
||||
<button type="button" onClick={del} disabled={remove.isPending} className="cursor-pointer font-bold text-(--ink3) underline-offset-2 hover:underline">
|
||||
지우기
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</small>
|
||||
{remove.isError && <small className="block text-xs font-bold text-(--heart)">지우지 못했어요. 다시 해 주세요.</small>}
|
||||
</div>
|
||||
<button type="button" onClick={toggle} aria-pressed={liked} aria-label="댓글 좋아요" className="cursor-pointer pt-1">
|
||||
<HeartIcon className={cx('size-4 stroke-2', liked ? 'fill-(--heart) stroke-(--heart)' : 'fill-none stroke-(--ink3)')} />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CommentsSheet({ postId }: { postId: number }) {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const { loggedIn, me } = useAuth()
|
||||
const queryClient = useQueryClient()
|
||||
const list = useQuery(listCommentsOptions({ path: { post_id: postId } }))
|
||||
const add = useMutation(addCommentMutation())
|
||||
const [text, setText] = useState('')
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const comments = list.data?.comments ?? []
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!loggedIn) return open({ type: 'login' })
|
||||
const body = text.trim()
|
||||
if (!body) return
|
||||
add.mutate(
|
||||
{ path: { post_id: postId }, body: { body } },
|
||||
{
|
||||
onSuccess: () => {
|
||||
setText('')
|
||||
queryClient.invalidateQueries({ queryKey: listCommentsQueryKey({ path: { post_id: postId } }) })
|
||||
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Body>
|
||||
{comments.length ? (
|
||||
comments.map((c, k) => <CommentRow key={c.comment_id} c={c} index={k} postId={postId} />)
|
||||
) : list.isSuccess ? (
|
||||
<p className="my-6 text-center font-semibold text-(--ink3)">
|
||||
아직 댓글이 없어요.
|
||||
<br />첫 댓글을 남겨 보세요.
|
||||
</p>
|
||||
) : (
|
||||
<StateBox loading={list.isPending} error={list.error} onRetry={() => list.refetch()} className="mx-0" />
|
||||
)}
|
||||
</Body>
|
||||
<div className="flex justify-around pt-1 pb-2 text-[22px]" role="group" aria-label="빠른 이모지">
|
||||
{EMOJIS.map((e) => (
|
||||
<button
|
||||
key={e}
|
||||
type="button"
|
||||
className="cursor-pointer"
|
||||
onClick={() => {
|
||||
setText((t) => (t + e).slice(0, 60))
|
||||
inputRef.current?.focus()
|
||||
}}
|
||||
>
|
||||
{e}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{add.isError && (
|
||||
<p className="px-4 pb-1 text-center text-xs font-bold text-(--heart)" role="alert">
|
||||
댓글을 올리지 못했어요. 다시 해 주세요.
|
||||
</p>
|
||||
)}
|
||||
<form onSubmit={submit} className="flex items-center gap-2.5 border-t border-(--line) px-3 pt-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))]">
|
||||
<input ref={inputRef} value={text} onChange={(e) => setText(e.target.value)} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<button type="submit" disabled={add.isPending || (loggedIn && !text.trim())} className="cursor-pointer font-extrabold text-(--rain) disabled:opacity-40">
|
||||
게시
|
||||
</button>
|
||||
</form>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 로그인 ---------- */
|
||||
const AUTH_ERRORS: Record<string, string> = {
|
||||
AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.',
|
||||
AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.',
|
||||
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8자 이상, 닉네임은 2~12자로 써 주세요.',
|
||||
}
|
||||
|
||||
function LoginSheet({ onDone }: { onDone: () => void }) {
|
||||
const { me, logout } = useAuth()
|
||||
const [mode, setMode] = useState<'login' | 'signup'>('login')
|
||||
const [loginId, setLoginId] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [nickname, setNickname] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const login = useMutation(loginMutation())
|
||||
const signup = useMutation(signupMutation())
|
||||
const pending = login.isPending || signup.isPending
|
||||
|
||||
const done = (res: ResAuth) => {
|
||||
if (!res.result?.success || !res.access_token) {
|
||||
setError(AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.')
|
||||
return
|
||||
}
|
||||
setTokens(res.access_token, res.refresh_token ?? null)
|
||||
onDone()
|
||||
}
|
||||
const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.')
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: done, onError: fail })
|
||||
else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: done, onError: fail })
|
||||
}
|
||||
|
||||
if (me)
|
||||
return (
|
||||
<Body className="flex flex-col gap-2.5 text-center">
|
||||
<p className="text-sm font-semibold text-(--ink2)">{me.nickname}(으)로 로그인했어요.</p>
|
||||
<button type="button" onClick={logout} className="cursor-pointer rounded-[14px] bg-[#f3f6fb] p-[13px] text-[15px] font-extrabold text-(--ink)">
|
||||
로그아웃
|
||||
</button>
|
||||
</Body>
|
||||
)
|
||||
|
||||
const field = 'w-full rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3'
|
||||
return (
|
||||
<Body>
|
||||
<form onSubmit={submit} className="flex flex-col gap-2.5">
|
||||
<p className="text-center text-sm font-semibold text-(--ink2)">좋아요·저장·댓글은 로그인한 뒤에 할 수 있어요.</p>
|
||||
<div className="grid grid-cols-2 gap-1 rounded-full bg-[#f3f6fb] p-1" role="group" aria-label="로그인 또는 가입">
|
||||
{(
|
||||
[
|
||||
['login', '로그인'],
|
||||
['signup', '처음이에요'],
|
||||
] as const
|
||||
).map(([m, l]) => (
|
||||
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full py-2 text-sm font-extrabold', mode === m ? 'bg-(--ink) text-white' : 'text-(--ink2)')}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<input value={loginId} onChange={(e) => setLoginId(e.target.value)} autoComplete="username" required minLength={4} maxLength={20} placeholder="아이디" aria-label="아이디" className={field} />
|
||||
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'} required minLength={8} placeholder="비밀번호 (8자 이상)" aria-label="비밀번호" className={field} />
|
||||
{mode === 'signup' && <input value={nickname} onChange={(e) => setNickname(e.target.value)} required minLength={2} maxLength={12} placeholder="닉네임 (2~12자)" aria-label="닉네임" className={field} />}
|
||||
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
|
||||
{error}
|
||||
</p>
|
||||
<button type="submit" disabled={pending} className="cursor-pointer rounded-[14px] bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
{mode === 'login' ? '로그인' : '가입하고 시작하기'}
|
||||
</button>
|
||||
<button type="button" onClick={onDone} className="cursor-pointer rounded-[14px] p-[13px] text-[15px] font-extrabold text-(--ink2)">
|
||||
나중에 할게요
|
||||
</button>
|
||||
</form>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
|
||||
/* ---------- 지역 ---------- */
|
||||
const LOCATE_TEXT = { idle: '', locating: '위치를 찾는 중이에요…', denied: '위치 권한이 꺼져 있어요. 아래 목록에서 골라 주세요.', error: '위치를 찾지 못했어요. 아래 목록에서 골라 주세요.' } as const
|
||||
|
||||
function RegionSheet({ onDone }: { onDone: () => void }) {
|
||||
const { region, setRegion, locate, locateStatus } = useRegion()
|
||||
const { me, logout } = useAuth()
|
||||
const { open } = useSheet()
|
||||
const [q, setQ] = useState('')
|
||||
const deferred = useDeferredValue(q.trim())
|
||||
const list = useQuery(listRegionsOptions(deferred ? { query: { q: deferred } } : undefined))
|
||||
const regions = list.data?.regions ?? []
|
||||
|
||||
return (
|
||||
<Body>
|
||||
<button type="button" onClick={locate} disabled={locateStatus === 'locating'} className="w-full cursor-pointer rounded-full bg-(--orange) p-3 font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
지금 위치로 찾기
|
||||
</button>
|
||||
<p className="mt-2 min-h-5 text-center text-[13px] font-bold text-(--ink2)" aria-live="polite">
|
||||
{LOCATE_TEXT[locateStatus]}
|
||||
</p>
|
||||
<input value={q} onChange={(e) => setQ(e.target.value)} placeholder="구 이름으로 찾기 (예: 마포)" aria-label="구 이름으로 찾기" className="mt-1 w-full rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" />
|
||||
<StateBox loading={list.isPending} error={list.error} onRetry={() => list.refetch()} empty={list.isSuccess && !regions.length ? '찾는 구가 없어요.' : undefined} className="mx-0" />
|
||||
<ul className="mt-2 flex flex-col">
|
||||
{regions.map((r) => (
|
||||
<li key={r.code}>
|
||||
<button
|
||||
type="button"
|
||||
aria-current={r.code === region.code ? 'true' : undefined}
|
||||
onClick={() => {
|
||||
setRegion(r)
|
||||
onDone()
|
||||
}}
|
||||
className={cx('flex w-full cursor-pointer items-center justify-between border-b-[1.5px] border-(--line) px-1 py-3 text-left font-jua text-[17px]', r.code === region.code && 'text-(--orange)')}
|
||||
>
|
||||
{r.name}
|
||||
{r.code === region.code && <small className="font-sans text-xs font-extrabold">지금 보는 곳</small>}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="mt-4 flex items-center justify-center gap-2 text-[13px] font-bold text-(--ink2)">
|
||||
{me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·저장·댓글을 쓸 수 있어요'}
|
||||
<button type="button" onClick={me ? logout : () => open({ type: 'login' })} className="cursor-pointer font-extrabold text-(--rain)">
|
||||
{me ? '로그아웃' : '로그인'}
|
||||
</button>
|
||||
</p>
|
||||
</Body>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getSkyOptions, getSkyRankingOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { RegionData, SpotData } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { clockShort, dayLabel, timeWords } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { Rail, Sec, StateBox } from './ui'
|
||||
|
||||
const W = 400
|
||||
const H = 260
|
||||
const BLOCKS = [
|
||||
[20, 20, 90, 60],
|
||||
[130, 18, 100, 52],
|
||||
[262, 22, 110, 48],
|
||||
[24, 190, 110, 54],
|
||||
[170, 196, 90, 50],
|
||||
[290, 180, 92, 62],
|
||||
]
|
||||
|
||||
/** 내 구 중심을 기준으로 명소를 km 단위로 놓고, 해 지는 방향을 그린다 */
|
||||
function SpotMap({ region, spots, azimuth }: { region: RegionData; spots: SpotData[]; azimuth: number | null | undefined }) {
|
||||
const kx = 111 * Math.cos((region.lat * Math.PI) / 180)
|
||||
const pts = spots.map((s) => ({ no: s.no, x: (s.lon - region.lon) * kx, y: (s.lat - region.lat) * 111 }))
|
||||
const maxX = Math.max(0.5, ...pts.map((p) => Math.abs(p.x)))
|
||||
const maxY = Math.max(0.5, ...pts.map((p) => Math.abs(p.y)))
|
||||
const scale = Math.min(160 / maxX, 95 / maxY)
|
||||
const cx0 = W / 2
|
||||
const cy0 = H / 2
|
||||
const az = ((azimuth ?? 270) * Math.PI) / 180
|
||||
const dir = (len: number, turn = 0) => [cx0 + Math.sin(az + turn) * len, cy0 - Math.cos(az + turn) * len] as const
|
||||
const tip = dir(190)
|
||||
const label = dir(120)
|
||||
|
||||
return (
|
||||
<div className="mx-3 mt-3 overflow-hidden rounded-[26px] bg-[#eef2e8] shadow-[inset_0_0_0_2px_#e1e7da]">
|
||||
<svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={`${region.name} 주변 노을 명소 지도`} className="block h-auto w-full">
|
||||
<rect width={W} height={H} fill="#eef2e8" />
|
||||
{BLOCKS.map(([x, y, w, h]) => (
|
||||
<rect key={`${x}-${y}`} x={x} y={y} width={w} height={h} rx="10" fill="#e1e7da" />
|
||||
))}
|
||||
<path d={`M${W / 2 - 10} 0 L${W / 2 + 4} ${H}`} stroke="#fff" strokeWidth="9" />
|
||||
<path d={`M0 ${H / 2 - 30} H${W}`} stroke="#fff" strokeWidth="10" />
|
||||
{azimuth != null && (
|
||||
<>
|
||||
<path d={`M${cx0} ${cy0} L${dir(260, -0.3).join(' ')} L${dir(260, 0.3).join(' ')} Z`} fill="#ff8e4e" opacity=".18" />
|
||||
<path d={`M${cx0} ${cy0} L${tip.join(' ')}`} stroke="#ff7a45" strokeWidth="3" strokeDasharray="7 6" />
|
||||
<text x={Math.min(W - 110, Math.max(8, label[0] - 50))} y={label[1] + 26} fontFamily="Jua,sans-serif" fontSize="14" fill="#d4552a">
|
||||
해 지는 쪽 {azimuth}°
|
||||
</text>
|
||||
</>
|
||||
)}
|
||||
<circle cx={cx0} cy={cy0} r="13" fill="#4f97e3" opacity=".25" />
|
||||
<circle cx={cx0} cy={cy0} r="6" fill="#4f97e3" stroke="#fff" strokeWidth="2" />
|
||||
<text x={cx0 + 14} y={cy0 + 18} fontFamily="Pretendard Variable,sans-serif" fontWeight="800" fontSize="11" fill="#2f6fb7">
|
||||
지금 여기
|
||||
</text>
|
||||
{pts.map((p) => (
|
||||
<g key={p.no}>
|
||||
<circle cx={cx0 + p.x * scale} cy={cy0 - p.y * scale} r="13" fill="#ff7a45" stroke="#fff" strokeWidth="3" />
|
||||
<text x={cx0 + p.x * scale} y={cy0 - p.y * scale + 5} textAnchor="middle" fontFamily="Bagel Fat One,sans-serif" fontSize="14" fill="#fff">
|
||||
{p.no}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
</svg>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Li({ no, title, sub, right, meter, mine = false }: { no: number; title: string; sub?: string | null; right: string; meter?: number; mine?: boolean }) {
|
||||
return (
|
||||
<li className={cx('grid grid-cols-[34px_1fr_auto] items-center gap-2.5 border-b-[1.5px] border-(--line) px-1 py-3 last:border-b-0', mine && 'rounded-2xl bg-white')}>
|
||||
<span className="text-center font-bagel text-xl text-(--orange)">{no}</span>
|
||||
<span>
|
||||
<b className="block font-jua text-[17px] font-normal">
|
||||
{title}
|
||||
{mine && <small className="ml-1.5 font-sans text-xs font-extrabold text-(--rain)">내 지역</small>}
|
||||
</b>
|
||||
{sub && <small className="text-[12.5px] font-semibold text-(--ink2)">{sub}</small>}
|
||||
{meter != null && (
|
||||
<span className="mt-[5px] block h-1.5 overflow-hidden rounded-full bg-[#eef1f6]">
|
||||
<s className="block h-full bg-[linear-gradient(90deg,#ffc86e,#ff6f8e)]" style={{ width: `${meter}%` }} />
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<em className="font-jua text-base not-italic">{right}</em>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
export function SkyPage() {
|
||||
const { region } = useRegion()
|
||||
const sky = useQuery(getSkyOptions({ query: { region: region.code } }))
|
||||
const ranking = useQuery(getSkyRankingOptions())
|
||||
const s = sky.data?.sunset
|
||||
const times = s?.best_times ?? []
|
||||
const peak = times.find((t) => t.kind === 'peak')
|
||||
const spots = sky.data?.spots ?? []
|
||||
const days = sky.data?.days ?? []
|
||||
const items = (ranking.data?.items ?? []).slice(0, 8)
|
||||
|
||||
return (
|
||||
<section aria-label="노을">
|
||||
{s ? (
|
||||
<div className="relative mx-3 mt-1 min-h-[300px] overflow-hidden rounded-[32px] bg-[linear-gradient(180deg,#7e6fe6,#f08aa2_58%,#ffc28a)] px-5 pt-5 pb-16 text-white">
|
||||
<div className="b-skyline pointer-events-none absolute inset-0 [--sky-h:22%]" aria-hidden="true" />
|
||||
<p className="relative m-0 text-[13px] font-extrabold opacity-90">오늘 노을 · {region.name}</p>
|
||||
<b className="relative mt-1.5 block font-bagel text-[96px] leading-[0.9] font-normal">{s.score}</b>
|
||||
<p className="relative m-0 font-jua text-[29px] leading-tight">
|
||||
{s.grade_label}
|
||||
{peak && ` · ${timeWords(peak.at)}이 절정`}
|
||||
</p>
|
||||
{times.length > 0 && (
|
||||
<div className="relative z-[1] mt-[18px]">
|
||||
<div className="h-2.5 rounded-full bg-[linear-gradient(90deg,#ffd27a,#ff7a6e_50%,#6a5bd6)]" />
|
||||
<div className="mt-1.5 flex justify-between text-[12.5px] font-extrabold">
|
||||
{times.map((t, i) => (
|
||||
<span key={t.kind} className={cx(i === 1 && 'text-center', i === times.length - 1 && i > 0 && 'text-right')}>
|
||||
<b className="block font-bagel text-lg font-normal">{clockShort(t.at)}</b>
|
||||
{t.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<StateBox loading={sky.isPending} error={sky.error} onRetry={() => sky.refetch()} empty="오늘 노을 정보가 없어요." />
|
||||
)}
|
||||
{times.length > 0 && (
|
||||
<>
|
||||
<Sec title="오늘의 노을 3컷" sub="옆으로 넘겨 보세요" />
|
||||
<Rail label="오늘의 노을 3컷">
|
||||
{times.map((t, i) => (
|
||||
<div key={t.kind} className={cx('b-skyline relative h-[150px] w-[230px] overflow-hidden rounded-[22px] px-3.5 py-2.5 font-bagel text-2xl text-white [--sky-h:30%]', `b-cut-${Math.min(i + 1, 3)}`)}>
|
||||
<span className="relative z-[1]">
|
||||
{clockShort(t.at)}
|
||||
<small className="block font-jua text-sm">{t.label}</small>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</Rail>
|
||||
</>
|
||||
)}
|
||||
<Sec title="가까운 노을 명소" sub={sky.data?.sunset_azimuth != null ? `해 지는 쪽 ${sky.data.sunset_azimuth}° · 서쪽이 트인 곳` : '서쪽이 트인 곳'} />
|
||||
{spots.length ? (
|
||||
<>
|
||||
<SpotMap region={region} spots={spots} azimuth={sky.data?.sunset_azimuth} />
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{spots.map((p) => (
|
||||
<Li key={p.no} no={p.no} title={p.name} sub={p.description} right={`${p.distance_km}km`} />
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<StateBox loading={sky.isPending} error={sky.error} empty="이 지역은 아직 등록된 노을 명소가 없어요." />
|
||||
)}
|
||||
<Sec title="전국 노을 순위" sub={items[0] ? `오늘 기준 · 1위 ${items[0].name} ${items[0].score}점` : '오늘 기준'} />
|
||||
{items.length ? (
|
||||
<ul className="mx-3 mt-1.5 flex flex-col">
|
||||
{items.map((r) => (
|
||||
<Li key={r.region_code} no={r.rank} title={r.name} sub={r.note} right={String(r.score)} meter={r.score} mine={r.region_code === region.code} />
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<StateBox loading={ranking.isPending} error={ranking.error} onRetry={() => ranking.refetch()} empty="순위가 아직 없어요." />
|
||||
)}
|
||||
{days.length > 0 && (
|
||||
<>
|
||||
<Sec title="앞으로 3일" />
|
||||
<div className="grid grid-cols-3 gap-2 p-3">
|
||||
{days.map((d, i) => (
|
||||
<div key={d.day} className="rounded-[20px] bg-white p-3 text-center shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<small className="text-[12.5px] font-extrabold text-(--ink2)">{dayLabel(d.day, i)}</small>
|
||||
<b className={cx('block font-bagel text-[30px] font-normal', d.score < 50 ? 'text-(--ink3)' : 'text-[#d6457a]')}>{d.score}</b>
|
||||
<span className="text-xs font-bold text-(--ink2)">{d.grade_label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import { Fragment, useEffect, useState, type ReactNode } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getFeedOptions, getWeatherTodayOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import type { BandArticle, BandEvent, Hero as HeroData, ResWeatherToday, TopIndex } from '../api/client/types.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, fall, kindOfHour, kst, MEDALS, sidoOf, WEEKDAYS, type TimeKind } from './lib'
|
||||
import { PostCard } from './Post'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Ic, Rail, Sec, StateBox } from './ui'
|
||||
import { deg, skyText, slotAt } from './weatherText'
|
||||
|
||||
type Mode = 'now' | TimeKind
|
||||
|
||||
const MODES: [Mode, string][] = [
|
||||
['now', '지금 시간'],
|
||||
['morning', '아침'],
|
||||
['day', '낮'],
|
||||
['sunset', '노을'],
|
||||
['night', '밤'],
|
||||
]
|
||||
|
||||
// 미리보기 시간대마다 보여 줄 시계와 그 시각의 예보 칸
|
||||
const PREVIEW: Record<TimeKind, { label: string; clock: string; hour: number }> = {
|
||||
morning: { label: '아침', clock: '07:40', hour: 7 },
|
||||
day: { label: '낮', clock: '13:20', hour: 13 },
|
||||
sunset: { label: '노을', clock: '18:25', hour: 18 },
|
||||
night: { label: '밤', clock: '22:10', hour: 22 },
|
||||
}
|
||||
|
||||
const STARS = Array.from({ length: 26 }, (_, i) => ({ left: `${(i * 37) % 100}%`, top: `${(i * 53) % 60}%`, opacity: 0.4 + ((i * 7) % 6) / 10 }))
|
||||
const ORB_POS = [
|
||||
{ left: '66%', top: '6px', d: '.5s', f: '4.4s' },
|
||||
{ left: '0%', top: '34px', d: '.7s', f: '5.1s' },
|
||||
{ left: '4%', top: '184px', d: '.9s', f: '4.7s' },
|
||||
]
|
||||
|
||||
function useNow(ms = 20000) {
|
||||
const [now, setNow] = useState(() => new Date())
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setNow(new Date()), ms)
|
||||
return () => clearInterval(id)
|
||||
}, [ms])
|
||||
return now
|
||||
}
|
||||
|
||||
type HeroProps = { hero?: HeroData | null; today?: ResWeatherToday }
|
||||
|
||||
function Hero({ hero, today }: HeroProps) {
|
||||
const { open } = useSheet()
|
||||
const [mode, setMode] = useState<Mode>('now')
|
||||
const clock = useNow()
|
||||
const t = kst(clock)
|
||||
const kind = mode === 'now' ? (hero?.sky_mode ?? kindOfHour(t.h)) : mode
|
||||
const slots = today?.slots ?? []
|
||||
const slot = slots.length ? slotAt(slots, mode === 'now' ? t.h : PREVIEW[mode].hour) : undefined
|
||||
// 지금은 /v1/feed hero 값을, 미리보기는 그 시각의 예보 칸을 쓴다
|
||||
const temp = mode === 'now' && hero ? hero.temp_c : slot?.temp_c
|
||||
const feels = mode === 'now' && hero ? hero.feels_c : slot?.feels_c
|
||||
const top3 = hero?.top3 ?? []
|
||||
const who = kind === 'night' ? 'bear' : 'rabbit'
|
||||
|
||||
return (
|
||||
<div className="b-hero relative mx-3 mt-1 overflow-hidden rounded-[32px] px-[18px] pt-4 pb-[18px]" data-t={kind}>
|
||||
<div className="b-stars pointer-events-none absolute inset-0" aria-hidden="true">
|
||||
{STARS.map((s, i) => (
|
||||
<i key={i} className="absolute size-[3px] rounded-full bg-white shadow-[0_0_6px_#fff]" style={s} />
|
||||
))}
|
||||
</div>
|
||||
<div className="relative z-[3] flex flex-wrap gap-1.5" role="group" aria-label="시간대 배경 미리보기">
|
||||
{MODES.map(([m, l]) => (
|
||||
<button key={m} type="button" aria-pressed={mode === m} onClick={() => setMode(m)} className={cx('cursor-pointer rounded-full px-2.5 py-[5px] text-xs font-bold', mode === m ? 'bg-(--ink) text-white' : 'bg-white/55 text-(--ink)')}>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="relative z-[3] mt-3 flex items-end justify-between">
|
||||
<div>
|
||||
<p className="mb-1 text-[13.5px] font-bold opacity-85">
|
||||
{t.mo}월 {t.d}일 {WEEKDAYS[t.wd]}요일 · {mode === 'now' ? '지금' : `${PREVIEW[mode].label} 미리보기`}
|
||||
</p>
|
||||
<div className="font-bagel text-[60px] leading-none">{mode === 'now' ? `${String(t.h).padStart(2, '0')}:${String(t.mi).padStart(2, '0')}` : PREVIEW[mode].clock}</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<b className="font-bagel text-[42px] leading-none font-normal">{temp != null ? deg(temp) : '--°'}</b>
|
||||
<span className="block text-[12.5px] font-bold opacity-85">{temp != null ? `체감 ${deg(feels)}${slot ? ` · ${skyText(slot)}` : ''}` : '날씨를 불러오는 중'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative z-[3] mt-3 grid grid-cols-2 gap-2.5">
|
||||
<div className="b-stat flex items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
|
||||
<Ic name="thermo" className="w-9" />
|
||||
<div>
|
||||
<small className="block text-xs font-bold opacity-80">불쾌지수</small>
|
||||
<b className="font-jua text-lg font-normal">{hero?.discomfort != null ? `${hero.discomfort} · ${hero.discomfort_label ?? ''}` : '-'}</b>
|
||||
</div>
|
||||
</div>
|
||||
<div className="b-stat flex items-center gap-2.5 rounded-[20px] px-3 py-[9px]">
|
||||
<Ic name="umbrella" className="w-9" />
|
||||
<div>
|
||||
<small className="block text-xs font-bold opacity-80">지금 비</small>
|
||||
<b className="font-jua text-lg font-normal">{hero?.will_rain_2h == null ? '-' : hero.will_rain_2h ? '2시간 안에 비' : '2시간 없음'}</b>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-5 h-[286px]">
|
||||
<span className="b-cloud b-fall top-6 left-[6%] h-[30px] w-[84px]" style={fall('.1s', '6s')} aria-hidden="true" />
|
||||
<div className="b-sun b-fall absolute top-10 left-1/2 -ml-[82px] grid aspect-square w-[164px] place-items-center rounded-full text-center" style={fall('0s', '5.6s', '8px')}>
|
||||
<span>
|
||||
<b className="block font-bagel text-[56px] leading-[0.9] font-normal">{hero?.weather_score ?? '-'}</b>
|
||||
<small className="mt-0.5 block font-jua text-[14.5px]">오늘 날씨 점수</small>
|
||||
</span>
|
||||
</div>
|
||||
<span className="b-cloud b-fall top-[188px] left-[54%] h-10 w-[118px]" style={fall('.25s', '6.4s')} aria-hidden="true" />
|
||||
{top3.map((g, i) => (
|
||||
<button
|
||||
key={g.index_id}
|
||||
type="button"
|
||||
onClick={() => open({ type: 'gak', indexId: g.index_id })}
|
||||
aria-label={`${i + 1}위 ${g.name} ${g.score}점, 계산 근거 보기`}
|
||||
className="b-fall absolute z-[2] flex w-24 cursor-pointer flex-col items-center"
|
||||
style={{ left: ORB_POS[i].left, top: ORB_POS[i].top, ...fall(ORB_POS[i].d, ORB_POS[i].f) }}
|
||||
>
|
||||
<span className={cx('relative', i === 0 ? 'w-[78px]' : 'w-[60px]')}>
|
||||
<Ic name={g.icon} className="w-full drop-shadow-[0_10px_12px_rgb(40_48_74/0.16)]" />
|
||||
<Ic name={MEDALS[i]} className="absolute -top-2 -left-3.5 w-[30px]" />
|
||||
</span>
|
||||
<span className="b-orb-label font-jua text-sm whitespace-nowrap">
|
||||
{i + 1}위 {g.name} <em className="font-bagel text-(--orange) not-italic">{g.score}</em>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{hero?.bubble && (
|
||||
<div className="relative z-[3] flex items-end gap-2">
|
||||
<Ic name={who} alt={who === 'rabbit' ? '토끼' : '곰'} className="w-[50px] drop-shadow-[0_8px_10px_rgb(40_48_74/0.15)]" />
|
||||
<span className="mb-3 rounded-[20px_20px_20px_6px] bg-white px-3.5 py-[9px] font-jua text-base text-(--ink) shadow-[0_8px_16px_rgb(40_48_74/0.1)]">{hero.bubble}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Stories({ items }: { items: TopIndex[] }) {
|
||||
const { open } = useSheet()
|
||||
return (
|
||||
<Rail label="오늘의 각 순위">
|
||||
{items.map((g, i) => (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} aria-label={`${g.rank}위 ${g.name} ${g.score}점`} className="flex w-[72px] cursor-pointer flex-col items-center gap-1">
|
||||
<span className={cx('relative size-[68px] rounded-full p-[3px]', g.score < 50 ? 'bg-[#d6deea]' : 'b-ring')}>
|
||||
<i className="grid size-full place-items-center rounded-full border-[3px] border-(--page) bg-(--page)">
|
||||
<Ic name={g.icon} className="w-[42px]" />
|
||||
</i>
|
||||
{i < 3 && <Ic name={MEDALS[i]} className="absolute -right-1 -bottom-1 w-[25px]" />}
|
||||
</span>
|
||||
<b className="font-jua text-[13px] font-normal whitespace-nowrap">{g.name}</b>
|
||||
<em className="font-bagel text-[12.5px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||
</button>
|
||||
))}
|
||||
</Rail>
|
||||
)
|
||||
}
|
||||
|
||||
function Band({ tone, title, sub, to, children }: { tone: 1 | 2 | 3; title: string; sub: string; to: string; children: ReactNode }) {
|
||||
return (
|
||||
<section className={cx('mt-3.5 pt-4 pb-3.5', `b-band-${tone}`)} aria-label={title}>
|
||||
<Sec title={title} sub={sub} more={{ to }} className="pt-0" />
|
||||
{children}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function EventsBand({ events }: { events: BandEvent[] }) {
|
||||
const { region } = useRegion()
|
||||
return (
|
||||
<Band tone={1} title={`이번 주 ${sidoOf(region.name)} 행사`} sub="날씨까지 같이 보고 골라요" to="/week">
|
||||
<Rail>
|
||||
{events.map((e, i) => (
|
||||
<Link key={e.event_id} to="/week" className="w-[200px] overflow-hidden rounded-[22px] bg-white shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<span className={cx('relative grid h-[116px] place-items-center', `b-bg-${cardBg(e.icon, i)}`)}>
|
||||
<span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', e.status_label === '진행 중' ? 'bg-[#1f9d62]' : 'bg-(--orange)')}>{e.status_label}</span>
|
||||
<Ic name={e.icon} className="w-[76px]" />
|
||||
</span>
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<b className="block font-jua text-[16.5px] leading-snug font-normal">{e.name}</b>
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</Rail>
|
||||
</Band>
|
||||
)
|
||||
}
|
||||
|
||||
function TopBand({ items, sub }: { items: TopIndex[]; sub: string }) {
|
||||
const { open } = useSheet()
|
||||
return (
|
||||
<Band tone={2} title="지금 뜨는 각 TOP 5" sub={sub} to="/gak">
|
||||
<Rail>
|
||||
{items.slice(0, 5).map((g, i) => (
|
||||
<button key={g.index_id} type="button" onClick={() => open({ type: 'gak', indexId: g.index_id })} className="relative flex w-[138px] cursor-pointer flex-col items-start gap-1 rounded-[22px] bg-white p-3 text-left shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
{i < 3 ? <Ic name={MEDALS[i]} alt={`${i + 1}위`} className="absolute top-2 left-2 w-[26px]" /> : <span className="absolute top-2.5 left-3 font-jua text-(--ink3)">{i + 1}위</span>}
|
||||
<Ic name={g.icon} className="w-[58px] self-center" />
|
||||
<b className="font-jua text-base font-normal">{g.name}</b>
|
||||
<em className="font-bagel text-[22px] leading-none text-(--orange) not-italic">{g.score}</em>
|
||||
{g.summary && <small className="text-xs font-semibold text-(--ink2)">{g.summary}</small>}
|
||||
</button>
|
||||
))}
|
||||
</Rail>
|
||||
</Band>
|
||||
)
|
||||
}
|
||||
|
||||
function SeasonBand({ news }: { news: BandArticle[] }) {
|
||||
const { open } = useSheet()
|
||||
return (
|
||||
<Band tone={3} title="이번 주 계절 이야기" sub="예년 이맘때의 소식" to="/season">
|
||||
<Rail>
|
||||
{news.map((a) => (
|
||||
<button key={a.article_id} type="button" onClick={() => open({ type: 'article', articleId: a.article_id })} className="w-[200px] cursor-pointer overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<span className={cx('grid h-[116px] place-items-center', `b-bg-${cardBg(a.icon, a.article_id)}`)}>
|
||||
<Ic name={a.icon} className="w-[76px]" />
|
||||
</span>
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<b className="block font-jua text-[16.5px] leading-snug font-normal">{a.title}</b>
|
||||
<small className="text-[12.5px] font-semibold text-(--ink2)">{a.meta}</small>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</Rail>
|
||||
</Band>
|
||||
)
|
||||
}
|
||||
|
||||
export function TodayPage() {
|
||||
const { region } = useRegion()
|
||||
const feed = useQuery(getFeedOptions({ query: { region: region.code } }))
|
||||
const today = useQuery(getWeatherTodayOptions({ query: { region: region.code } }))
|
||||
const f = feed.data
|
||||
const posts = f?.posts ?? []
|
||||
const stories = f?.stories ?? []
|
||||
const bands = f?.bands
|
||||
const nowAt = f?.hero?.now_at
|
||||
|
||||
// 디자인대로 3·6·9번째 글 뒤에 띠를 넣고, 글이 모자라면 남은 띠는 맨 뒤에 붙인다
|
||||
const bandAt: [number, ReactNode][] = [
|
||||
[3, bands?.events?.length ? <EventsBand key="events" events={bands.events} /> : null],
|
||||
[6, bands?.top5?.length ? <TopBand key="top5" items={bands.top5} sub={nowAt ? `${kst(nowAt).h}시 기준` : '오늘 기준'} /> : null],
|
||||
[9, bands?.season?.length ? <SeasonBand key="season" news={bands.season} /> : null],
|
||||
]
|
||||
|
||||
return (
|
||||
<section aria-label="오늘">
|
||||
<Hero hero={f?.hero} today={today.data} />
|
||||
<Sec title="오늘의 각" sub="누르면 계산 근거를 보여 줘요" more={{ to: '/gak' }} />
|
||||
{stories.length ? <Stories items={stories} /> : <StateBox loading={feed.isPending} error={feed.error} onRetry={() => feed.refetch()} empty="오늘 계산된 각이 없어요." />}
|
||||
<StateBox loading={feed.isPending} error={feed.error} onRetry={() => feed.refetch()} empty={feed.isSuccess && !posts.length ? '오늘 올라온 글이 아직 없어요.' : undefined} />
|
||||
<div>
|
||||
{posts.map((p, i) => (
|
||||
<Fragment key={p.post_id}>
|
||||
<PostCard key={`${p.post_id}-${p.liked}-${p.saved}-${p.like_count}`} post={p} />
|
||||
{bandAt.find(([at]) => at === i + 1)?.[1]}
|
||||
</Fragment>
|
||||
))}
|
||||
{feed.isSuccess && bandAt.filter(([at]) => at > posts.length).map(([at, node]) => <Fragment key={at}>{node}</Fragment>)}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getWeekOptions, listEventsOptions, listPlacesOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { cx } from '../lib/utils'
|
||||
import { cardBg, dateRange, sidoOf } from './lib'
|
||||
import { useRegion } from './regionContext'
|
||||
import { useSheet } from './sheetContext'
|
||||
import { Ic, Rail, Sec, StateBox } from './ui'
|
||||
|
||||
const PLACE_BG: Record<string, string> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', bulb: 'lilac' }
|
||||
|
||||
export function WeekPage() {
|
||||
const { region } = useRegion()
|
||||
const { open } = useSheet()
|
||||
const week = useQuery(getWeekOptions({ query: { region: region.code } }))
|
||||
const days = week.data?.days ?? []
|
||||
const [picked, setPicked] = useState<string | null>(null)
|
||||
// 지역을 바꾸면 동네 고르기는 전체로 돌아간다
|
||||
const [areaPick, setAreaPick] = useState({ region: region.code, area: '전체' })
|
||||
const area = areaPick.region === region.code ? areaPick.area : '전체'
|
||||
// 처음에는 이번 토요일을 고른다
|
||||
const sel = days.find((d) => d.day === picked) ?? days.find((d) => d.weekday === '토') ?? days[0]
|
||||
const places = useQuery({ ...listPlacesOptions({ query: { region: region.code, day: sel?.day, area: area === '전체' ? undefined : area } }), enabled: !!sel })
|
||||
const events = useQuery(listEventsOptions({ query: { region: region.code } }))
|
||||
const sido = sidoOf(region.name)
|
||||
const areas = places.data?.areas ?? []
|
||||
const rainy = places.data?.rainy ?? sel?.is_rainy
|
||||
const placeList = places.data?.places ?? []
|
||||
const eventList = events.data?.events ?? []
|
||||
|
||||
const sendPlan = () => {
|
||||
if (!sel) return
|
||||
open({ type: 'share', share: { title: `${sel.weekday}요일 일정`, icon: 'calendar', bg: 'mint', messages: [`${sel.weekday}요일 이렇게 놀자! ${sel.pick} 😆`, '이번 주말 같이 놀자 🙌'] } })
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-label="주말·행사">
|
||||
<Sec title="이번 주 날씨" sub="날짜를 누르면 그날 추천이 바뀌어요" />
|
||||
{days.length ? (
|
||||
<div className="grid grid-cols-7 gap-1 px-3 pt-3" role="group" aria-label="날짜 고르기">
|
||||
{days.map((d) => {
|
||||
const on = d.day === sel?.day
|
||||
const weekend = d.weekday === '토' || d.weekday === '일' || !!d.holiday
|
||||
return (
|
||||
<button
|
||||
key={d.day}
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
onClick={() => setPicked(d.day)}
|
||||
className={cx('flex cursor-pointer flex-col items-center gap-0.5 rounded-[18px] pt-[9px] pb-2 text-xs font-extrabold', on ? 'bg-(--ink) text-white' : cx('bg-white shadow-[inset_0_-4px_0_var(--shade)]', weekend ? 'text-[#d6457a]' : 'text-(--ink2)'))}
|
||||
>
|
||||
<span>{d.weekday}</span>
|
||||
<Ic name={d.icon} className="w-7" />
|
||||
<b className={cx('font-jua text-sm font-normal', on ? 'text-white' : 'text-(--ink)')}>{d.temp_max_c != null ? `${Math.round(d.temp_max_c)}°` : '-'}</b>
|
||||
<span className={cx('max-w-full truncate px-0.5 text-[9.5px]', on ? 'text-[#ffb3c4]' : 'text-[#d6457a]')}>{d.holiday ? d.holiday.replace(/\(.*\)/, '') : `${Number(d.day.slice(8))}일`}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<StateBox loading={week.isPending} error={week.error} onRetry={() => week.refetch()} empty="이번 주 날씨가 아직 없어요." />
|
||||
)}
|
||||
{sel && (
|
||||
<div className="mx-3 mt-3 flex items-center gap-3.5 rounded-3xl bg-[linear-gradient(180deg,#e9fbf2,#fff)] p-4 shadow-[inset_0_-5px_0_var(--shade)]" aria-live="polite">
|
||||
<Ic name={sel.icon} className="w-16" />
|
||||
<div>
|
||||
<b className="block font-jua text-[19px] font-normal">{sel.headline}</b>
|
||||
<p className="mt-0.5 text-[13.5px] font-semibold text-(--ink2)">{sel.summary}</p>
|
||||
<p className="mt-2 font-jua text-base text-(--ink)">추천: {sel.pick}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{areas.length > 0 && (
|
||||
<div className="mx-3 mt-3.5 flex items-center justify-between">
|
||||
<label htmlFor="b-area" className="text-[13.5px] font-bold text-(--ink2)">
|
||||
{sido} · 데이트 명소
|
||||
</label>
|
||||
<select id="b-area" value={area} onChange={(e) => setAreaPick({ region: region.code, area: e.target.value })} className="rounded-full bg-white px-3 py-[7px] font-bold text-(--ink) shadow-[inset_0_-3px_0_var(--shade)]">
|
||||
{['전체', ...areas].map((a) => (
|
||||
<option key={a}>{a}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
<Sec title="날씨 맞춤 데이트 명소" sub={sel ? `${sel.weekday}요일은 ${rainy ? '비가 와서 실내 명소를 먼저' : '맑아서 야외 명소를 먼저'} 보여 줘요` : undefined} className="pt-3" />
|
||||
{placeList.length ? (
|
||||
<Rail>
|
||||
{placeList.map((p, i) => (
|
||||
<div key={p.place_id} className="w-[178px] overflow-hidden rounded-[22px] bg-white text-left shadow-[inset_0_-5px_0_var(--shade),0_8px_16px_rgb(40_48_74/0.06)]">
|
||||
<span className={cx('relative grid h-[104px] place-items-center', `b-bg-${PLACE_BG[p.icon] ?? (p.is_outdoor ? 'mint' : cardBg(p.icon, i))}`)}>
|
||||
{p.is_good && <span className={cx('absolute top-2.5 left-2.5 rounded-full px-2 py-[3px] text-[11.5px] font-extrabold text-white', p.is_outdoor ? 'bg-[#1f9d62]' : 'bg-(--rain)')}>{p.is_outdoor ? '오늘 딱' : '비 와도 OK'}</span>}
|
||||
<Ic name={p.icon} className="w-[62px]" />
|
||||
</span>
|
||||
<span className="block px-3 pt-2.5 pb-3">
|
||||
<span className="text-[11.5px] font-extrabold text-(--ink3)">
|
||||
{p.area} · {p.is_outdoor ? '야외' : '실내'}
|
||||
</span>
|
||||
<b className="block font-jua text-[16.5px] font-normal">{p.name}</b>
|
||||
<small className="block text-[12.5px] leading-snug font-semibold text-(--ink2)">
|
||||
{p.reason}
|
||||
<br />
|
||||
추천 {p.best_time}
|
||||
</small>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</Rail>
|
||||
) : (
|
||||
<StateBox loading={places.isPending && !!sel} error={places.error} onRetry={() => places.refetch()} empty={`${sido} 데이트 명소는 아직 준비 중이에요.`} />
|
||||
)}
|
||||
<Sec title={`${sido} 축제·행사`} sub="앞으로 30일 · 그날 날씨까지 같이 봐요" className="pt-[18px]" />
|
||||
{eventList.length ? (
|
||||
eventList.map((e, i) => (
|
||||
<div key={e.event_id} className="mx-3 mt-2.5 grid grid-cols-[84px_1fr] items-center gap-3 rounded-[22px] bg-white p-3 shadow-[inset_0_-5px_0_var(--shade)]">
|
||||
<span className={cx('grid h-[84px] place-items-center rounded-2xl', `b-bg-${cardBg(e.icon, i)}`)}>
|
||||
<Ic name={e.icon} className="w-14" />
|
||||
</span>
|
||||
<span>
|
||||
<span className={cx('mr-1.5 inline-block rounded-full px-[7px] py-0.5 align-[2px] text-[11px] font-extrabold', e.status === 'live' ? 'bg-[#dff5ea] text-[#1f7a4f]' : 'bg-[#ffe8dc] text-[#c2471b]')}>{e.status_label}</span>
|
||||
<b className="inline font-jua text-[17px] leading-snug font-normal">{e.name}</b>
|
||||
<small className="block text-[12.5px] font-semibold text-(--ink2)">
|
||||
{dateRange(e.start_date, e.end_date)} · {e.place_name}
|
||||
{!e.is_confirmed && ' · 일정 확인 필요'}
|
||||
</small>
|
||||
{e.fit && <span className={cx('mt-[5px] inline-block text-xs font-extrabold', e.fit.includes('비') ? 'text-[#d6457a]' : 'text-[#1f9d62]')}>{e.fit}</span>}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<StateBox loading={events.isPending} error={events.error} onRetry={() => events.refetch()} empty="이 지역 행사는 아직 없어요. 다른 지역을 골라 보세요." />
|
||||
)}
|
||||
<button type="button" onClick={sendPlan} disabled={!sel} className="mx-3 mt-4 block w-[calc(100%-24px)] cursor-pointer rounded-full bg-(--orange) p-[13px] font-jua text-[17px] text-white shadow-[inset_0_-5px_0_var(--orange-deep)] disabled:opacity-60">
|
||||
이번 주말 일정 보내기
|
||||
</button>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo, useSyncExternalStore, type ReactNode } from 'react'
|
||||
import { clearTokens, getAccessToken, subscribeAuth } from '../api/auth'
|
||||
import { meOptions } from '../api/client/@tanstack/react-query.gen'
|
||||
import { AuthContext } from './authContext'
|
||||
|
||||
const subscribe = (cb: () => void) => subscribeAuth((reason) => reason === 'change' && cb())
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const token = useSyncExternalStore(subscribe, getAccessToken)
|
||||
const queryClient = useQueryClient()
|
||||
const me = useQuery({ ...meOptions(), enabled: !!token })
|
||||
|
||||
// 로그인·로그아웃하면 좋아요·저장 여부가 달라지니 받아 둔 데이터를 다시 받는다
|
||||
useEffect(() => subscribeAuth((reason) => reason === 'change' && queryClient.invalidateQueries()), [queryClient])
|
||||
|
||||
const api = useMemo(() => ({ loggedIn: !!token, me: (token && me.data?.me) || null, logout: clearTokens }), [token, me.data])
|
||||
return <AuthContext value={api}>{children}</AuthContext>
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { createContext, use } from 'react'
|
||||
import type { Me } from '../api/client/types.gen'
|
||||
|
||||
export type AuthApi = { loggedIn: boolean; me: Me | null; logout: () => void }
|
||||
|
||||
export const AuthContext = createContext<AuthApi | null>(null)
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = use(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth must be used inside AuthProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
/* 시안 B 피드: 말랑한 3D 토큰과 Tailwind로 쓰기 어려운 그라데이션·애니메이션 */
|
||||
.b-app {
|
||||
--ink: #28304a;
|
||||
--ink2: #5a6380;
|
||||
--ink3: #8a92aa;
|
||||
--line: #e6ecf4;
|
||||
--page: #f7fbff;
|
||||
--outer: #dfeaf6;
|
||||
--shade: #d9e5f4;
|
||||
--orange: #ff7a45;
|
||||
--orange-deep: #d4552a;
|
||||
--rain: #4f97e3;
|
||||
--heart: #ff3b5c;
|
||||
font-size: 15px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.b-app :focus-visible {
|
||||
outline: 3px solid var(--rain);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.b-noscroll {
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.b-noscroll::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* 하늘에서 떨어진 뒤 둥둥 */
|
||||
.b-fall {
|
||||
animation:
|
||||
b-drop 1.05s cubic-bezier(0.22, 0.9, 0.3, 1) var(--d, 0s) both,
|
||||
b-float var(--f, 4.8s) ease-in-out calc(var(--d, 0s) + 1.05s) infinite;
|
||||
}
|
||||
@keyframes b-drop {
|
||||
0% {
|
||||
transform: translateY(-60vh) rotate(-10deg);
|
||||
opacity: 0;
|
||||
}
|
||||
55% {
|
||||
opacity: 1;
|
||||
}
|
||||
72% {
|
||||
transform: translateY(0) rotate(2deg) scale(1.04, 0.96);
|
||||
}
|
||||
86% {
|
||||
transform: translateY(-10px);
|
||||
}
|
||||
100% {
|
||||
transform: none;
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes b-float {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(calc(var(--amp, 9px) * -1)) rotate(var(--tilt, 1.2deg));
|
||||
}
|
||||
}
|
||||
|
||||
.b-heart-pop {
|
||||
animation: b-hpop 0.8s ease-out;
|
||||
}
|
||||
@keyframes b-hpop {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: scale(0.3);
|
||||
}
|
||||
25% {
|
||||
opacity: 1;
|
||||
transform: scale(1.1);
|
||||
}
|
||||
60% {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.b-sheet {
|
||||
animation: b-up 0.26s cubic-bezier(0.2, 0.9, 0.3, 1);
|
||||
}
|
||||
@keyframes b-up {
|
||||
from {
|
||||
transform: translateY(40px);
|
||||
opacity: 0.4;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.b-fall,
|
||||
.b-heart-pop,
|
||||
.b-sheet {
|
||||
animation: none !important;
|
||||
}
|
||||
.b-heart-pop {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* 히어로 시간대 배경 */
|
||||
.b-hero {
|
||||
transition: background 0.6s;
|
||||
}
|
||||
.b-hero[data-t='morning'] {
|
||||
background: linear-gradient(180deg, #ffd9b8, #ffe9d4 40%, #dff0ff);
|
||||
}
|
||||
.b-hero[data-t='day'] {
|
||||
background: linear-gradient(180deg, #9fd3ff, #cfe9ff 55%, #f1f8ff);
|
||||
}
|
||||
.b-hero[data-t='sunset'] {
|
||||
background: linear-gradient(180deg, #8e7cf0, #f28aa0 48%, #ffc38a);
|
||||
color: #fff;
|
||||
}
|
||||
.b-hero[data-t='night'] {
|
||||
background: linear-gradient(180deg, #141b3d, #27306a 60%, #3d3f86);
|
||||
color: #fff;
|
||||
}
|
||||
.b-hero .b-stars {
|
||||
opacity: 0;
|
||||
transition: opacity 0.6s;
|
||||
}
|
||||
.b-hero[data-t='night'] .b-stars {
|
||||
opacity: 1;
|
||||
}
|
||||
.b-stat {
|
||||
background: rgb(255 255 255 / 0.72);
|
||||
color: var(--ink);
|
||||
box-shadow: inset 0 -5px 0 rgb(217 229 244 / 0.9);
|
||||
}
|
||||
.b-hero[data-t='night'] .b-stat,
|
||||
.b-hero[data-t='sunset'] .b-stat {
|
||||
background: rgb(255 255 255 / 0.18);
|
||||
color: #fff;
|
||||
box-shadow: inset 0 -5px 0 rgb(255 255 255 / 0.12);
|
||||
}
|
||||
.b-orb-label {
|
||||
text-shadow: 0 2px 0 rgb(255 255 255 / 0.7);
|
||||
}
|
||||
.b-hero[data-t='night'] .b-orb-label,
|
||||
.b-hero[data-t='sunset'] .b-orb-label {
|
||||
text-shadow: 0 2px 0 rgb(0 0 0 / 0.2);
|
||||
}
|
||||
|
||||
.b-sun {
|
||||
background: radial-gradient(circle at 34% 30%, #fff5cf, #ffc86e 30%, #ff8e4e 68%, #ee6436);
|
||||
box-shadow:
|
||||
inset -18px -24px 40px rgb(170 50 20 / 0.34),
|
||||
inset 16px 18px 28px rgb(255 255 255 / 0.55),
|
||||
0 30px 56px rgb(240 106 58 / 0.32);
|
||||
color: #fff;
|
||||
}
|
||||
.b-hero[data-t='night'] .b-sun {
|
||||
background: radial-gradient(circle at 34% 30%, #fff, #e7e3ff 35%, #b9b0f2 72%, #8f86d9);
|
||||
color: #2b2a5c;
|
||||
box-shadow:
|
||||
inset -18px -24px 40px rgb(60 50 140 / 0.3),
|
||||
inset 16px 18px 28px rgb(255 255 255 / 0.6),
|
||||
0 0 60px rgb(190 180 255 / 0.45);
|
||||
}
|
||||
|
||||
.b-cloud {
|
||||
position: absolute;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
box-shadow:
|
||||
inset 0 -12px 18px rgb(160 190 230 / 0.45),
|
||||
0 16px 28px rgb(40 70 120 / 0.13);
|
||||
}
|
||||
.b-cloud::before,
|
||||
.b-cloud::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
border-radius: 999px;
|
||||
background: #fff;
|
||||
box-shadow: inset 0 -10px 16px rgb(160 190 230 / 0.35);
|
||||
}
|
||||
.b-cloud::before {
|
||||
left: 16%;
|
||||
top: -58%;
|
||||
width: 46%;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
.b-cloud::after {
|
||||
left: 50%;
|
||||
top: -36%;
|
||||
width: 36%;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
.b-hero[data-t='night'] .b-cloud,
|
||||
.b-hero[data-t='night'] .b-cloud::before,
|
||||
.b-hero[data-t='night'] .b-cloud::after {
|
||||
background: #c9cdf0;
|
||||
}
|
||||
|
||||
/* 이야기 고리 */
|
||||
.b-ring {
|
||||
background: conic-gradient(var(--orange), #ffc86e, #8fcaff, var(--orange));
|
||||
}
|
||||
|
||||
/* 슬라이드·카드 배경 */
|
||||
.b-bg-sky {
|
||||
background: linear-gradient(180deg, #bfe3ff, #eef7ff);
|
||||
}
|
||||
.b-bg-butter {
|
||||
background: linear-gradient(180deg, #ffe7a0, #fff6d8);
|
||||
}
|
||||
.b-bg-peach {
|
||||
background: linear-gradient(180deg, #ffd2bb, #fff2ea);
|
||||
}
|
||||
.b-bg-mint {
|
||||
background: linear-gradient(180deg, #bfecd6, #effaf4);
|
||||
}
|
||||
.b-bg-lilac {
|
||||
background: linear-gradient(180deg, #d8cffc, #f4f1ff);
|
||||
}
|
||||
.b-bg-dusk {
|
||||
background: linear-gradient(180deg, #7e6fe6, #f08aa2 60%, #ffc28a);
|
||||
color: #fff;
|
||||
}
|
||||
.b-bg-night {
|
||||
background: linear-gradient(180deg, #1f2658, #3d3f86);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
/* 건물 실루엣 */
|
||||
.b-skyline::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: auto 0 0 0;
|
||||
height: var(--sky-h, 32%);
|
||||
background: #2d2440;
|
||||
clip-path: polygon(0 55%, 8% 55%, 8% 30%, 15% 30%, 15% 50%, 22% 50%, 22% 10%, 28% 10%, 28% 45%, 36% 45%, 36% 25%, 44% 25%, 44% 55%, 52% 55%, 52% 35%, 60% 35%, 60% 5%, 66% 5%, 66% 40%, 74% 40%, 74% 20%, 82% 20%, 82% 50%, 90% 50%, 90% 30%, 100% 30%, 100% 100%, 0 100%);
|
||||
}
|
||||
.b-cut-1 {
|
||||
background: linear-gradient(#9fd0ff, #ffd79a 60%, #ff9a5c);
|
||||
}
|
||||
.b-cut-2 {
|
||||
background: linear-gradient(#8f7cf0, #ff6f8e 55%, #ff8a4c);
|
||||
}
|
||||
.b-cut-3 {
|
||||
background: linear-gradient(#34306e, #7a5cc8);
|
||||
}
|
||||
|
||||
/* 각 줄 사이 가로 띠 */
|
||||
.b-band-1 {
|
||||
background: linear-gradient(180deg, #fff4ec, #f7fbff);
|
||||
}
|
||||
.b-band-2 {
|
||||
background: linear-gradient(180deg, #fff6d8, #f7fbff);
|
||||
}
|
||||
.b-band-3 {
|
||||
background: linear-gradient(180deg, #e9fbf2, #f7fbff);
|
||||
}
|
||||
|
||||
.b-sheet-dialog::backdrop {
|
||||
background: rgb(20 26 45 / 0.45);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
const SHARED = new Set(['bear', 'bike', 'bronze', 'camping', 'carwash', 'chimaek', 'cloud', 'coldwind', 'delivery', 'dog', 'garden', 'glasses', 'gold', 'hiking', 'iced_hot', 'jjamppong', 'laundry', 'letter', 'makeup', 'makgeolli', 'maple', 'moon', 'muggy', 'naengmyeon', 'photo', 'picnic', 'rabbit', 'rain', 'running', 'silver', 'snow', 'stars', 'sun_cloud', 'sun', 'sunset', 'taxi', 'umbrella', 'vent', 'walk', 'yajang'])
|
||||
const OWN = new Set(['fireworks', 'bulb', 'calendar', 'thermo', 'sheaf'])
|
||||
|
||||
/** 아이콘 이름 → 파일 경로 (공용 public/icons, B 전용 public/b/icons) */
|
||||
export function iconSrc(name: string) {
|
||||
if (OWN.has(name)) return `/b/icons/${name}.png`
|
||||
return `/icons/${SHARED.has(name) ? name : 'sun_cloud'}.png`
|
||||
}
|
||||
|
||||
export const MEDALS = ['gold', 'silver', 'bronze'] as const
|
||||
|
||||
export const fall = (d: string, f = '4.8s', amp?: string) => ({ '--d': d, '--f': f, ...(amp ? { '--amp': amp } : {}) }) as CSSProperties
|
||||
|
||||
export const WEEKDAYS = ['일', '월', '화', '수', '목', '금', '토'] as const
|
||||
|
||||
const KST = new Intl.DateTimeFormat('en-US', { timeZone: 'Asia/Seoul', year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23', weekday: 'short' })
|
||||
const WD_EN = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
||||
|
||||
/** 한국 시각으로 쪼개기 (브라우저 시간대와 상관없이) */
|
||||
export function kst(input: string | Date) {
|
||||
const parts = Object.fromEntries(KST.formatToParts(typeof input === 'string' ? new Date(input) : input).map((p) => [p.type, p.value]))
|
||||
return { y: +parts.year, mo: +parts.month, d: +parts.day, h: +parts.hour, mi: +parts.minute, wd: WD_EN.indexOf(parts.weekday) }
|
||||
}
|
||||
|
||||
const h12 = (h: number) => h % 12 || 12
|
||||
|
||||
/** 18:25 → "6:25" */
|
||||
export function clockShort(iso: string) {
|
||||
const t = kst(iso)
|
||||
return `${h12(t.h)}:${String(t.mi).padStart(2, '0')}`
|
||||
}
|
||||
|
||||
/** 18:30 → "6시 반", 18:25 → "6시 25분" */
|
||||
export function timeWords(iso: string) {
|
||||
const t = kst(iso)
|
||||
return `${h12(t.h)}시${t.mi === 0 ? '' : t.mi === 30 ? ' 반' : ` ${t.mi}분`}`
|
||||
}
|
||||
|
||||
/** 발표 시각 → "방금" · "12분 전" · "3시간 전" */
|
||||
export function ago(iso: string | null | undefined, now = Date.now()) {
|
||||
if (!iso) return '오늘'
|
||||
const min = Math.max(0, Math.round((now - new Date(iso).getTime()) / 60000))
|
||||
if (min < 5) return '방금'
|
||||
if (min < 60) return `${min}분 전`
|
||||
return `${Math.floor(min / 60)}시간 전`
|
||||
}
|
||||
|
||||
/** 날짜 칸 이름: 오늘 · 내일 · "토 10.4" */
|
||||
export function dayLabel(date: string, index: number) {
|
||||
if (index === 0) return '오늘'
|
||||
if (index === 1) return '내일'
|
||||
const [, m, d] = date.split('-').map(Number)
|
||||
const wd = new Date(`${date}T12:00:00+09:00`).getUTCDay()
|
||||
return `${WEEKDAYS[wd]} ${m}.${d}`
|
||||
}
|
||||
|
||||
export type TimeKind = 'morning' | 'day' | 'sunset' | 'night'
|
||||
|
||||
export function kindOfHour(h: number): TimeKind {
|
||||
if (h >= 5 && h < 9) return 'morning'
|
||||
if (h >= 9 && h < 16) return 'day'
|
||||
if (h >= 16 && h < 19) return 'sunset'
|
||||
return 'night'
|
||||
}
|
||||
|
||||
/** "서울 마포구" → "서울" */
|
||||
export const sidoOf = (regionName: string) => regionName.split(' ')[0]
|
||||
|
||||
/** 2026-10-02 ~ 2026-10-11 → "10.2 ~ 10.11", 하루짜리는 "10.3" */
|
||||
export function dateRange(start: string, end: string) {
|
||||
return start === end ? shortDay(start) : `${shortDay(start)} ~ ${shortDay(end)}`
|
||||
}
|
||||
|
||||
const CARD_BG = ['night', 'butter', 'lilac', 'mint', 'peach', 'sky'] as const
|
||||
const ICON_BG: Record<string, (typeof CARD_BG)[number] | 'dusk'> = { picnic: 'mint', walk: 'mint', sunset: 'dusk', chimaek: 'peach', photo: 'butter', fireworks: 'night', sheaf: 'butter', rain: 'sky', calendar: 'sky', bulb: 'lilac', maple: 'peach', snow: 'sky', thermo: 'sky', umbrella: 'lilac' }
|
||||
|
||||
/** API에 배경색이 없어 아이콘·순서로 카드 배경을 고른다 */
|
||||
export function cardBg(icon: string, index: number) {
|
||||
return ICON_BG[icon] && icon !== 'calendar' ? ICON_BG[icon] : CARD_BG[index % CARD_BG.length]
|
||||
}
|
||||
|
||||
/** "2026-09-23" → "9.23" */
|
||||
export const shortDay = (day: string) => day.split('-').slice(1).map(Number).join('.')
|
||||
|
||||
export const ARTICLE_CAT: Record<number, [string, string]> = { 1: ['계절 소식', 'text-[#1f9d62]'], 2: ['날씨 상식', 'text-[#7a5cd6]'], 3: ['각 원리', 'text-(--orange)'] }
|
||||
|
||||
/** 읽을거리 한 줄 정보: "계절 소식 · 3분" */
|
||||
export const articleMeta = (a: { category: number; read_minutes: number }) => `${ARTICLE_CAT[a.category]?.[0] ?? '읽을거리'} · ${a.read_minutes}분`
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'
|
||||
import { nearestRegion } from '../api/client/sdk.gen'
|
||||
import type { RegionData } from '../api/client/types.gen'
|
||||
import { DEFAULT_REGION, RegionContext, type LocateStatus } from './regionContext'
|
||||
|
||||
const KEY = 'nalssigak.b.region'
|
||||
|
||||
function readStored(): RegionData | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(KEY)
|
||||
return raw ? (JSON.parse(raw) as RegionData) : null
|
||||
} catch {
|
||||
// 사파리 프라이빗 모드 등에서는 저장소를 못 쓴다 → 기본 구로 시작
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeStored(r: RegionData) {
|
||||
try {
|
||||
localStorage.setItem(KEY, JSON.stringify(r))
|
||||
} catch {
|
||||
// 저장이 막혀도 이번 방문 동안은 메모리 값으로 계속 쓴다
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
export function RegionProvider({ children }: { children: ReactNode }) {
|
||||
const [stored] = useState(readStored)
|
||||
const [region, setRegionState] = useState<RegionData>(stored ?? DEFAULT_REGION)
|
||||
const canLocate = typeof navigator !== 'undefined' && 'geolocation' in navigator
|
||||
const [locateStatus, setLocateStatus] = useState<LocateStatus>(!stored && canLocate ? 'locating' : 'idle')
|
||||
|
||||
const setRegion = useCallback((r: RegionData) => {
|
||||
setRegionState(r)
|
||||
writeStored(r)
|
||||
}, [])
|
||||
|
||||
const findNearest = useCallback(() => {
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(pos) => {
|
||||
nearestRegion({ query: { lat: pos.coords.latitude, lon: pos.coords.longitude } })
|
||||
.then(({ data: res }) => {
|
||||
if (!res.region) throw new Error('가까운 구를 찾지 못함')
|
||||
setRegion(res.region)
|
||||
setLocateStatus('idle')
|
||||
})
|
||||
.catch(() => setLocateStatus('error'))
|
||||
},
|
||||
(err) => setLocateStatus(err.code === err.PERMISSION_DENIED ? 'denied' : 'error'),
|
||||
{ timeout: 10000, maximumAge: 600000 },
|
||||
)
|
||||
}, [setRegion])
|
||||
|
||||
const locate = useCallback(() => {
|
||||
if (!canLocate) {
|
||||
setLocateStatus('error')
|
||||
return
|
||||
}
|
||||
setLocateStatus('locating')
|
||||
findNearest()
|
||||
}, [canLocate, findNearest])
|
||||
|
||||
// 처음 온 사람만 위치 권한을 물어 가장 가까운 구로 맞춘다
|
||||
useEffect(() => {
|
||||
if (!stored && canLocate) findNearest()
|
||||
}, [stored, canLocate, findNearest])
|
||||
|
||||
const api = useMemo(() => ({ region, setRegion, locate, locateStatus }), [region, setRegion, locate, locateStatus])
|
||||
return <RegionContext value={api}>{children}</RegionContext>
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { createContext, use } from 'react'
|
||||
import type { RegionData } from '../api/client/types.gen'
|
||||
|
||||
export type LocateStatus = 'idle' | 'locating' | 'denied' | 'error'
|
||||
|
||||
export type RegionApi = { region: RegionData; setRegion: (r: RegionData) => void; locate: () => void; locateStatus: LocateStatus }
|
||||
|
||||
export const DEFAULT_REGION: RegionData = { code: '1144000000', name: '서울 마포구', short_name: '마포구', lat: 37.56071, lon: 126.91053 }
|
||||
|
||||
export const RegionContext = createContext<RegionApi | null>(null)
|
||||
|
||||
export function useRegion() {
|
||||
const ctx = use(RegionContext)
|
||||
if (!ctx) throw new Error('useRegion must be used inside RegionProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { createContext, use } from 'react'
|
||||
import type { SlideBg } from './types'
|
||||
|
||||
export type SharePayload = { title: string; icon: string; bg: SlideBg; messages: string[] }
|
||||
|
||||
export type SheetState =
|
||||
| { type: 'gak'; indexId: number }
|
||||
| { type: 'article'; articleId: number }
|
||||
| { type: 'share'; share: SharePayload }
|
||||
| { type: 'comments'; postId: number }
|
||||
| { type: 'seasonWeek' }
|
||||
| { type: 'login' }
|
||||
| { type: 'region' }
|
||||
| null
|
||||
|
||||
export type SheetApi = { open: (s: Exclude<SheetState, null>) => void; close: () => void }
|
||||
|
||||
export const SheetContext = createContext<SheetApi | null>(null)
|
||||
|
||||
export function useSheet() {
|
||||
const ctx = use(SheetContext)
|
||||
if (!ctx) throw new Error('useSheet must be used inside SheetProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
type P = { className?: string }
|
||||
|
||||
const line = { fill: 'none', stroke: 'currentColor', strokeLinecap: 'round', strokeLinejoin: 'round' } as const
|
||||
|
||||
export function HeartIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
|
||||
<path d="M12 20.5s-8-4.9-8-11A4.6 4.6 0 0 1 12 6.8a4.6 4.6 0 0 1 8 2.7c0 6.1-8 11-8 11z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function CommentIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
|
||||
<path d="M20.5 12a8.5 8.5 0 0 1-12.6 7.4L3.5 20.5l1.2-4.2A8.5 8.5 0 1 1 20.5 12z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function SendIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
|
||||
<path d="M21 3 10 14M21 3l-6.5 18-4-7.5L3 9.5z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function SaveIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" className={className} aria-hidden="true">
|
||||
<path d="M19 21l-7-5-7 5V4.5A1.5 1.5 0 0 1 6.5 3h11A1.5 1.5 0 0 1 19 4.5z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function MoreIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor" className={className} aria-hidden="true">
|
||||
<circle cx="5" cy="12" r="1.8" />
|
||||
<circle cx="12" cy="12" r="1.8" />
|
||||
<circle cx="19" cy="12" r="1.8" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function PinIcon({ className }: P) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" {...line} strokeWidth="2.2" className={className} aria-hidden="true">
|
||||
<path d="M12 21s7-6.2 7-11.5A7 7 0 0 0 5 9.5C5 14.8 12 21 12 21z" />
|
||||
<circle cx="12" cy="9.5" r="2.5" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function TabIcon({ name, className }: P & { name: 'today' | 'gak' | 'sky' | 'week' | 'season' }) {
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" {...line} className={className} aria-hidden="true">
|
||||
{name === 'today' && <path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z" />}
|
||||
{name === 'gak' && (
|
||||
<>
|
||||
<rect x="3.5" y="3.5" width="7" height="7" rx="2" />
|
||||
<rect x="13.5" y="3.5" width="7" height="7" rx="2" />
|
||||
<rect x="3.5" y="13.5" width="7" height="7" rx="2" />
|
||||
<rect x="13.5" y="13.5" width="7" height="7" rx="2" />
|
||||
</>
|
||||
)}
|
||||
{name === 'sky' && <path d="M3 18h18M6 14a6 6 0 0 1 12 0M12 4v3M4.9 7.9l2 2M19.1 7.9l-2 2M8 21h8" />}
|
||||
{name === 'week' && (
|
||||
<>
|
||||
<rect x="3.5" y="5" width="17" height="15.5" rx="2.5" />
|
||||
<path d="M3.5 10h17M8 3v4M16 3v4" />
|
||||
<circle cx="12" cy="15" r="1.6" />
|
||||
</>
|
||||
)}
|
||||
{name === 'season' && <path d="M12 6.5C10 5 7 4.5 3.5 5v14c3.5-.5 6.5 0 8.5 1.5 2-1.5 5-2 8.5-1.5V5C17 4.5 14 5 12 6.5zM12 6.5v14" />}
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export type SlideBg = 'sky' | 'butter' | 'peach' | 'mint' | 'lilac' | 'dusk' | 'night'
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { CSSProperties, ReactNode } from 'react'
|
||||
import { Link } from 'react-router'
|
||||
import { cx } from '../lib/utils'
|
||||
import { iconSrc } from './lib'
|
||||
|
||||
type IcProps = { name: string; className?: string; alt?: string; style?: CSSProperties }
|
||||
|
||||
export function Ic({ name, className, alt = '', style }: IcProps) {
|
||||
return <img src={iconSrc(name)} alt={alt} className={cx('block', className)} style={style} decoding="async" />
|
||||
}
|
||||
|
||||
type SecProps = { title: string; sub?: ReactNode; more?: { to: string; label?: string }; className?: string }
|
||||
|
||||
export function Sec({ title, sub, more, className }: SecProps) {
|
||||
return (
|
||||
<div className={cx('flex items-end justify-between px-4 pt-[22px] pb-1.5', className)}>
|
||||
<div>
|
||||
<h2 className="m-0 font-jua text-[21px] font-normal">{title}</h2>
|
||||
{sub && <p className="mt-0.5 text-[13px] font-semibold text-(--ink2)">{sub}</p>}
|
||||
</div>
|
||||
{more && (
|
||||
<Link to={more.to} className="text-[13px] font-bold text-(--ink2)">
|
||||
{more.label ?? '전체 보기'}
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function Rail({ children, className, label }: { children: ReactNode; className?: string; label?: string }) {
|
||||
return (
|
||||
<div className={cx('b-noscroll flex snap-x snap-proximity gap-2.5 overflow-x-auto px-4 pt-3 pb-1 *:shrink-0 *:snap-start', className)} role={label ? 'group' : undefined} aria-label={label}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type ChipsProps<K extends string> = { items: readonly (readonly [K, string])[]; value: K; onChange: (k: K) => void; label: string }
|
||||
|
||||
export function Chips<K extends string>({ items, value, onChange, label }: ChipsProps<K>) {
|
||||
return (
|
||||
<div className="b-noscroll flex gap-2 overflow-x-auto px-4 pt-3 pb-0.5" role="group" aria-label={label}>
|
||||
{items.map(([k, l]) => (
|
||||
<button
|
||||
key={k}
|
||||
type="button"
|
||||
aria-pressed={value === k}
|
||||
onClick={() => onChange(k)}
|
||||
className={cx('shrink-0 cursor-pointer rounded-full px-3.5 py-[7px] text-[13.5px] font-bold', value === k ? 'bg-(--ink) text-white' : 'bg-white text-(--ink2) shadow-[inset_0_-3px_0_var(--shade)]')}
|
||||
>
|
||||
{l}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type StateProps = { loading?: boolean; error?: unknown; onRetry?: () => void; empty?: string; className?: string }
|
||||
|
||||
/** 불러오는 중·실패·빈 목록 안내 */
|
||||
export function StateBox({ loading, error, onRetry, empty, className }: StateProps) {
|
||||
const text = loading ? '불러오는 중이에요…' : error ? '정보를 불러오지 못했어요.' : empty
|
||||
if (!text) return null
|
||||
return (
|
||||
<div className={cx('mx-3 mt-3 flex flex-col items-center gap-2 rounded-[22px] bg-white px-4 py-6 text-center text-[13.5px] font-semibold text-(--ink2) shadow-[inset_0_-5px_0_var(--shade)]', className)} role={error ? 'alert' : 'status'}>
|
||||
<span>{text}</span>
|
||||
{error != null && onRetry && (
|
||||
<button type="button" onClick={onRetry} className="cursor-pointer rounded-full bg-(--ink) px-4 py-1.5 text-[13px] font-bold text-white">
|
||||
다시 시도
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 줄 목록 (라벨 · 값) */
|
||||
export function Rows({ rows, dark = false }: { rows: { label: string; value: string }[]; dark?: boolean }) {
|
||||
return (
|
||||
<div className="mt-auto flex flex-col">
|
||||
{rows.map((r) => (
|
||||
<div key={r.label} className={cx('flex justify-between gap-2.5 border-b-2 py-2.5 font-bold last:border-b-0', dark ? 'border-white/18' : 'border-[rgb(40_48_74/0.08)]')}>
|
||||
<span>{r.label}</span>
|
||||
<b className="text-right font-jua text-[17px] font-normal">{r.value}</b>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { RainType, Sky, type WeatherSlot } from '../api/client/types.gen'
|
||||
import { kst } from './lib'
|
||||
|
||||
const RAIN_TEXT: Partial<Record<RainType, string>> = { [RainType.RAIN]: '비', [RainType.SLEET]: '진눈깨비', [RainType.SNOW]: '눈', [RainType.SHOWER]: '소나기' }
|
||||
const SKY_TEXT: Record<Sky, string> = { [Sky.CLEAR]: '맑음', [Sky.PARTLY]: '구름 많음', [Sky.CLOUDY]: '흐림' }
|
||||
|
||||
/** 칸 하나의 하늘 상태 한 마디: 비·눈이 오면 그걸, 아니면 하늘 */
|
||||
export function skyText(slot: WeatherSlot) {
|
||||
return (slot.rain_type != null && RAIN_TEXT[slot.rain_type]) || (slot.sky != null ? SKY_TEXT[slot.sky] : slot.note)
|
||||
}
|
||||
|
||||
/** 주어진 시(0~23)를 넘지 않는 마지막 칸 */
|
||||
export function slotAt(slots: WeatherSlot[], hour: number) {
|
||||
let pick: WeatherSlot | undefined
|
||||
for (const s of slots) if (kst(s.at).h <= hour) pick = s
|
||||
return pick ?? slots[0]
|
||||
}
|
||||
|
||||
export const deg = (v: number | null | undefined) => (v == null ? '-' : `${Math.round(v)}°`)
|
||||
@@ -0,0 +1,164 @@
|
||||
@import 'tailwindcss';
|
||||
|
||||
@theme {
|
||||
--font-sans: 'Pretendard Variable', Pretendard, 'Apple SD Gothic Neo', 'Malgun Gothic', sans-serif;
|
||||
--font-jua: 'Jua', 'Pretendard Variable', sans-serif;
|
||||
--font-bagel: 'Bagel Fat One', 'Jua', sans-serif;
|
||||
--font-batang: 'Gowun Batang', 'Nanum Myeongjo', serif;
|
||||
--font-poster: 'Gasoek One', 'Black Han Sans', sans-serif;
|
||||
--font-block: 'Black Han Sans', 'Pretendard Variable', sans-serif;
|
||||
|
||||
--color-pop-orange: #ff5c1f;
|
||||
--color-pop-blue: #2346d9;
|
||||
--color-pop-yellow: #ffd23f;
|
||||
--color-pop-cream: #fff6e0;
|
||||
--color-pop-pink: #ff8fc7;
|
||||
--color-pop-green: #1fbf6a;
|
||||
--color-pop-sky: #8fb3ff;
|
||||
--color-pop-navy: #1d2a5c;
|
||||
|
||||
--color-ink: #28304a;
|
||||
--color-ink-2: #5a6380;
|
||||
--color-sky-1: #bfe3ff;
|
||||
--color-sky-2: #e5f2ff;
|
||||
--color-page: #f7fbff;
|
||||
--color-orange: #ff7a45;
|
||||
--color-orange-deep: #d4552a;
|
||||
--color-butter: #fff1c4;
|
||||
--color-butter-deep: #7a6320;
|
||||
--color-mint: #dcf4e8;
|
||||
--color-peach: #fff4ec;
|
||||
--color-lilac: #ece7ff;
|
||||
--color-rain: #4f97e3;
|
||||
--color-clay-shade: #d9e5f4;
|
||||
--color-gold: #d89413;
|
||||
--color-silver: #7f8aa3;
|
||||
--color-bronze: #b0673a;
|
||||
|
||||
--shadow-clay: inset 0 -6px 0 var(--color-clay-shade), 0 10px 20px rgb(40 48 74 / 0.08);
|
||||
--shadow-clay-lg: inset 0 -9px 0 var(--color-clay-shade), 0 12px 20px rgb(40 48 74 / 0.08);
|
||||
--shadow-btn: inset 0 -6px 0 var(--color-orange-deep), 0 12px 22px rgb(240 106 58 / 0.28);
|
||||
|
||||
--animate-marquee: marquee 40s linear infinite;
|
||||
@keyframes marquee {
|
||||
to {
|
||||
transform: translateX(-50%);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@layer base {
|
||||
html {
|
||||
word-break: keep-all;
|
||||
overflow-wrap: break-word;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
}
|
||||
body {
|
||||
@apply bg-page font-sans text-ink antialiased;
|
||||
}
|
||||
:focus-visible {
|
||||
outline: 3px solid var(--color-rain);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
}
|
||||
|
||||
@utility clay-sun {
|
||||
border-radius: 9999px;
|
||||
background: radial-gradient(circle at 34% 30%, #fff5cf 0%, #ffc86e 30%, #ff8e4e 68%, #ee6436 100%);
|
||||
box-shadow:
|
||||
inset -20px -28px 44px rgb(170 50 20 / 0.34),
|
||||
inset 18px 20px 32px rgb(255 255 255 / 0.55),
|
||||
0 34px 64px rgb(240 106 58 / 0.32);
|
||||
}
|
||||
|
||||
@utility clay-cloud {
|
||||
position: relative;
|
||||
border-radius: 9999px;
|
||||
background: #fff;
|
||||
box-shadow:
|
||||
inset 0 -14px 22px rgb(160 190 230 / 0.45),
|
||||
0 20px 34px rgb(40 70 120 / 0.13);
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
border-radius: 9999px;
|
||||
background: #fff;
|
||||
box-shadow: inset 0 -12px 18px rgb(160 190 230 / 0.35);
|
||||
}
|
||||
&::before {
|
||||
left: 16%;
|
||||
top: -58%;
|
||||
width: 46%;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
&::after {
|
||||
left: 50%;
|
||||
top: -36%;
|
||||
width: 36%;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@utility drop-icon {
|
||||
filter: drop-shadow(0 10px 12px rgb(40 48 74 / 0.16));
|
||||
}
|
||||
|
||||
/* 히어로 오브젝트: 하늘에서 떨어진 뒤 계속 둥둥 떠 있기 */
|
||||
@keyframes sky-drop {
|
||||
0% {
|
||||
transform: translateY(-110vh) rotate(-10deg);
|
||||
opacity: 0;
|
||||
}
|
||||
55% {
|
||||
opacity: 1;
|
||||
}
|
||||
72% {
|
||||
transform: translateY(0) rotate(2deg) scale(1.04, 0.96);
|
||||
}
|
||||
86% {
|
||||
transform: translateY(-14px) rotate(-1deg);
|
||||
}
|
||||
100% {
|
||||
transform: none;
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes sky-float {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0) rotate(0deg);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(calc(var(--amp, 12px) * -1)) rotate(var(--tilt, 1.5deg));
|
||||
}
|
||||
}
|
||||
|
||||
@utility sky-fall {
|
||||
animation:
|
||||
sky-drop 1.1s cubic-bezier(0.22, 0.9, 0.3, 1) var(--delay, 0s) both,
|
||||
sky-float var(--float, 4.6s) ease-in-out calc(var(--delay, 0s) + 1.1s) infinite;
|
||||
}
|
||||
|
||||
/* PC: 모든 섹션 최소 한 화면(메뉴 바 제외) + 섹션 단위 스냅 */
|
||||
@utility screen-fill {
|
||||
@media (width >= 64rem) {
|
||||
min-height: calc(100svh - var(--nav, 76px));
|
||||
scroll-snap-align: start;
|
||||
scroll-margin-top: var(--nav, 76px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (width >= 64rem) {
|
||||
html {
|
||||
scroll-snap-type: y proximity;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.animate-marquee,
|
||||
.sky-fall {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export function cx(...parts: (string | false | null | undefined)[]) {
|
||||
return parts.filter(Boolean).join(' ')
|
||||
}
|
||||
|
||||
const RANK_COLOR = { 1: 'text-gold', 2: 'text-silver', 3: 'text-bronze' } as const
|
||||
|
||||
export function rankText(rank: number) {
|
||||
return rank <= 3 ? RANK_COLOR[rank as 1 | 2 | 3] : 'text-ink-2'
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import './api/setup'
|
||||
import App from './App.tsx'
|
||||
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { staleTime: 5 * 60 * 1000, retry: 1, refetchOnWindowFocus: false } },
|
||||
})
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
Reference in new issue
Block a user