feat: 카드뉴스 포스트(관리자 admin/, /v1/card API, 피드 이미지 슬라이드), 인스타 홍보 기획 문서
No files matched your search
@@ -0,0 +1,21 @@
|
||||
import { BrowserRouter, Route, Routes } from 'react-router'
|
||||
import { AdminLayout } from './pages/AdminLayout'
|
||||
import { CardsPage } from './pages/CardsPage'
|
||||
import { HistoryPage } from './pages/HistoryPage'
|
||||
import { RenderPage } from './pages/RenderPage'
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<Routes>
|
||||
{/* npm run card 가 찍는 화면: 카드 한 장만, 1080×1350 */}
|
||||
<Route path="render" element={<RenderPage />} />
|
||||
<Route element={<AdminLayout />}>
|
||||
<Route index element={<CardsPage />} />
|
||||
<Route path="history" element={<HistoryPage />} />
|
||||
<Route path="*" element={<CardsPage />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
)
|
||||
}
|
||||
@@ -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:9811', 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, addMyGak, addTalk, authConfig, blockTalkAuthor, deleteComment, deleteMyGak, deleteTalk, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTalkImage, getTodayGuPage, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, likeTalk, listArticles, listComments, listEvents, listIndices, listMyGak, listPlaces, listRegions, listSaved, listTalks, login, logout, me, nearestRegion, type Options, refresh, reportTalk, savePost, scoreMyGak, signup, unlikeComment, unlikePost, unlikeTalk, unsavePost, updateMe, uploadTalkImage } from './sdk.gen';
|
||||
export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AddMyGakData, type AddMyGakError, type AddMyGakErrors, type AddMyGakResponse, type AddMyGakResponses, type AddTalkData, type AddTalkError, type AddTalkErrors, type AddTalkResponse, type AddTalkResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockTalkAuthorData, type BlockTalkAuthorError, type BlockTalkAuthorErrors, type BlockTalkAuthorResponse, type BlockTalkAuthorResponses, type BodyUploadTalkImageV1TalkImagePost, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type DeleteMyGakData, type DeleteMyGakError, type DeleteMyGakErrors, type DeleteMyGakResponse, type DeleteMyGakResponses, type DeleteTalkData, type DeleteTalkError, type DeleteTalkErrors, type DeleteTalkResponse, type DeleteTalkResponses, 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 GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, 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 GetTalkImageData, type GetTalkImageError, type GetTalkImageErrors, type GetTalkImageResponses, type GetTodayGuPageData, type GetTodayGuPageError, type GetTodayGuPageErrors, type GetTodayGuPageResponse, type GetTodayGuPageResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, 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 GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, 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 LikeTalkData, type LikeTalkError, type LikeTalkErrors, type LikeTalkResponse, type LikeTalkResponses, 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 ListMyGakData, type ListMyGakError, type ListMyGakErrors, type ListMyGakResponse, type ListMyGakResponses, 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 ListTalksData, type ListTalksError, type ListTalksErrors, type ListTalksResponse, type ListTalksResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses,
Line truncated
|
||||
@@ -0,0 +1,362 @@
|
||||
// This file is auto-generated by @hey-api/openapi-ts
|
||||
|
||||
import { type Client, type ClientMeta, formDataBodySerializer, type Options as Options2, type RequestResult, type TDataShape } from './client';
|
||||
import { client } from './client.gen';
|
||||
import type { AddCommentData, AddCommentErrors, AddCommentResponses, AddMyGakData, AddMyGakErrors, AddMyGakResponses, AddTalkData, AddTalkErrors, AddTalkResponses, AuthConfigData, AuthConfigResponses, BlockTalkAuthorData, BlockTalkAuthorErrors, BlockTalkAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, DeleteMyGakData, DeleteMyGakErrors, DeleteMyGakResponses, DeleteTalkData, DeleteTalkErrors, DeleteTalkResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTalkImageData, GetTalkImageErrors, GetTalkImageResponses, GetTodayGuPageData, GetTodayGuPageErrors, GetTodayGuPageResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, LikeTalkData, LikeTalkErrors, LikeTalkResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListMyGakData, ListMyGakErrors, ListMyGakResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, ListTalksData, ListTalksErrors, ListTalksResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportTalkData, ReportTalkErrors, ReportTalkResponses, SavePostData, SavePostErrors, SavePostResponses, ScoreMyGakData, ScoreMyGakErrors, ScoreMyGakResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnlikeTalkData, UnlikeTalkErrors, UnlikeTalkResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, UploadTalkImageData, UploadTalkImageErrors, UploadTalkImageResponses } 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일, 가까운 명소
|
||||
*/
|
||||
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 });
|
||||
|
||||
/**
|
||||
* 이번 주말 전국 나들이 날씨 순위 (대표 30곳)
|
||||
*/
|
||||
export const getWeekRanking = <ThrowOnError extends boolean = true>(options?: Options<GetWeekRankingData, ThrowOnError>): RequestResult<GetWeekRankingResponses, unknown, ThrowOnError> => (options?.client ?? client).get<GetWeekRankingResponses, unknown, ThrowOnError>({ url: '/v1/week/ranking', ...options });
|
||||
|
||||
/**
|
||||
* 날씨 맞춤 데이트 명소 (구 중심 30km 안, 없으면 가장 가까운 곳)
|
||||
*/
|
||||
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 googleLogin = <ThrowOnError extends boolean = true>(options: Options<GoogleLoginData, ThrowOnError>): RequestResult<GoogleLoginResponses, GoogleLoginErrors, ThrowOnError> => (options.client ?? client).post<GoogleLoginResponses, GoogleLoginErrors, ThrowOnError>({
|
||||
url: '/v1/auth/google',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 로그인 화면 설정 (구글 클라이언트 ID)
|
||||
*/
|
||||
export const authConfig = <ThrowOnError extends boolean = true>(options?: Options<AuthConfigData, ThrowOnError>): RequestResult<AuthConfigResponses, unknown, ThrowOnError> => (options?.client ?? client).get<AuthConfigResponses, unknown, ThrowOnError>({ url: '/v1/auth/config', ...options });
|
||||
|
||||
/**
|
||||
* 토큰 재발급
|
||||
*/
|
||||
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 logout = <ThrowOnError extends boolean = true>(options?: Options<LogoutData, ThrowOnError>): RequestResult<LogoutResponses, LogoutErrors, ThrowOnError> => (options?.client ?? client).post<LogoutResponses, LogoutErrors, ThrowOnError>({ url: '/v1/auth/logout', ...options });
|
||||
|
||||
/**
|
||||
* 내 정보
|
||||
*/
|
||||
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 });
|
||||
|
||||
/**
|
||||
* 내 정보 바꾸기 (닉네임 2~12자, 캐릭터 rabbit·bear·dog·sun·moon·cloud, 배경색 orange·blue·green·purple·pink·brown, 기분 clear·partly·cloudy·rain·thunder·snow·fog·rainbow, 빈 문자열이면 지움)
|
||||
*/
|
||||
export const updateMe = <ThrowOnError extends boolean = true>(options: Options<UpdateMeData, ThrowOnError>): RequestResult<UpdateMeResponses, UpdateMeErrors, ThrowOnError> => (options.client ?? client).patch<UpdateMeResponses, UpdateMeErrors, ThrowOnError>({
|
||||
url: '/v1/auth/me',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 좋아요 취소
|
||||
*/
|
||||
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 });
|
||||
|
||||
/**
|
||||
* 좋아요 (로그인 없으면 IP 당 한 번)
|
||||
*/
|
||||
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 });
|
||||
|
||||
/**
|
||||
* 댓글 좋아요 (로그인 없으면 IP 당 한 번)
|
||||
*/
|
||||
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 listMyGak = <ThrowOnError extends boolean = true>(options?: Options<ListMyGakData, ThrowOnError>): RequestResult<ListMyGakResponses, ListMyGakErrors, ThrowOnError> => (options?.client ?? client).get<ListMyGakResponses, ListMyGakErrors, ThrowOnError>({ url: '/v1/my-gak', ...options });
|
||||
|
||||
/**
|
||||
* 이름과 날씨 조건으로 내 각 만들기
|
||||
*/
|
||||
export const addMyGak = <ThrowOnError extends boolean = true>(options: Options<AddMyGakData, ThrowOnError>): RequestResult<AddMyGakResponses, AddMyGakErrors, ThrowOnError> => (options.client ?? client).post<AddMyGakResponses, AddMyGakErrors, ThrowOnError>({
|
||||
url: '/v1/my-gak',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 조건들의 그 동네 오늘 점수 (로그인 없이, 받은 링크의 각도)
|
||||
*/
|
||||
export const scoreMyGak = <ThrowOnError extends boolean = true>(options: Options<ScoreMyGakData, ThrowOnError>): RequestResult<ScoreMyGakResponses, ScoreMyGakErrors, ThrowOnError> => (options.client ?? client).post<ScoreMyGakResponses, ScoreMyGakErrors, ThrowOnError>({
|
||||
url: '/v1/my-gak/score',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 내 각 지우기
|
||||
*/
|
||||
export const deleteMyGak = <ThrowOnError extends boolean = true>(options: Options<DeleteMyGakData, ThrowOnError>): RequestResult<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError> => (options.client ?? client).delete<DeleteMyGakResponses, DeleteMyGakErrors, ThrowOnError>({ url: '/v1/my-gak/{my_gak_id}', ...options });
|
||||
|
||||
/**
|
||||
* 동네 이야기 (전국, 최신순, 로그인 없이 보기)
|
||||
*/
|
||||
export const listTalks = <ThrowOnError extends boolean = true>(options?: Options<ListTalksData, ThrowOnError>): RequestResult<ListTalksResponses, ListTalksErrors, ThrowOnError> => (options?.client ?? client).get<ListTalksResponses, ListTalksErrors, ThrowOnError>({ url: '/v1/talk/list', ...options });
|
||||
|
||||
/**
|
||||
* 동네 이야기 쓰기 (링크·전화번호 불가, 하루 5개)
|
||||
*/
|
||||
export const addTalk = <ThrowOnError extends boolean = true>(options: Options<AddTalkData, ThrowOnError>): RequestResult<AddTalkResponses, AddTalkErrors, ThrowOnError> => (options.client ?? client).post<AddTalkResponses, AddTalkErrors, ThrowOnError>({
|
||||
url: '/v1/talk',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 글에 붙일 사진 올리기 (10MB까지, 위치 정보를 지우고 1080px로 줄여 저장)
|
||||
*/
|
||||
export const uploadTalkImage = <ThrowOnError extends boolean = true>(options: Options<UploadTalkImageData, ThrowOnError>): RequestResult<UploadTalkImageResponses, UploadTalkImageErrors, ThrowOnError> => (options.client ?? client).post<UploadTalkImageResponses, UploadTalkImageErrors, ThrowOnError>({
|
||||
...formDataBodySerializer,
|
||||
url: '/v1/talk/image',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': null,
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 올린 사진
|
||||
*/
|
||||
export const getTalkImage = <ThrowOnError extends boolean = true>(options: Options<GetTalkImageData, ThrowOnError>): RequestResult<GetTalkImageResponses, GetTalkImageErrors, ThrowOnError> => (options.client ?? client).get<GetTalkImageResponses, GetTalkImageErrors, ThrowOnError>({ url: '/v1/talk/image/{name}', ...options });
|
||||
|
||||
/**
|
||||
* 내 이야기 지우기
|
||||
*/
|
||||
export const deleteTalk = <ThrowOnError extends boolean = true>(options: Options<DeleteTalkData, ThrowOnError>): RequestResult<DeleteTalkResponses, DeleteTalkErrors, ThrowOnError> => (options.client ?? client).delete<DeleteTalkResponses, DeleteTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}', ...options });
|
||||
|
||||
/**
|
||||
* 이야기 좋아요 취소
|
||||
*/
|
||||
export const unlikeTalk = <ThrowOnError extends boolean = true>(options: Options<UnlikeTalkData, ThrowOnError>): RequestResult<UnlikeTalkResponses, UnlikeTalkErrors, ThrowOnError> => (options.client ?? client).delete<UnlikeTalkResponses, UnlikeTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 이야기 좋아요 (로그인 없으면 IP 당 한 번)
|
||||
*/
|
||||
export const likeTalk = <ThrowOnError extends boolean = true>(options: Options<LikeTalkData, ThrowOnError>): RequestResult<LikeTalkResponses, LikeTalkErrors, ThrowOnError> => (options.client ?? client).post<LikeTalkResponses, LikeTalkErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/like', ...options });
|
||||
|
||||
/**
|
||||
* 이야기 신고 (서로 다른 3명이면 숨김)
|
||||
*/
|
||||
export const reportTalk = <ThrowOnError extends boolean = true>(options: Options<ReportTalkData, ThrowOnError>): RequestResult<ReportTalkResponses, ReportTalkErrors, ThrowOnError> => (options.client ?? client).post<ReportTalkResponses, ReportTalkErrors, ThrowOnError>({
|
||||
url: '/v1/talk/{talk_id}/report',
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* 이 글 쓴 사람의 글 안 보기
|
||||
*/
|
||||
export const blockTalkAuthor = <ThrowOnError extends boolean = true>(options: Options<BlockTalkAuthorData, ThrowOnError>): RequestResult<BlockTalkAuthorResponses, BlockTalkAuthorErrors, ThrowOnError> => (options.client ?? client).post<BlockTalkAuthorResponses, BlockTalkAuthorErrors, ThrowOnError>({ url: '/v1/talk/{talk_id}/block', ...options });
|
||||
|
||||
/**
|
||||
* 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표
|
||||
*/
|
||||
export const getWatchSummary = <ThrowOnError extends boolean = true>(options: Options<GetWatchSummaryData, ThrowOnError>): RequestResult<GetWatchSummaryResponses, GetWatchSummaryErrors, ThrowOnError> => (options.client ?? client).get<GetWatchSummaryResponses, GetWatchSummaryErrors, ThrowOnError>({ url: '/v1/watch/summary', ...options });
|
||||
|
||||
/**
|
||||
* 행사 사진 대신 받기 (공유 이미지용, 허용한 호스트만)
|
||||
*/
|
||||
export const getImage = <ThrowOnError extends boolean = true>(options: Options<GetImageData, ThrowOnError>): RequestResult<GetImageResponses, GetImageErrors, ThrowOnError> => (options.client ?? client).get<GetImageResponses, GetImageErrors, ThrowOnError>({ url: '/v1/image', ...options });
|
||||
|
||||
/**
|
||||
* 지역 검색 페이지: 정적 HTML 에 오늘 날씨·각을 채워 돌려준다 (nginx 가 /today/... 를 넘김)
|
||||
*/
|
||||
export const getTodayPage = <ThrowOnError extends boolean = true>(options: Options<GetTodayPageData, ThrowOnError>): RequestResult<GetTodayPageResponses, GetTodayPageErrors, ThrowOnError> => (options.client ?? client).get<GetTodayPageResponses, GetTodayPageErrors, ThrowOnError>({ url: '/v1/seo/today/{sido}/{place}', ...options });
|
||||
|
||||
/**
|
||||
* 구로 나뉜 시의 구 페이지 (/today/gyeonggi/seongnam/bundang)
|
||||
*/
|
||||
export const getTodayGuPage = <ThrowOnError extends boolean = true>(options: Options<GetTodayGuPageData, ThrowOnError>): RequestResult<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError> => (options.client ?? client).get<GetTodayGuPageResponses, GetTodayGuPageErrors, ThrowOnError>({ url: '/v1/seo/today/{sido}/{place}/{gu}', ...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 });
|
||||
@@ -0,0 +1,5 @@
|
||||
import { client } from './client/client.gen'
|
||||
|
||||
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
||||
|
||||
client.setConfig({ baseUrl: API_BASE_URL, throwOnError: true })
|
||||
|
After Width: | Height: | Size: 222 KiB |
|
After Width: | Height: | Size: 222 KiB |
|
After Width: | Height: | Size: 214 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 88 KiB |
|
After Width: | Height: | Size: 94 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 98 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 69 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 68 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 171 KiB |
|
After Width: | Height: | Size: 37 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 28 KiB |
|
After Width: | Height: | Size: 32 KiB |
@@ -0,0 +1,32 @@
|
||||
import type { CSSProperties, ReactNode } from 'react'
|
||||
import { themeVars } from './themes'
|
||||
|
||||
/** 줄바꿈(\n)은 카드에서도 줄바꿈, *별표* 사이는 강조색 */
|
||||
export function Lines({ text }: { text: string }) {
|
||||
return text.split('\n').map((line, i) => (
|
||||
<span className="line" key={i}>
|
||||
{line.split(/(\*[^*]+\*)/).map((part, j) => (part.startsWith('*') && part.endsWith('*') ? <strong key={j}>{part.slice(1, -1)}</strong> : part))}
|
||||
</span>
|
||||
))
|
||||
}
|
||||
|
||||
export function Frame({ page, total, theme, skin, className = '', style, children }: { page: number; total: number; theme?: string; skin?: string; className?: string; style?: CSSProperties; children: ReactNode }) {
|
||||
return (
|
||||
<section className={`slide ${className}`} data-skin={skin || 'star'} style={{ ...themeVars(theme), ...style }}>
|
||||
<header className="topbar">
|
||||
<div className="brand">
|
||||
<i className="brand-mark" aria-hidden="true" />
|
||||
날씨각
|
||||
</div>
|
||||
{total > 1 && (
|
||||
<div className="pagination" aria-hidden="true">
|
||||
{Array.from({ length: total }, (_, i) => (
|
||||
<i key={i} className={i === page ? 'active' : ''} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</header>
|
||||
{children}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
/* 인스타 카드 1080×1350. 브랜드 색·서체는 서비스(frontend b.css)와 같다 */
|
||||
.slide {
|
||||
--ink: #28304a;
|
||||
--paper: #f7fbff;
|
||||
--orange: #ff7a45;
|
||||
--rust: #d4552a;
|
||||
--blue: #4f97e3;
|
||||
--muted: #546078;
|
||||
--accent: var(--rust);
|
||||
--tint: #fff0e5;
|
||||
--soft: #ffd7bd;
|
||||
--stage: #e1efff;
|
||||
position: relative;
|
||||
width: 1080px;
|
||||
height: 1350px;
|
||||
overflow: hidden;
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
font-family: 'Pretendard Variable', Pretendard, sans-serif;
|
||||
isolation: isolate;
|
||||
word-break: keep-all;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
.slide h1,
|
||||
.slide h2,
|
||||
.slide p,
|
||||
.slide ol {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-weight: 400;
|
||||
}
|
||||
.slide .line {
|
||||
display: block;
|
||||
}
|
||||
.slide strong {
|
||||
color: var(--accent);
|
||||
font-weight: inherit;
|
||||
}
|
||||
|
||||
/* 공통 머리 */
|
||||
.slide .topbar {
|
||||
position: absolute;
|
||||
top: 85px;
|
||||
left: 80px;
|
||||
right: 80px;
|
||||
height: 53px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
z-index: 5;
|
||||
}
|
||||
.slide .brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
font: 40px/1 Jua, sans-serif;
|
||||
letter-spacing: -1px;
|
||||
}
|
||||
.slide .brand-mark {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 50%;
|
||||
background: var(--orange);
|
||||
box-shadow: 0 4px 0 var(--rust);
|
||||
}
|
||||
.slide .brand-mark::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
right: -7px;
|
||||
bottom: -2px;
|
||||
width: 23px;
|
||||
height: 12px;
|
||||
border-radius: 10px;
|
||||
background: #bddbfb;
|
||||
border: 3px solid var(--paper);
|
||||
}
|
||||
.slide .pagination {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
.slide .pagination i {
|
||||
display: block;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 50%;
|
||||
background: #cbd7e7;
|
||||
}
|
||||
.slide .pagination i.active {
|
||||
width: 30px;
|
||||
border-radius: 8px;
|
||||
background: var(--accent);
|
||||
}
|
||||
.slide .meta {
|
||||
position: absolute;
|
||||
top: 174px;
|
||||
left: 80px;
|
||||
font-size: 32px;
|
||||
font-weight: 600;
|
||||
color: var(--muted);
|
||||
letter-spacing: -0.6px;
|
||||
}
|
||||
.slide .meta.right {
|
||||
top: 92px;
|
||||
left: auto;
|
||||
right: 88px;
|
||||
}
|
||||
.slide .sparkle {
|
||||
position: absolute;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
background: var(--orange);
|
||||
clip-path: polygon(50% 0, 64% 36%, 100% 50%, 64% 64%, 50% 100%, 36% 64%, 0 50%, 36% 36%);
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
/* OOTD */
|
||||
.ootd .meta {
|
||||
top: 168px;
|
||||
}
|
||||
.ootd-title {
|
||||
position: absolute;
|
||||
top: 214px;
|
||||
left: 80px;
|
||||
right: 80px;
|
||||
font: 104px/1.1 Jua, sans-serif;
|
||||
letter-spacing: -3px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ootd-stage {
|
||||
position: absolute;
|
||||
top: 350px;
|
||||
left: 80px;
|
||||
width: 920px;
|
||||
height: 840px;
|
||||
border-radius: 44px;
|
||||
overflow: hidden;
|
||||
background: var(--stage);
|
||||
}
|
||||
.ootd-stage > img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.ootd-labels {
|
||||
position: absolute;
|
||||
inset: 24px;
|
||||
display: grid;
|
||||
grid-template-columns: auto auto;
|
||||
align-content: space-between;
|
||||
justify-content: space-between;
|
||||
justify-items: start;
|
||||
gap: 16px;
|
||||
}
|
||||
.ootd-labels span:nth-child(even) {
|
||||
justify-self: end;
|
||||
}
|
||||
.ootd-labels span {
|
||||
padding: 8px 20px;
|
||||
border-radius: 99px;
|
||||
background: #fff;
|
||||
font-size: 30px;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 6px 16px #28304a1f;
|
||||
}
|
||||
.ootd-labels.only {
|
||||
inset: 60px;
|
||||
flex-direction: column;
|
||||
flex-wrap: nowrap;
|
||||
align-content: center;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 28px;
|
||||
}
|
||||
.ootd-labels.only span {
|
||||
padding: 18px 44px;
|
||||
font: 60px/1.2 Jua, sans-serif;
|
||||
}
|
||||
/* 날씨 타로 표지·마지막 장 */
|
||||
.cover-title {
|
||||
position: absolute;
|
||||
top: 170px;
|
||||
left: 100px;
|
||||
width: 880px;
|
||||
text-align: center;
|
||||
font-family: Jua, sans-serif;
|
||||
line-height: 1.07;
|
||||
letter-spacing: -4px;
|
||||
z-index: 3;
|
||||
}
|
||||
.cover-title .line:first-child {
|
||||
font-size: 64px;
|
||||
}
|
||||
.cover-title .line + .line {
|
||||
margin-top: 10px;
|
||||
font-size: 124px;
|
||||
color: var(--rust);
|
||||
text-shadow: 0 6px 0 var(--soft);
|
||||
}
|
||||
/* 타로 질문: 이 질문에 카드가 답한다 */
|
||||
.slide .cover-question {
|
||||
position: absolute;
|
||||
top: 400px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: max-content;
|
||||
max-width: 900px;
|
||||
padding: 14px 28px;
|
||||
border-radius: 99px;
|
||||
background: #fff;
|
||||
box-shadow: 0 6px 0 var(--soft), 0 14px 26px #28304a10;
|
||||
text-align: center;
|
||||
font-size: 34px;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
letter-spacing: -1.2px;
|
||||
white-space: nowrap;
|
||||
z-index: 5;
|
||||
}
|
||||
.slide .cover-question b {
|
||||
margin-right: 10px;
|
||||
font: 38px/1 'Bagel Fat One', sans-serif;
|
||||
color: var(--rust);
|
||||
}
|
||||
.cover-stage {
|
||||
position: absolute;
|
||||
top: 600px;
|
||||
left: 92px;
|
||||
width: 896px;
|
||||
height: 500px;
|
||||
border-radius: 50%;
|
||||
background: var(--stage);
|
||||
}
|
||||
.back-card {
|
||||
position: absolute;
|
||||
width: 250px;
|
||||
height: 375px;
|
||||
border-radius: 22px;
|
||||
box-shadow: 0 13px 0 #b8cce1, 0 23px 26px #28304a1c;
|
||||
z-index: 3;
|
||||
}
|
||||
.back-card img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 22px;
|
||||
object-fit: cover;
|
||||
}
|
||||
.back-card .number {
|
||||
position: absolute;
|
||||
top: 42px;
|
||||
left: calc(50% - 44px);
|
||||
width: 88px;
|
||||
height: 88px;
|
||||
padding-bottom: 6px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 50%;
|
||||
font: 67px/1 'Bagel Fat One', sans-serif;
|
||||
color: var(--ink);
|
||||
background: var(--paper);
|
||||
border: 5px solid #ffb76f;
|
||||
box-shadow: 0 5px 0 #171f37;
|
||||
}
|
||||
.back-card.big.card-1 { left: 117px; top: 651px; transform: rotate(-9deg); }
|
||||
.back-card.big.card-2 { left: 415px; top: 588px; transform: rotate(1deg); }
|
||||
.back-card.big.card-3 { left: 713px; top: 651px; transform: rotate(9deg); }
|
||||
.tarot-cover .rabbit,
|
||||
.tarot-cover .bear {
|
||||
position: absolute;
|
||||
top: 1120px;
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
z-index: 4;
|
||||
}
|
||||
.tarot-cover .rabbit { left: 145px; transform: rotate(-10deg); }
|
||||
.tarot-cover .bear { right: 143px; top: 1128px; transform: rotate(9deg); }
|
||||
.cover-date {
|
||||
position: absolute;
|
||||
top: 1200px;
|
||||
left: 190px;
|
||||
width: 700px;
|
||||
text-align: center;
|
||||
font-size: 30px;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.6px;
|
||||
color: var(--muted);
|
||||
}
|
||||
.tarot-cover .sparkle.a { left: 167px; top: 260px; width: 55px; height: 55px; transform: rotate(13deg); }
|
||||
.tarot-cover .sparkle.b { right: 166px; top: 374px; width: 40px; height: 40px; background: var(--blue); }
|
||||
.tarot-cover .sparkle.c { left: 508px; top: 1108px; width: 54px; height: 54px; }
|
||||
|
||||
/* 날씨 타로 결과 장 */
|
||||
|
||||
|
||||
/* 주제별 꾸밈 (topics.json skin): 반짝이(.sparkle)와 표지 장식(.deco) 모양만 바뀐다 */
|
||||
.slide .deco {
|
||||
position: absolute;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
background: var(--orange);
|
||||
clip-path: polygon(50% 0, 64% 36%, 100% 50%, 64% 64%, 50% 100%, 36% 64%, 0 50%, 36% 36%);
|
||||
opacity: 0.85;
|
||||
z-index: 2;
|
||||
}
|
||||
.slide .deco.d1 { left: 74px; top: 560px; width: 30px; height: 30px; }
|
||||
.slide .deco.d2 { right: 70px; top: 520px; width: 38px; height: 38px; background: var(--blue); }
|
||||
.slide .deco.d3 { left: 58px; top: 905px; width: 26px; height: 26px; background: var(--blue); }
|
||||
.slide .deco.d4 { right: 64px; top: 880px; width: 32px; height: 32px; }
|
||||
.slide .deco.d5 { left: 330px; top: 1160px; width: 24px; height: 24px; background: var(--blue); }
|
||||
.slide .deco.d6 { right: 330px; top: 1175px; width: 28px; height: 28px; }
|
||||
|
||||
.slide[data-skin='heart'] :is(.sparkle, .deco) {
|
||||
clip-path: none;
|
||||
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M12 21.5s-7.8-4.7-10-9.4C.4 8.6 2.5 4.4 6.4 4.4c2.3 0 3.8 1.3 5.6 3.4 1.8-2.1 3.3-3.4 5.6-3.4 3.9 0 6 4.2 4.4 7.7-2.2 4.7-10 9.4-10 9.4z'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath d='M12 21.5s-7.8-4.7-10-9.4C.4 8.6 2.5 4.4 6.4 4.4c2.3 0 3.8 1.3 5.6 3.4 1.8-2.1 3.3-3.4 5.6-3.4 3.9 0 6 4.2 4.4 7.7-2.2 4.7-10 9.4-10 9.4z'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||
}
|
||||
.slide[data-skin='coin'] :is(.sparkle, .deco) {
|
||||
clip-path: none;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(circle, var(--orange) 0 52%, var(--rust) 53% 62%, var(--orange) 63%);
|
||||
}
|
||||
.slide[data-skin='clover'] :is(.sparkle, .deco) {
|
||||
clip-path: none;
|
||||
-webkit-mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Ccircle cx='8' cy='8' r='5'/%3E%3Ccircle cx='16' cy='8' r='5'/%3E%3Ccircle cx='8' cy='16' r='5'/%3E%3Ccircle cx='16' cy='16' r='5'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Ccircle cx='8' cy='8' r='5'/%3E%3Ccircle cx='16' cy='8' r='5'/%3E%3Ccircle cx='8' cy='16' r='5'/%3E%3Ccircle cx='16' cy='16' r='5'/%3E%3C/svg%3E") center / contain no-repeat;
|
||||
}
|
||||
|
||||
/* 날씨 타로: 대주제(skin)마다 한 번 만든 배경 그림(src/assets/tarot-bg) 위에 카드·글만 갈아 끼운다 */
|
||||
.slide .tarot-bg {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
z-index: 0;
|
||||
}
|
||||
.tarot-result > :not(.tarot-bg):not(.topbar) { position: relative; z-index: 1; }
|
||||
|
||||
/* 결과 장: 틀·장식 없이 카드 그림과 리딩이 화면을 채운다. 배경 그림이 없을 땐 아래쪽에 옅은 색 번짐만 */
|
||||
.tarot-result {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 150px 80px 64px;
|
||||
gap: 24px;
|
||||
background:
|
||||
radial-gradient(60% 34% at 85% 96%, var(--tint) 0%, transparent 70%),
|
||||
radial-gradient(40% 24% at 8% 78%, var(--tint) 0%, transparent 70%),
|
||||
var(--paper);
|
||||
}
|
||||
.tarot-result .topbar { z-index: 5; }
|
||||
.result-head {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 18px;
|
||||
}
|
||||
.slide .card-no {
|
||||
margin-bottom: 14px;
|
||||
padding: 8px 16px;
|
||||
border-radius: 99px;
|
||||
background: var(--tint);
|
||||
font: 700 30px/1 'Pretendard Variable', Pretendard, sans-serif;
|
||||
color: var(--accent);
|
||||
letter-spacing: -0.5px;
|
||||
}
|
||||
.slide .card-name {
|
||||
font: 96px/1 Jua, sans-serif;
|
||||
letter-spacing: -3px;
|
||||
}
|
||||
.result-body {
|
||||
display: grid;
|
||||
grid-template-columns: 520px minmax(0, 1fr);
|
||||
gap: 32px;
|
||||
align-items: stretch;
|
||||
}
|
||||
.slide .card-art {
|
||||
width: 520px;
|
||||
height: 780px;
|
||||
object-fit: cover;
|
||||
border-radius: 30px;
|
||||
box-shadow: 0 12px 0 var(--tint), 0 22px 40px #28304a22;
|
||||
}
|
||||
.slide .card-art-fallback {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--tint);
|
||||
}
|
||||
.slide .card-art-fallback img {
|
||||
width: 280px;
|
||||
height: 280px;
|
||||
object-fit: contain;
|
||||
}
|
||||
.result-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 22px;
|
||||
}
|
||||
.slide .card-keyword {
|
||||
font: 700 34px/1.3 'Pretendard Variable', Pretendard, sans-serif;
|
||||
color: var(--accent);
|
||||
letter-spacing: -1px;
|
||||
}
|
||||
.slide .reading {
|
||||
font: 500 38px/1.55 'Pretendard Variable', Pretendard, sans-serif;
|
||||
letter-spacing: -1px;
|
||||
/* 단어(어절) 단위로만 줄을 바꾸고, 마지막 줄에 한 어절만 남지 않게 */
|
||||
word-break: keep-all;
|
||||
overflow-wrap: normal;
|
||||
text-wrap: pretty;
|
||||
}
|
||||
.slide .reading .line { display: inline; }
|
||||
.slide .reading strong {
|
||||
font-weight: 750;
|
||||
color: var(--accent);
|
||||
}
|
||||
.slide .lucky {
|
||||
margin-top: 18px;
|
||||
padding: 24px 32px;
|
||||
border-radius: 24px;
|
||||
background: var(--tint);
|
||||
font: 700 34px/1.35 'Pretendard Variable', Pretendard, sans-serif;
|
||||
letter-spacing: -0.8px;
|
||||
color: var(--accent);
|
||||
}
|
||||
.slide .lucky::before {
|
||||
content: '행운 포인트 · ';
|
||||
opacity: 0.7;
|
||||
}
|
||||
/* 맨 위: 이 장이 답하는 질문 → 카드 번호·이름 → 그림 순으로 읽힌다 */
|
||||
.slide .result-question {
|
||||
display: flex;
|
||||
gap: 14px;
|
||||
align-items: baseline;
|
||||
font: 600 30px/1.4 'Pretendard Variable', Pretendard, sans-serif;
|
||||
letter-spacing: -0.8px;
|
||||
color: var(--muted);
|
||||
word-break: keep-all;
|
||||
}
|
||||
.slide .result-question b {
|
||||
font: 32px/1 'Bagel Fat One', sans-serif;
|
||||
color: var(--accent);
|
||||
}
|
||||
.slide .footnote {
|
||||
margin-top: auto;
|
||||
font-size: 28px;
|
||||
font-weight: 600;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
/* 코디 장 아래: 오늘 날씨 한 줄 */
|
||||
.slide .ootd-weather {
|
||||
position: absolute;
|
||||
left: 80px;
|
||||
right: 80px;
|
||||
bottom: 64px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 18px;
|
||||
font: 600 36px/1.2 'Pretendard Variable', Pretendard, sans-serif;
|
||||
letter-spacing: -1px;
|
||||
color: var(--ink);
|
||||
}
|
||||
.slide .ootd-weather img {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
object-fit: contain;
|
||||
}
|
||||
.slide .ootd-weather b {
|
||||
font: 700 40px/1 'Pretendard Variable', Pretendard, sans-serif;
|
||||
color: var(--rust);
|
||||
}
|
||||
|
||||
/* 마지막 장은 표지와 같은 틀. 안내 문구만 캐릭터 사이에 두 줄로 */
|
||||
.tarot-closing .cover-date {
|
||||
left: 290px;
|
||||
width: 500px;
|
||||
top: 1192px;
|
||||
font-size: 27px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import '../api/setup'
|
||||
import { loadCardData } from './data'
|
||||
import { neededImages } from './images'
|
||||
import { templateById } from './templates'
|
||||
import type { Copy } from './templates'
|
||||
|
||||
/** Claude 기획 요청에 넘기는 재료: 템플릿 설명·칸·지금 문구·오늘 날씨. 관리자 서버(/api/plan)가 불러 쓴다 */
|
||||
export async function planContext(templateId: string, current: Copy = {}) {
|
||||
const template = templateById(templateId)
|
||||
if (!template) throw new Error(`템플릿 '${templateId}' 이 없어요`)
|
||||
const d = await loadCardData()
|
||||
const defaults = template.defaults(d)
|
||||
return {
|
||||
template: { id: template.id, name: template.name, about: template.about, how: template.how },
|
||||
fields: template.fields,
|
||||
defaults,
|
||||
current: { ...defaults, ...current },
|
||||
weather: {
|
||||
date: d.dateLabel,
|
||||
headline: d.headline,
|
||||
morningC: d.morningC,
|
||||
maxC: d.maxC,
|
||||
minC: d.minC,
|
||||
rainy: d.rainy,
|
||||
오늘_각_점수: d.gaks.map((g) => ({ code: g.code, name: g.name, score: g.score, summary: g.summary })),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** 이 카드에 아직 없는 그림 (all 이면 다시 그릴 그림 전부). 관리자 서버(/api/gen-image)가 쓴다 */
|
||||
export async function missingImages(templateId: string, copy: Copy = {}, all = false) {
|
||||
return neededImages(templateId, await loadCardData(), copy, all)
|
||||
}
|
||||
|
||||
/** 날씨각 피드 포스트 제목·설명 (npm run card --post 처럼 화면 밖에서 올릴 때) */
|
||||
export async function postText(templateId: string, copy: Copy = {}) {
|
||||
const template = templateById(templateId)
|
||||
if (!template) throw new Error(`템플릿 '${templateId}' 이 없어요`)
|
||||
const d = await loadCardData()
|
||||
return template.post(d, { ...template.defaults(d), ...copy })
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { getWeatherToday, listIndices } from '../api/client'
|
||||
import type { IndexSummary, WeatherSlot } from '../api/client'
|
||||
import { RainType } from '../api/client'
|
||||
|
||||
/** 인스타 카드는 지역을 고르지 않고 서울(중구) 예보 하나로 만든다. 카드에 지역 이름은 나가지 않는다 */
|
||||
export const BASE_REGION = '1114000000'
|
||||
|
||||
/** 템플릿이 쓰는 그날 데이터. 웹 화면과 대화로 만드는 이미지가 같은 값을 쓴다 */
|
||||
export type CardData = {
|
||||
regionCode: string
|
||||
regionName: string
|
||||
day: string
|
||||
/** '10.21 화' */
|
||||
dateLabel: string
|
||||
headline: string
|
||||
top3: IndexSummary[]
|
||||
/** 오늘 각 전체 (점수 높은 순) — 날씨 타로가 카드로 쓴다 */
|
||||
gaks: IndexSummary[]
|
||||
morningC: number
|
||||
maxC: number
|
||||
minC: number
|
||||
rainy: boolean
|
||||
}
|
||||
|
||||
const WEEKDAY = ['일', '월', '화', '수', '목', '금', '토']
|
||||
|
||||
export function dateLabel(day: string) {
|
||||
const d = day ? new Date(`${day}T00:00:00+09:00`) : new Date()
|
||||
return `${d.getMonth() + 1}.${d.getDate()} ${WEEKDAY[d.getDay()]}`
|
||||
}
|
||||
|
||||
/** 아침 6시~밤 9시 예보로 아침 기온·낮 최고·비 여부 */
|
||||
function temps(slots: WeatherSlot[]) {
|
||||
const hour = (s: WeatherSlot) => new Date(s.at).getHours()
|
||||
const withTemp = slots.filter((s) => s.temp_c != null)
|
||||
const day = withTemp.filter((s) => hour(s) >= 6 && hour(s) <= 21)
|
||||
const t = day.length ? day : withTemp
|
||||
const values = t.map((s) => s.temp_c as number)
|
||||
const morning = t.find((s) => hour(s) === 6) ?? t[0]
|
||||
return {
|
||||
morningC: Math.round(morning?.temp_c ?? 0),
|
||||
maxC: Math.round(Math.max(...values)),
|
||||
minC: Math.round(Math.min(...values)),
|
||||
rainy: t.some((s) => (s.rain_type != null && s.rain_type !== RainType.NONE) || (s.rain_prob ?? 0) >= 60),
|
||||
}
|
||||
}
|
||||
|
||||
type Indices = NonNullable<Awaited<ReturnType<typeof listIndices>>['data']>
|
||||
type Weather = NonNullable<Awaited<ReturnType<typeof getWeatherToday>>['data']>
|
||||
|
||||
/** 날씨각 API 는 실패를 200 + result.success=false 로 알린다 */
|
||||
function okOrThrow<T extends { result?: { success?: boolean; desc?: string } }>(data: T | undefined, what: string): T {
|
||||
if (!data || data.result?.success === false) throw new Error(`${what} 을(를) 받지 못했어요 (${data?.result?.desc ?? '응답 없음'})`)
|
||||
return data
|
||||
}
|
||||
const fetchIndices = (region: string) => listIndices({ query: { region } }).then((r) => okOrThrow(r.data, '오늘의 각'))
|
||||
const fetchWeather = (region: string) => getWeatherToday({ query: { region } }).then((r) => okOrThrow(r.data, '오늘 예보'))
|
||||
|
||||
function buildCardData(regionCode: string, indices: Indices, weather: Weather): CardData {
|
||||
const day = weather.day ?? ''
|
||||
return {
|
||||
regionCode,
|
||||
regionName: weather.region_name ?? '',
|
||||
day,
|
||||
dateLabel: dateLabel(day),
|
||||
headline: weather.headline ?? '',
|
||||
top3: indices.top3 ?? [],
|
||||
gaks: [...(indices.items ?? [])].sort((a, b) => b.score - a.score),
|
||||
...temps(weather.slots ?? []),
|
||||
}
|
||||
}
|
||||
|
||||
/** 화면 밖(기획 요청)에서 같은 데이터를 받을 때 */
|
||||
export async function loadCardData(regionCode = BASE_REGION) {
|
||||
const [indices, weather] = await Promise.all([fetchIndices(regionCode), fetchWeather(regionCode)])
|
||||
return buildCardData(regionCode, indices, weather)
|
||||
}
|
||||
|
||||
export function useCardData(regionCode: string) {
|
||||
const indices = useQuery({ queryKey: ['cards', 'indices', regionCode], queryFn: () => fetchIndices(regionCode), enabled: !!regionCode })
|
||||
const weather = useQuery({ queryKey: ['cards', 'weather', regionCode], queryFn: () => fetchWeather(regionCode), enabled: !!regionCode })
|
||||
const error = indices.error ?? weather.error
|
||||
if (!indices.data || !weather.data) return { data: null, error, loading: indices.isLoading || weather.isLoading }
|
||||
return { data: buildCardData(regionCode, indices.data, weather.data), error, loading: false }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import defs from '../../../backend/seed/index_definition.json'
|
||||
|
||||
/** 날씨 타로 카드 덱 = 날씨각 각 카드 (서비스와 같은 목록) */
|
||||
export type GakCard = { code: string; name: string; icon: string; meaning: string }
|
||||
export const GAK_DECK: GakCard[] = defs.map((g) => ({ code: g.code, name: g.name, icon: g.icon, meaning: g.description }))
|
||||
export const gakByCode = (code?: string) => GAK_DECK.find((g) => g.code === code)
|
||||
|
||||
// 각 카드 앞면 그림 (Codex, npm run gen-image -- gak-card <code>). 없으면 각 아이콘
|
||||
const ART = import.meta.glob<string>('../assets/gak-card/*.webp', { eager: true, import: 'default' })
|
||||
export const gakArt = (code?: string) => (code ? ART[`../assets/gak-card/${code}.webp`] : undefined)
|
||||
@@ -0,0 +1,2 @@
|
||||
/** 카드 아이콘: 서비스 각·날씨 아이콘(/icons, ../frontend/public/icons) */
|
||||
export const iconUrl = (name: string) => `/icons/${name}.png`
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { CardData } from './data'
|
||||
import { gakArt } from './gaks'
|
||||
import { hasTarotBg } from './templates'
|
||||
import { ootdBand, ootdOutfits } from './ootd'
|
||||
import type { Copy } from './templates'
|
||||
|
||||
export type ImageNeed = { kind: string; ids: string[] }
|
||||
|
||||
/** 이 카드에 필요한 그림 중 아직 없는 것 (all 이면 전부). kind 는 image-prompts/<kind>.json, 그날 필요한 것만 Codex로 만든다. 타로는 그날 뽑힌 각 카드 그림 */
|
||||
export function neededImages(templateId: string, d: CardData, copy: Copy, all = false): ImageNeed[] {
|
||||
if (templateId === 'ootd') {
|
||||
const style = copy.style || 'casual'
|
||||
const band = ootdBand(d.maxC).id
|
||||
const ids = ootdOutfits(d.maxC, style)
|
||||
.filter((o) => all || !o.image)
|
||||
.map((o) => `${band}-${o.persona}-${style}`)
|
||||
return ids.length ? [{ kind: 'ootd', ids }] : []
|
||||
}
|
||||
if (templateId === 'tarot') {
|
||||
const out: ImageNeed[] = []
|
||||
const ids = ['c1', 'c2', 'c3'].map((k) => copy[k]).filter((id) => id && (all || !gakArt(id)))
|
||||
if (ids.length) out.push({ kind: 'gak-card', ids })
|
||||
// 대주제 배경은 한 번만 만들고 다시 쓴다
|
||||
if (copy.skin && (all || !hasTarotBg(copy.skin))) out.push({ kind: 'tarot-bg', ids: [copy.skin] })
|
||||
return out
|
||||
}
|
||||
return []
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import spec from '../../image-prompts/ootd.json'
|
||||
|
||||
/** 낮 최고기온 구간 × 스타일 × 사람별 옷. 옷 목록·카드 글자는 image-prompts/ootd.json 한 곳에서 정한다.
|
||||
* 그림은 src/assets/ootd/<구간>-<사람>-<스타일>.webp 가 있으면 자동으로 붙는다 (npm run gen-image -- ootd <구간|스타일>) */
|
||||
export type Outfit = { persona: string; label: string; labels: string[]; outer: string; image?: string }
|
||||
export type OotdBand = { id: string; from: number }
|
||||
|
||||
const IMAGES = import.meta.glob<string>('../assets/ootd/*.webp', { eager: true, import: 'default' })
|
||||
|
||||
type Persona = keyof typeof spec.personas
|
||||
type StyleId = keyof typeof spec.styles
|
||||
const PERSONAS = Object.keys(spec.personas) as Persona[]
|
||||
|
||||
export const OOTD_STYLES = (Object.keys(spec.styles) as StyleId[]).map((id) => ({ id, label: spec.styles[id].label }))
|
||||
export const DEFAULT_STYLE: StyleId = 'casual'
|
||||
const styleOf = (id?: string): StyleId => (id && id in spec.styles ? (id as StyleId) : DEFAULT_STYLE)
|
||||
export const styleLabel = (id?: string) => spec.styles[styleOf(id)].label
|
||||
|
||||
export const OOTD_BANDS: OotdBand[] = spec.bands.map((b) => ({ id: b.id, from: b.from }))
|
||||
|
||||
export function ootdBand(maxC: number) {
|
||||
return OOTD_BANDS.find((b) => maxC >= b.from) ?? OOTD_BANDS[OOTD_BANDS.length - 1]
|
||||
}
|
||||
|
||||
/** 그 구간·스타일의 6명 옷 */
|
||||
/** 그 구간·스타일의 6명 옷. bandId 를 주면 기온 대신 그 구간 (예시 카드용) */
|
||||
export function ootdOutfits(maxC: number, style?: string, bandId?: string): Outfit[] {
|
||||
const band = spec.bands.find((b) => b.id === (bandId || ootdBand(maxC).id))!
|
||||
const st = styleOf(style)
|
||||
return PERSONAS.map((p) => {
|
||||
const o = band.outfits[st][p]
|
||||
return { persona: p, label: spec.personas[p].label, labels: o.labels, outer: o.outer, image: IMAGES[`../assets/ootd/${band.id}-${p}-${st}.webp`] }
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { Copy } from './templates'
|
||||
|
||||
/** 고친 문구를 주소에 싣는 꼴 (/render?copy=...). npm run card --copy 도 같은 꼴을 쓴다 */
|
||||
export function encodeCopy(copy: Copy) {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(copy))
|
||||
return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
export function decodeCopy(value: string | null): Copy {
|
||||
if (!value) return {}
|
||||
try {
|
||||
const bin = atob(value.replace(/-/g, '+').replace(/_/g, '/'))
|
||||
return JSON.parse(new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0))))
|
||||
} catch (e) {
|
||||
console.warn('copy 값을 읽지 못해 기본 문구로 그립니다', e)
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
/** 이미지가 다 그려지고 글꼴이 다 받아진 뒤 */
|
||||
export async function whenPainted(root: HTMLElement) {
|
||||
await document.fonts.ready
|
||||
await Promise.all(
|
||||
Array.from(root.querySelectorAll('img'), (img) => (img.complete ? Promise.resolve() : img.decode().catch(() => undefined))),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import tarotBack from '../assets/tarot-back.webp'
|
||||
import type { CardData } from './data'
|
||||
import { Frame, Lines } from './Frame'
|
||||
import { tidy } from './text'
|
||||
import { DEFAULT_STYLE, ootdBand, ootdOutfits, styleLabel } from './ootd'
|
||||
import { gakArt } from './gaks'
|
||||
|
||||
// 대주제(skin)마다 한 번 만든 배경 그림 (npm run gen-image -- tarot-bg <skin>). 없으면 민무늬 배경
|
||||
const TAROT_BG = import.meta.glob<string>('../assets/tarot-bg/*.webp', { eager: true, import: 'default' })
|
||||
const tarotBg = (skin?: string) => (skin ? TAROT_BG[`../assets/tarot-bg/${skin}.webp`] : undefined)
|
||||
export const hasTarotBg = (skin?: string) => !!tarotBg(skin)
|
||||
import { iconUrl } from './icons'
|
||||
import { toneVars } from './themes'
|
||||
|
||||
|
||||
export type Copy = Record<string, string>
|
||||
export type Field = { key: string; label: string }
|
||||
|
||||
/** 포스트 종류 하나 = 템플릿 하나. 웹 화면과 대화(npm run card)가 같은 템플릿으로 그린다 */
|
||||
export type Template = {
|
||||
id: string
|
||||
name: string
|
||||
about: string
|
||||
/** 이 카드를 어떻게 만드는지 (데이터·계산·문구 규칙). 관리자 화면과 기획 요청에 같이 쓴다 */
|
||||
how: string[]
|
||||
fields: Field[]
|
||||
defaults: (d: CardData) => Copy
|
||||
slides: (d: CardData, c: Copy) => ReactNode[]
|
||||
/** 이대로 올리면 안 되는 이유 (그림 없음 등) */
|
||||
warnings?: (d: CardData, c: Copy) => string[]
|
||||
/** Claude 기획으로 채워지는 템플릿 (화면은 만들기를 눌러야 기획, npm run card 는 기획부터 한다) */
|
||||
autoPlan?: boolean
|
||||
/** 처음 열 때 보여 주는 미리 만든 예시 문구 (그림도 미리 만들어 둠). 만들기를 누르면 그날 카드로 바뀐다 */
|
||||
example?: Copy
|
||||
/** 날씨각 피드 포스트 제목·설명 */
|
||||
post: (d: CardData, c: Copy) => { title: string; caption: string }
|
||||
}
|
||||
|
||||
|
||||
const ootd: Template = {
|
||||
id: 'ootd',
|
||||
name: '오늘의 코디',
|
||||
about: '캐주얼·세미정장·정장·스트릿·꾸안꾸 중 하나 · 20대·30대·40대~ 여자·남자 6장 · 서울 낮 최고기온 구간별',
|
||||
how: [
|
||||
'서울(중구) 오늘 예보의 아침 6시~밤 9시 중 가장 높은 기온으로 7개 구간(28도 이상 · 23 · 17 · 12 · 9 · 5 · 그 아래) 중 하나를 고른다.',
|
||||
'스타일(캐주얼·세미정장·정장·스트릿·꾸안꾸)을 고르면 바로 그 옷으로 바뀐다. Claude 기획은 쓰지 않는다.',
|
||||
'구간 × 스타일 × 사람(20대·30대·40대~ 여자·남자)마다 옷 4가지가 image-prompts/ootd.json에 정해져 있고, 같은 파일의 문장으로 Codex가 그린 그림(src/assets/ootd/<구간>-<사람>-<스타일>.webp)을 붙인다. 그림이 없으면 옷 이름만 나간다.',
|
||||
'카드에 지역 이름은 넣지 않는다.',
|
||||
],
|
||||
fields: [{ key: 'title', label: '제목 (사람·스타일 뒤에 붙음)' }],
|
||||
// 제목은 '20대 여자 세미정장'까지만 (한 줄에 들어가야 함). 제목 칸에 쓴 말은 그 뒤에 붙는다
|
||||
defaults: () => ({ title: '', style: DEFAULT_STYLE }),
|
||||
// 예시: 17~22도 캐주얼 (Codex 그림 6장)
|
||||
example: { style: 'casual', band: 'mild', theme: 'berry' },
|
||||
post: (d, c) => ({ title: `오늘의 코디 · ${styleLabel(c.style)}`, caption: `낮 최고 ${d.maxC}도, 20대부터 40대~까지 오늘 입을 옷을 넘겨 보세요` }),
|
||||
warnings: (d, c) => {
|
||||
const missing = ootdOutfits(d.maxC, c.style).filter((o) => !o.image)
|
||||
const id = `${ootdBand(d.maxC).id}`
|
||||
return missing.length
|
||||
? [`낮 최고 ${d.maxC}도 · ${styleLabel(c.style)}에 ${missing.map((o) => o.label).join(', ')} 옷 그림이 아직 없어요. 옷 이름만 나갑니다. (npm run gen-image -- ootd ${id} ${c.style ?? DEFAULT_STYLE})`]
|
||||
: []
|
||||
},
|
||||
slides: (d, c) =>
|
||||
ootdOutfits(d.maxC, c.style, c.band).map((o, i, all) => (
|
||||
<Frame page={i} total={all.length} theme={c.theme} className="ootd" key={o.persona}>
|
||||
<p className="meta">{d.dateLabel} · 오늘의 코디</p>
|
||||
<h1 className="ootd-title">
|
||||
<Lines text={`*${o.label}* ${styleLabel(c.style)}${c.title ? ` ${c.title}` : ''}`} />
|
||||
</h1>
|
||||
<div className="ootd-stage">
|
||||
{o.image ? <img src={o.image} alt="" /> : null}
|
||||
<div className={o.image ? 'ootd-labels' : 'ootd-labels only'}>
|
||||
{o.labels.map((l) => (
|
||||
<span key={l}>{l}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<p className="ootd-weather">
|
||||
<img src={iconUrl(d.rainy ? 'rain' : d.maxC - d.morningC >= 8 ? 'sun_cloud' : 'sun')} alt="" />
|
||||
<span>
|
||||
오늘 아침 <b>{d.morningC}°</b> · 낮 <b>{d.maxC}°</b>
|
||||
{d.rainy ? ' · 비 소식 있어요' : d.maxC - d.morningC >= 8 ? ' · 일교차 커요' : ' · 비 안 와요'}
|
||||
</span>
|
||||
</p>
|
||||
</Frame>
|
||||
)),
|
||||
}
|
||||
|
||||
const tarot: Template = {
|
||||
id: 'tarot',
|
||||
post: (_d, c) => ({ title: c.title.replaceAll('\n', ' ').replaceAll('*', ''), caption: `Q. ${c.question} 1·2·3 중 한 장을 골라 보세요` }),
|
||||
name: '날씨 타로',
|
||||
autoPlan: true,
|
||||
about: '주제를 바꿔 가며 · 3장 중 고르기, 뒷면은 오늘 날씨',
|
||||
how: [
|
||||
'카드는 날씨각의 각 카드다(산책각·빨래각·치맥각… 53장). 타로 덱(컵·펜타클 등)은 쓰지 않는다.',
|
||||
'표지 질문(question)에 1·2·3번 각 카드로 답한다. 소주제마다 질문이 정해져 있다(topics.json questions).',
|
||||
'카드는 오늘 서울(중구) 예보로 점수가 높은 각, 즉 오늘 실제로 하기 좋은 각 가운데 질문과 엮을 수 있는 것을 고른다. 세 장은 서로 다른 각.',
|
||||
'리딩(r)은 진짜 타로 리더 말투로 3문장(70~95자): 그 사람의 겉과 속 → 한 번 꺾기(다만) → 오늘 할 행동 하나(각 카드의 활동). 질문자는 "님", 상대는 "그 사람". 규칙과 좋은·나쁜 예는 scripts/plan.mjs TAROT_TONE.',
|
||||
'행운 포인트(l)는 한 줄: 그 각이 좋은 오늘의 시간·기온·날씨 사실.',
|
||||
'카드 그림은 Codex가 그린 각 카드 그림(그날 뽑힌 카드만 그리고 다시 씀, 없으면 각 아이콘), 카드 이름은 각 이름 그대로.',
|
||||
'질문·카드·리딩은 각각 관리자가 직접 정하거나 Claude에게 맡길 수 있다. 카드를 직접 고르면 Claude는 그 카드로 리딩만 한다.',
|
||||
'지켜야 할 것: 투자 권유(종목·매수·매도·수익)·건강 단정·사고·재난·정치는 쓰지 않는다. 마지막 장에 "재미로"를 남긴다.',
|
||||
'관리자가 주제를 고르고 만들기를 눌러야 만들어진다(화면을 열 때 자동으로 만들지 않는다). 색은 만들 때마다 6가지 테마 중 무작위, 고를 수도 있다.',
|
||||
],
|
||||
fields: [
|
||||
{ key: 'title', label: '표지 제목' },
|
||||
{ key: 'question', label: '질문 (카드가 답할 질문)' },
|
||||
{ key: 'prompt', label: '표지 안내' },
|
||||
...[1, 2, 3].flatMap((n) => [
|
||||
{ key: `n${n}`, label: `${n}번 각 카드` },
|
||||
{ key: `k${n}`, label: `${n}번 키워드 (한 줄)` },
|
||||
{ key: `r${n}`, label: `${n}번 리딩 (질문에 대한 답)` },
|
||||
{ key: `l${n}`, label: `${n}번 행운 포인트` },
|
||||
]),
|
||||
{ key: 'ask', label: '마지막 장 질문' },
|
||||
{ key: 'cta', label: '마지막 장 버튼' },
|
||||
{ key: 'note', label: '마지막 장 안내' },
|
||||
],
|
||||
// 카드 3장은 Claude가 기획해야 채워진다 (autoPlan). 기획 전에는 비워 두고 화면이 가린다
|
||||
// 예시: 연애·썸 (각 카드 그림은 Codex로 미리 그림)
|
||||
example: {
|
||||
title: '오늘의\n썸 타로', question: '지금 썸 타는 그 사람과 오늘 한 발 가까워질까요?', topic: '연애 썸', skin: 'heart', theme: 'berry',
|
||||
c1: 'iced_hot', n1: '뜨아각', i1: 'iced_hot', k1: '커피 사진 한 장',
|
||||
r1: '아침부터 그 사람 생각났죠. 상대도 비슷해요. 다만 마음이 식어서가 아니라 하루 시작이 바빠서 조용한 거예요. 오늘은 커피 사진 한 장만 보내세요. 그 이상은 저녁에.', l1: '아침 8시, 따뜻한 커피가 당기는 날씨',
|
||||
c2: 'walk', n2: '산책각', i2: 'walk', k2: '잠깐 걸을래?',
|
||||
r2: '오늘 그 사람, 님 생각보다 가까이 와 있어요. 겉으론 평소랑 똑같이 굴어도 말 걸 타이밍만 재는 중이거든요. 해 지고 선선해질 때 "잠깐 걸을래?" 한마디면 돼요. 길게 쓰지 마세요.', l2: '저녁 8시, 17도로 걷기 딱 좋아요',
|
||||
c3: 'yajang', n3: '야장각', i3: 'yajang', k3: '둘만 있는 바깥 자리',
|
||||
r3: '오늘 밤 한 발 가까워지는 그림이 보여요. 조건이 하나 있어요, 둘만 있는 자리일 것. 여럿이 모인 데서는 이 사람 티를 안 내거든요. 2차 얘기 나오면 님이 먼저 "밖에 앉자" 하세요.', l3: '밤 9시, 16도로 바깥이 포근해요',
|
||||
},
|
||||
// 만들기 전 빈 카드. 관리자가 주제를 고르고 만들면 Claude가 채운다
|
||||
defaults: () => ({
|
||||
title: '오늘의\n날씨 타로',
|
||||
question: '오늘 나에게 좋은 일이 생길까요?',
|
||||
prompt: '1·2·3 중 한 장을 골라 보세요',
|
||||
...Object.fromEntries([1, 2, 3].flatMap((n) => [[`c${n}`, ''], [`n${n}`, ''], [`i${n}`, 'sun'], [`k${n}`, ''], [`r${n}`, ''], [`l${n}`, '']])),
|
||||
ask: '몇 번 골랐어요?\n*댓글로 알려 주세요*',
|
||||
cta: '내 동네 오늘의 각은\n프로필 링크에서',
|
||||
note: '재미로 보는 날씨 타로 · 카드 뒷면은 실제 날씨로 계산했어요',
|
||||
}),
|
||||
slides: (d, c) => {
|
||||
const backs = (cls: string) =>
|
||||
[1, 2, 3].map((n) => (
|
||||
<div className={`back-card ${cls} card-${n}`} key={n}>
|
||||
<img src={tarotBack} alt="" />
|
||||
<span className="number">{n}</span>
|
||||
</div>
|
||||
))
|
||||
return [
|
||||
<Frame page={0} total={5} theme={c.theme} skin={c.skin} className="tarot-cover" key="cover">
|
||||
{[1, 2, 6].map((n) => (
|
||||
<i className={`deco d${n}`} aria-hidden="true" key={n} />
|
||||
))}
|
||||
<i className="sparkle a" />
|
||||
<i className="sparkle b" />
|
||||
<i className="sparkle c" />
|
||||
<h1 className="cover-title">
|
||||
<Lines text={c.title} />
|
||||
</h1>
|
||||
<p className="cover-question">
|
||||
<b>Q.</b>
|
||||
{c.question}
|
||||
</p>
|
||||
<div className="cover-stage" aria-hidden="true" />
|
||||
{backs('big')}
|
||||
<img className="rabbit" src="/icons/rabbit.png" alt="" />
|
||||
<img className="bear" src="/icons/bear.png" alt="" />
|
||||
<p className="cover-date">
|
||||
{d.dateLabel} · {c.prompt}
|
||||
</p>
|
||||
</Frame>,
|
||||
...[0, 1, 2].map((i) => (
|
||||
<Frame page={i + 1} total={5} theme={c.theme} skin={c.skin} style={toneVars(c.theme, i)} className="tarot-result" key={i}>
|
||||
{tarotBg(c.skin) && <img className="tarot-bg" src={tarotBg(c.skin)} alt="" />}
|
||||
<p className="result-question">
|
||||
<b>Q.</b>
|
||||
<span>{c.question}</span>
|
||||
</p>
|
||||
<div className="result-head">
|
||||
<span className="card-no">{i + 1}번 카드</span>
|
||||
<span className="card-name">{c[`n${i + 1}`]}</span>
|
||||
</div>
|
||||
<div className="result-body">
|
||||
{gakArt(c[`c${i + 1}`]) ? (
|
||||
<img className="card-art" src={gakArt(c[`c${i + 1}`])} alt="" />
|
||||
) : (
|
||||
<div className="card-art card-art-fallback">
|
||||
<img src={iconUrl(c[`i${i + 1}`] || 'sun')} alt="" />
|
||||
</div>
|
||||
)}
|
||||
<div className="result-text">
|
||||
{c[`k${i + 1}`] && <p className="card-keyword">{c[`k${i + 1}`]}</p>}
|
||||
<p className="reading">
|
||||
<Lines text={tidy(c[`r${i + 1}`])} />
|
||||
</p>
|
||||
{c[`l${i + 1}`] && <p className="lucky">{c[`l${i + 1}`]}</p>}
|
||||
</div>
|
||||
</div>
|
||||
<p className="footnote">재미로 보는 날씨 타로 · 카드 뒷면은 실제 날씨로 계산했어요</p>
|
||||
</Frame>
|
||||
)),
|
||||
<Frame page={4} total={5} theme={c.theme} skin={c.skin} className="tarot-cover tarot-closing" key="closing">
|
||||
{[1, 2, 6].map((n) => (
|
||||
<i className={`deco d${n}`} aria-hidden="true" key={n} />
|
||||
))}
|
||||
<h2 className="cover-title">
|
||||
<Lines text={c.ask.replaceAll('*', '')} />
|
||||
</h2>
|
||||
<p className="cover-question">{c.cta.replaceAll('\n', ' ')}</p>
|
||||
<div className="cover-stage" aria-hidden="true" />
|
||||
{backs('big')}
|
||||
<img className="rabbit" src="/icons/rabbit.png" alt="" />
|
||||
<img className="bear" src="/icons/bear.png" alt="" />
|
||||
<p className="cover-date">{c.note}</p>
|
||||
</Frame>,
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
export const TEMPLATES: Template[] = [tarot, ootd]
|
||||
|
||||
export const templateById = (id: string) => TEMPLATES.find((t) => t.id === id)
|
||||
@@ -0,0 +1,3 @@
|
||||
/** 한 글자 어절(그·더·안·못·꼭…)은 다음 어절에 붙여 줄 끝에 혼자 남지 않게 한다 */
|
||||
export const tidy = (text: string) => text.replace(/(^|\s)([가-힣])\s(?=[가-힣])/g, '$1$2\u00a0')
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { CSSProperties } from 'react'
|
||||
|
||||
/** 카드 색 테마. 만들 때마다 하나를 무작위로 고르고, 화면·명령(--color)에서 직접 고를 수도 있다.
|
||||
* tones: 날씨 타로 1·2·3번 카드 색 (hue = 카드 앞면 틀 그림을 돌릴 각도) */
|
||||
type Tone = { accent: string; tint: string; hue: number }
|
||||
export type Theme = { id: string; name: string; paper: string; main: string; deep: string; soft: string; stage: string; second: string; tones: [Tone, Tone, Tone] }
|
||||
|
||||
const ORANGE: Tone = { accent: '#d4552a', tint: '#fff0e5', hue: 0 }
|
||||
const BLUE: Tone = { accent: '#317dc6', tint: '#e6f1ff', hue: 185 }
|
||||
const PURPLE: Tone = { accent: '#6556ac', tint: '#eeeaff', hue: 234 }
|
||||
const GREEN: Tone = { accent: '#1d8a5e', tint: '#e2f6ec', hue: 120 }
|
||||
const PINK: Tone = { accent: '#c43d6d', tint: '#fde6ee', hue: 320 }
|
||||
const MUSTARD: Tone = { accent: '#a87108', tint: '#fff2cc', hue: 25 }
|
||||
|
||||
export const THEMES: Theme[] = [
|
||||
{ id: 'sunset', name: '노을', paper: '#f7fbff', main: '#ff7a45', deep: '#d4552a', soft: '#ffd7bd', stage: '#e1efff', second: '#4f97e3', tones: [ORANGE, BLUE, PURPLE] },
|
||||
{ id: 'sky', name: '하늘', paper: '#f4f9ff', main: '#4f97e3', deep: '#2b6cb8', soft: '#cfe3fb', stage: '#e3efff', second: '#ff7a45', tones: [BLUE, GREEN, PURPLE] },
|
||||
{ id: 'mint', name: '민트', paper: '#f4fbf8', main: '#2fbf87', deep: '#1d8a5e', soft: '#c8f0de', stage: '#dff5ea', second: '#4f97e3', tones: [GREEN, BLUE, ORANGE] },
|
||||
{ id: 'berry', name: '베리', paper: '#fff7fa', main: '#ef6a96', deep: '#c43d6d', soft: '#fbd0de', stage: '#fde6ee', second: '#8b7be0', tones: [PINK, PURPLE, ORANGE] },
|
||||
{ id: 'lemon', name: '레몬', paper: '#fffbef', main: '#f5b82e', deep: '#a87108', soft: '#ffe7a3', stage: '#fff2cc', second: '#2fbf87', tones: [MUSTARD, GREEN, BLUE] },
|
||||
{ id: 'lavender', name: '라벤더', paper: '#f8f6ff', main: '#8b7be0', deep: '#6556ac', soft: '#ddd6fb', stage: '#eeeaff', second: '#ef6a96', tones: [PURPLE, PINK, BLUE] },
|
||||
]
|
||||
|
||||
export const themeById = (id?: string) => THEMES.find((t) => t.id === id) ?? THEMES[0]
|
||||
|
||||
export const randomTheme = (except?: string) => {
|
||||
const pool = THEMES.filter((t) => t.id !== except)
|
||||
return pool[Math.floor(Math.random() * pool.length)].id
|
||||
}
|
||||
|
||||
/** .slide 에 거는 색 변수 */
|
||||
export function themeVars(id?: string): CSSProperties {
|
||||
const t = themeById(id)
|
||||
return { '--paper': t.paper, '--orange': t.main, '--rust': t.deep, '--soft': t.soft, '--stage': t.stage, '--blue': t.second } as CSSProperties
|
||||
}
|
||||
|
||||
export function toneVars(id: string | undefined, i: number): CSSProperties {
|
||||
const tone = themeById(id).tones[i]
|
||||
return { '--accent': tone.accent, '--tint': tone.tint, '--hue': `${tone.hue}deg` } as CSSProperties
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import spec from '../../topics.json'
|
||||
|
||||
/** 날씨 타로 주제(대주제 > 소주제). 대주제마다 꾸밈(skin)·기본 색·먼저 고를 아이콘이 정해져 있다 (topics.json) */
|
||||
export type Category = (typeof spec.categories)[number]
|
||||
export const CATEGORIES: Category[] = spec.categories
|
||||
|
||||
/** '이별', '연애 이별', '연애' 처럼 들어온 주제에서 대주제를 찾는다 */
|
||||
export function categoryOf(topic: string) {
|
||||
const t = topic.trim()
|
||||
return CATEGORIES.find((c) => t.includes(c.name) || c.subtopics.some((s) => t.includes(s)))
|
||||
}
|
||||
|
||||
/** 그 주제의 타로 질문 (소주제 질문, 없으면 대주제 질문) */
|
||||
export function questionOf(topic: string) {
|
||||
const c = categoryOf(topic)
|
||||
if (!c) return ''
|
||||
const sub = c.subtopics.find((x) => topic.includes(x))
|
||||
const q = c.questions as Record<string, string | undefined>
|
||||
return q[sub ?? ''] ?? q[''] ?? ''
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
@import 'tailwindcss';
|
||||
|
||||
/* 관리자 화면: 밝은 사무실에서 오래 보는 작업 화면. 브랜드 색은 선택·주요 버튼에만 */
|
||||
@theme {
|
||||
--color-ink: #28304a;
|
||||
--color-ink-soft: #4a5470;
|
||||
--color-muted: #6a7390;
|
||||
--color-line: #dfe6f0;
|
||||
--color-panel: #ffffff;
|
||||
--color-page: #f3f6fb;
|
||||
--color-rail: #eaf0f8;
|
||||
--color-orange: #ff7a45;
|
||||
--color-rust: #c94c22;
|
||||
--color-rust-soft: #fff1e8;
|
||||
--color-warn: #8a5a0c;
|
||||
--color-warn-soft: #fff6df;
|
||||
--color-bad: #b4322e;
|
||||
--color-bad-soft: #fdecea;
|
||||
--font-sans: 'Pretendard Variable', Pretendard, system-ui, sans-serif;
|
||||
--font-brand: Jua, 'Pretendard Variable', sans-serif;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root {
|
||||
height: 100%;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--color-page);
|
||||
color: var(--color-ink);
|
||||
font-family: var(--font-sans);
|
||||
font-size: 14px;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
::selection {
|
||||
background: #ffd9c4;
|
||||
color: var(--color-ink);
|
||||
}
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--color-orange);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
textarea,
|
||||
input {
|
||||
caret-color: var(--color-rust);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import './cards/cards.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>,
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
import { NavLink, Outlet } from 'react-router'
|
||||
|
||||
const NAV = [
|
||||
{ to: '/', label: '인스타 카드', end: true },
|
||||
{ to: '/history', label: '만든 카드', end: false },
|
||||
]
|
||||
|
||||
export function AdminLayout() {
|
||||
return (
|
||||
<div className="flex min-h-full flex-col">
|
||||
<header className="sticky top-0 z-10 border-b border-line bg-rail/95 backdrop-blur-sm">
|
||||
<div className="mx-auto flex h-14 max-w-[1440px] items-center gap-6 px-4 sm:px-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="relative block size-5 rounded-full bg-orange shadow-[0_2px_0_var(--color-rust)]" aria-hidden="true" />
|
||||
<span className="font-brand text-[21px] leading-none">날씨각</span>
|
||||
<span className="ml-1 rounded-md bg-panel px-1.5 py-0.5 text-[11px] font-semibold text-ink-soft">관리자</span>
|
||||
</div>
|
||||
<nav className="flex gap-1">
|
||||
{NAV.map((n) => (
|
||||
<NavLink
|
||||
key={n.to}
|
||||
to={n.to}
|
||||
end={n.end}
|
||||
className={({ isActive }) =>
|
||||
`rounded-lg px-3 py-1.5 text-[14px] font-semibold transition-colors duration-150 ${isActive ? 'bg-panel text-ink shadow-[0_1px_2px_#28304a14]' : 'text-ink-soft hover:bg-panel/60'}`
|
||||
}
|
||||
>
|
||||
{n.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
<main className="min-w-0 flex-1">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,851 @@
|
||||
import { domToJpeg } from 'modern-screenshot'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useSearchParams } from 'react-router'
|
||||
import { API_BASE_URL } from '../api/setup'
|
||||
import { BASE_REGION, useCardData } from '../cards/data'
|
||||
import type { CardData } from '../cards/data'
|
||||
import { encodeCopy, whenPainted } from '../cards/share'
|
||||
import { TEMPLATES, templateById } from '../cards/templates'
|
||||
import { THEMES, randomTheme, themeById } from '../cards/themes'
|
||||
import { CATEGORIES, categoryOf, questionOf } from '../cards/topics'
|
||||
import { GAK_DECK, gakByCode } from '../cards/gaks'
|
||||
import type { IndexSummary } from '../api/client'
|
||||
import { neededImages } from '../cards/images'
|
||||
import { DEFAULT_STYLE, OOTD_STYLES } from '../cards/ootd'
|
||||
import type { Copy, Template } from '../cards/templates'
|
||||
|
||||
/** 큰 미리보기 배율: 들어갈 칸의 폭과 화면 높이 중 작은 쪽에 맞춘다 */
|
||||
function useStageScale() {
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const [box, setBox] = useState({ width: 0, height: window.innerHeight })
|
||||
useEffect(() => {
|
||||
const el = ref.current
|
||||
if (!el) return
|
||||
const update = () => setBox({ width: el.clientWidth, height: window.innerHeight })
|
||||
const ro = new ResizeObserver(update)
|
||||
ro.observe(el)
|
||||
window.addEventListener('resize', update)
|
||||
update()
|
||||
return () => {
|
||||
ro.disconnect()
|
||||
window.removeEventListener('resize', update)
|
||||
}
|
||||
}, [])
|
||||
const scale = Math.max(0.2, Math.min(0.62, box.width / 1080, (box.height - 340) / 1350))
|
||||
return { ref, scale }
|
||||
}
|
||||
|
||||
const THUMB = 0.1
|
||||
|
||||
const EDITS_KEY = 'card-edits-v2'
|
||||
|
||||
async function toJpeg(node: HTMLElement) {
|
||||
await whenPainted(node)
|
||||
return domToJpeg(node, { width: 1080, height: 1350, scale: 1, quality: 0.92, backgroundColor: '#f7fbff' })
|
||||
}
|
||||
|
||||
async function saveJpeg(node: HTMLElement, name: string) {
|
||||
const url = await toJpeg(node)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = name
|
||||
a.click()
|
||||
}
|
||||
|
||||
export function CardsPage() {
|
||||
const [params, setParams] = useSearchParams()
|
||||
const template = templateById(params.get('template') ?? '') ?? TEMPLATES[0]
|
||||
const { data, error, loading } = useCardData(BASE_REGION)
|
||||
// 템플릿·지역·날짜마다 고친 문구만 따로 둔다. 데이터가 바뀌면 안 고친 칸은 새 기본값을 따른다
|
||||
// 그림이 새로 생기면 화면이 다시 불러와질 수 있어, 고친 문구는 이 탭이 닫힐 때까지 남긴다
|
||||
const [edits, setEdits] = useState<Record<string, Copy>>(() => {
|
||||
try {
|
||||
// 예전 구성(타로 덱 카드 등)으로 저장된 문구는 버린다: 저장 이름을 바꾸고, 각 카드가 아닌 타로 카드는 뺀다
|
||||
sessionStorage.removeItem('card-edits')
|
||||
const saved: Record<string, Copy> = JSON.parse(sessionStorage.getItem(EDITS_KEY) ?? '{}')
|
||||
return Object.fromEntries(Object.entries(saved).filter(([, c]) => !c.c1 || gakByCode(c.c1)))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
})
|
||||
useEffect(() => {
|
||||
try {
|
||||
sessionStorage.setItem(EDITS_KEY, JSON.stringify(edits))
|
||||
} catch (e) {
|
||||
console.warn('고친 문구를 저장하지 못했어요', e)
|
||||
}
|
||||
}, [edits])
|
||||
const editKey = data ? `${template.id}:${data.day}` : ''
|
||||
const overrides = edits[editKey] ?? {}
|
||||
|
||||
const set = (next: Record<string, string>) => setParams((p) => {
|
||||
for (const [k, v] of Object.entries(next)) p.set(k, v)
|
||||
return p
|
||||
}, { replace: true })
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex max-w-[1440px] flex-col gap-5 px-4 py-5 sm:px-6">
|
||||
<header className="flex flex-wrap items-center justify-between gap-x-6 gap-y-3">
|
||||
<div className="flex min-w-0 flex-col gap-0.5">
|
||||
<h1 className="text-[20px] font-bold tracking-[-0.02em]">인스타 카드</h1>
|
||||
<p className="text-[13px] text-muted">
|
||||
{data ? `${data.dateLabel} 서울 예보로 만들어요. 카드에 지역 이름은 나가지 않아요.` : '오늘 예보를 불러오는 중이에요.'}
|
||||
</p>
|
||||
</div>
|
||||
<div role="tablist" aria-label="템플릿" className="flex flex-wrap gap-1 rounded-xl border border-line bg-panel p-1">
|
||||
{TEMPLATES.map((t) => {
|
||||
const on = t.id === template.id
|
||||
return (
|
||||
<button
|
||||
key={t.id}
|
||||
role="tab"
|
||||
aria-selected={on}
|
||||
title={t.about}
|
||||
onClick={() => set({ template: t.id })}
|
||||
className={`rounded-lg px-4 py-2 text-[14px] font-bold transition-colors duration-150 ${on ? 'bg-ink text-white' : 'text-ink-soft hover:bg-rail'}`}
|
||||
>
|
||||
{t.name}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{error ? (
|
||||
<div role="alert" className="rounded-xl border border-bad/30 bg-bad-soft px-5 py-4 text-[14px] text-bad">
|
||||
날씨각 API({API_BASE_URL})에서 예보를 받지 못했어요. 백엔드가 켜져 있는지, 주소가 맞는지 확인하세요. ({String(error)})
|
||||
</div>
|
||||
) : loading || !data ? (
|
||||
<SlidesSkeleton />
|
||||
) : (
|
||||
<Editor
|
||||
key={editKey}
|
||||
template={template}
|
||||
data={data}
|
||||
overrides={overrides}
|
||||
onEdit={(next) => setEdits((e) => ({ ...e, [editKey]: next }))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Editor({ template, data, overrides, onEdit }: { template: Template; data: CardData; overrides: Copy; onEdit: (c: Copy) => void }) {
|
||||
const defaults = template.defaults(data)
|
||||
const copy = { ...defaults, ...overrides }
|
||||
// 만들기 전에는 미리 만든 예시를 보여 준다 (Claude·Codex 를 부르지 않는다)
|
||||
const made = template.autoPlan ? !!overrides.n1 : overrides.made === '1'
|
||||
const slides = template.slides(data, made || !template.example ? copy : { ...defaults, ...template.example })
|
||||
const warnings = template.warnings?.(data, copy) ?? []
|
||||
const refs = useRef<(HTMLDivElement | null)[]>([])
|
||||
const [busy, setBusy] = useState<number | 'all' | null>(null)
|
||||
const [saveError, setSaveError] = useState('')
|
||||
const { ref: stageRef, scale } = useStageScale()
|
||||
const [current, setCurrent] = useState(0)
|
||||
const [tab, setTab] = useState<'plan' | 'copy' | 'post'>('plan')
|
||||
const [planStatus, setPlanStatus] = useState<PlanState['status']>('idle')
|
||||
const runPlan = useRef<() => void>(() => undefined)
|
||||
const at = Math.min(current, slides.length - 1)
|
||||
|
||||
const fileName = (i: number) => `${data.day}_${template.id}_${i + 1}.jpg`
|
||||
const save = async (indexes: number[], mark: number | 'all') => {
|
||||
setBusy(mark)
|
||||
setSaveError('')
|
||||
try {
|
||||
for (const i of indexes) {
|
||||
const node = refs.current[i]?.firstElementChild as HTMLElement | null
|
||||
if (node) await saveJpeg(node, fileName(i))
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
setSaveError(`JPEG로 바꾸지 못했어요. 새로고침한 뒤 다시 눌러 보세요. (${String(e)})`)
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
// 색은 만들 때마다 무작위로 하나 정한다. 문구와 같이 저장돼 미리보기·JPEG·명령이 같은 색을 쓴다
|
||||
useEffect(() => {
|
||||
if (!overrides.theme) onEdit({ ...overrides, theme: randomTheme() })
|
||||
}, [overrides, onEdit])
|
||||
|
||||
const edited = Object.keys(overrides).filter((k) => overrides[k] !== defaults[k])
|
||||
const command = `npm run card -- ${template.id}${edited.length ? ` --copy ${encodeCopy(Object.fromEntries(edited.map((k) => [k, overrides[k]])))}` : ''}`
|
||||
|
||||
return (
|
||||
<div className="grid items-start gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">
|
||||
<section aria-label="미리보기" className="flex min-w-0 flex-col gap-3">
|
||||
{made && warnings.map((w) => (
|
||||
<p key={w} className="rounded-xl border border-warn/25 bg-warn-soft px-4 py-3 text-[13px] font-medium text-warn">
|
||||
{w}
|
||||
</p>
|
||||
))}
|
||||
{!made && planStatus !== 'idle' && planStatus !== 'done' && <EmptyState template={template} planStatus={planStatus} onRetry={() => runPlan.current()} onMake={() => onEdit({ ...overrides, made: '1' })} />}
|
||||
{!made && (planStatus === 'idle' || planStatus === 'done') && (
|
||||
<p className="self-center rounded-full bg-rail px-3 py-1 text-[12px] font-semibold text-ink-soft">예시예요 · 오른쪽에서 고르고 '만들기'를 누르면 오늘 카드를 새로 만들어요</p>
|
||||
)}
|
||||
{made && <ImagesBar template={template.id} copy={copy} auto missing={neededImages(template.id, data, copy)} />}
|
||||
<div ref={stageRef} hidden={!made && planStatus !== 'idle' && planStatus !== 'done'} className="flex min-w-0 flex-col items-center gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<StepButton label="이전 장" disabled={at === 0} onClick={() => setCurrent(at - 1)} dir="prev" />
|
||||
<div className="relative overflow-hidden rounded-xl bg-panel shadow-[0_1px_2px_#28304a14,0_10px_30px_#28304a14]" style={{ width: 1080 * scale, height: 1350 * scale }}>
|
||||
<div style={{ width: 1080, height: 1350, transform: `scale(${scale})`, transformOrigin: '0 0' }}>{slides[at]}</div>
|
||||
</div>
|
||||
<StepButton label="다음 장" disabled={at === slides.length - 1} onClick={() => setCurrent(at + 1)} dir="next" />
|
||||
</div>
|
||||
<div className="flex items-center gap-3 text-[13px] text-muted">
|
||||
<span className="tabular-nums">
|
||||
{at + 1} / {slides.length}
|
||||
</span>
|
||||
<button onClick={() => save([at], at)} disabled={busy !== null} className="rounded-md px-2 py-1 font-semibold text-ink-soft transition-colors duration-150 hover:bg-rail disabled:opacity-40">
|
||||
{busy === at ? '만드는 중…' : '이 장 JPEG'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<ol aria-label="모든 장" hidden={!made && planStatus !== 'idle' && planStatus !== 'done'} className="m-0 flex list-none flex-wrap justify-center gap-2 p-1">
|
||||
{slides.map((slide, i) => (
|
||||
<li key={i} className="shrink-0">
|
||||
<button
|
||||
onClick={() => setCurrent(i)}
|
||||
aria-current={i === at}
|
||||
aria-label={`${i + 1}번째 장 보기`}
|
||||
className={`block overflow-hidden rounded-md outline-offset-2 transition-shadow duration-150 ${i === at ? 'outline-2 outline-ink outline' : 'opacity-80 hover:opacity-100'}`}
|
||||
style={{ width: 1080 * THUMB, height: 1350 * THUMB }}
|
||||
>
|
||||
<div ref={(el) => { refs.current[i] = el }} style={{ width: 1080, height: 1350, transform: `scale(${THUMB})`, transformOrigin: '0 0', pointerEvents: 'none' }}>
|
||||
{slide}
|
||||
</div>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<aside className="flex min-w-0 flex-col rounded-2xl border border-line bg-panel lg:sticky lg:top-[72px] lg:max-h-[calc(100vh-88px)]">
|
||||
<div role="tablist" aria-label="편집" className="flex shrink-0 gap-1 border-b border-line p-2">
|
||||
{(
|
||||
[
|
||||
['plan', '기획·색'],
|
||||
['copy', '문구'],
|
||||
['post', '확인·내보내기'],
|
||||
] as const
|
||||
).map(([id, label]) => (
|
||||
<button
|
||||
key={id}
|
||||
role="tab"
|
||||
aria-selected={tab === id}
|
||||
onClick={() => setTab(id)}
|
||||
className={`flex-1 rounded-lg px-2 py-2 text-[13px] font-bold transition-colors duration-150 ${tab === id ? 'bg-rail text-ink' : 'text-muted hover:text-ink'}`}
|
||||
>
|
||||
{label}
|
||||
{id === 'copy' && template.fields.some((f) => edited.includes(f.key)) && <span className="ml-1 text-rust">·</span>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-col gap-6 overflow-y-auto p-5">
|
||||
<div hidden={tab !== 'plan'} className="flex flex-col gap-6">
|
||||
{template.id === 'ootd' ? (
|
||||
<StylePicker value={copy.style} onChange={(style) => onEdit({ ...overrides, style })} onMake={() => onEdit({ ...overrides, made: '1' })} made={made} />
|
||||
) : (
|
||||
<PlanBox template={template} current={copy} gaks={data.gaks} onStatus={setPlanStatus} registerRun={(fn) => { runPlan.current = fn }} onPlanned={(c) => { onEdit({ ...overrides, ...c }); setTab('copy') }} />
|
||||
)}
|
||||
<ThemePicker value={copy.theme} onChange={(theme) => onEdit({ ...overrides, theme })} />
|
||||
</div>
|
||||
<section hidden={tab !== 'copy'} className="flex flex-col gap-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-[15px] font-bold">문구</h2>
|
||||
{edited.length > 0 && (
|
||||
<button onClick={() => onEdit({})} className="text-[12px] font-semibold text-rust hover:underline underline-offset-2">
|
||||
전부 기본 문구로
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="-mt-2 text-[12px] leading-relaxed text-muted">줄을 바꾸면 카드에서도 줄이 바뀌어요. *별표* 사이 글자는 강조색으로 나와요.</p>
|
||||
{template.fields.map((f) => {
|
||||
const changed = edited.includes(f.key)
|
||||
return (
|
||||
<label key={f.key} className="flex flex-col gap-1.5">
|
||||
<span className="flex items-center gap-2 text-[12px] font-semibold text-ink-soft">
|
||||
{f.label}
|
||||
{changed && <span className="rounded bg-rust-soft px-1.5 py-px text-[11px] text-rust">고침</span>}
|
||||
</span>
|
||||
<textarea
|
||||
id={`copy-${f.key}`}
|
||||
rows={Math.max(1, copy[f.key].split('\n').length)}
|
||||
value={copy[f.key]}
|
||||
onChange={(e) => onEdit({ ...overrides, [f.key]: e.target.value })}
|
||||
className="resize-none rounded-lg border border-line bg-page px-3 py-2 text-[14px] leading-relaxed outline-none transition-colors duration-150 focus:border-ink-soft focus:bg-panel"
|
||||
/>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</section>
|
||||
|
||||
<div hidden={tab !== 'post'} className="flex flex-col gap-6">
|
||||
<section className="flex flex-col gap-3">
|
||||
<h2 className="text-[15px] font-bold">올리기 전에 확인</h2>
|
||||
<dl className="grid grid-cols-[72px_1fr] gap-x-3 gap-y-2 text-[13px]">
|
||||
<dt className="text-muted">기준 예보</dt>
|
||||
<dd className="m-0">
|
||||
{data.regionName} · {data.dateLabel} (카드에는 안 나감)
|
||||
</dd>
|
||||
<dt className="text-muted">각 순위</dt>
|
||||
<dd className="m-0">{data.top3.map((g, i) => `${i + 1}. ${g.name} ${g.score}점`).join(' ')}</dd>
|
||||
<dt className="text-muted">기온</dt>
|
||||
<dd className="m-0">
|
||||
아침 {data.morningC}° · 낮 최고 {data.maxC}° · 최저 {data.minC}°{data.rainy ? ' · 비 소식' : ''}
|
||||
</dd>
|
||||
<dt className="text-muted">예보 한 줄</dt>
|
||||
<dd className="m-0">{data.headline || '없음'}</dd>
|
||||
</dl>
|
||||
<button
|
||||
onClick={() => save(slides.map((_, i) => i), 'all')}
|
||||
disabled={busy !== null}
|
||||
className="mt-1 rounded-xl bg-orange px-4 py-3 text-[14px] font-bold text-ink shadow-[0_2px_0_var(--color-rust)] transition-[transform,background-color] duration-150 hover:bg-[#ff8b5c] active:translate-y-px disabled:opacity-50"
|
||||
>
|
||||
{busy === 'all' ? '만드는 중…' : `${slides.length}장 모두 JPEG로 내려받기`}
|
||||
</button>
|
||||
{saveError && (
|
||||
<p role="alert" className="text-[12px] text-bad">
|
||||
{saveError}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<PostBox
|
||||
disabled={busy !== null || !made}
|
||||
onPost={async (publish) => {
|
||||
const images = []
|
||||
for (const i of slides.map((_, k) => k)) {
|
||||
const node = refs.current[i]?.firstElementChild as HTMLElement | null
|
||||
if (node) images.push(await toJpeg(node))
|
||||
}
|
||||
const { title, caption } = template.post(data, copy)
|
||||
const res = await fetch('/api/post', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ template: template.id, topic: copy.topic ?? null, title, caption, texts: copy, images, publish }),
|
||||
})
|
||||
const body = await res.json()
|
||||
if (!res.ok || body.result?.success === false) throw new Error(body.error ?? body.result?.desc ?? `HTTP ${res.status}`)
|
||||
return body as { card_id: number; status: number; post_id?: number }
|
||||
}}
|
||||
/>
|
||||
<CommandBox command={command} />
|
||||
<HowBox template={template} />
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type PlanState = { status: 'idle' } | { status: 'busy'; again: boolean } | { status: 'done'; topic: string } | { status: 'error'; message: string }
|
||||
|
||||
/** 주제를 넣거나 비워 두고 Claude에게 기획을 맡긴다. 결과는 문구 칸에 그대로 들어가 고칠 수 있다 */
|
||||
type Mode = 'claude' | 'custom'
|
||||
|
||||
/** 직접 / Claude 고르기 */
|
||||
function ModeSwitch({ label, value, onChange }: { label: string; value: Mode; onChange: (m: Mode) => void }) {
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<span className="text-[13px] font-semibold text-ink">{label}</span>
|
||||
<div role="radiogroup" aria-label={label} className="flex rounded-lg border border-line bg-page p-0.5">
|
||||
{(
|
||||
[
|
||||
['claude', 'Claude에게'],
|
||||
['custom', '직접'],
|
||||
] as const
|
||||
).map(([m, text]) => (
|
||||
<button
|
||||
key={m}
|
||||
role="radio"
|
||||
aria-checked={value === m}
|
||||
onClick={() => onChange(m)}
|
||||
className={`rounded-md px-2.5 py-1 text-[12px] font-semibold transition-colors duration-150 ${value === m ? 'bg-ink text-white' : 'text-ink-soft hover:text-ink'}`}
|
||||
>
|
||||
{text}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 각 카드 53장 중 3장을 순서대로 고른다. 오늘 점수 높은 순 */
|
||||
function CardPicker({ gaks, picked, onChange }: { gaks: IndexSummary[]; picked: string[]; onChange: (codes: string[]) => void }) {
|
||||
const [q, setQ] = useState('')
|
||||
const score = new Map(gaks.map((g) => [g.code, g.score]))
|
||||
const deck = [...GAK_DECK].sort((a, b) => (score.get(b.code) ?? -1) - (score.get(a.code) ?? -1)).filter((g) => !q || g.name.includes(q))
|
||||
const toggle = (code: string) => onChange(picked.includes(code) ? picked.filter((c) => c !== code) : picked.length < 3 ? [...picked, code] : picked)
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<input
|
||||
id="card-search"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder={`각 이름으로 찾기 · ${picked.length}/3장 골랐어요`}
|
||||
className="rounded-lg border border-line bg-page px-3 py-1.5 text-[13px] outline-none focus:border-ink-soft focus:bg-panel"
|
||||
/>
|
||||
<ul className="m-0 grid max-h-64 list-none grid-cols-3 gap-1.5 overflow-y-auto p-0.5">
|
||||
{deck.map((g) => {
|
||||
const at = picked.indexOf(g.code)
|
||||
return (
|
||||
<li key={g.code}>
|
||||
<button
|
||||
onClick={() => toggle(g.code)}
|
||||
aria-pressed={at >= 0}
|
||||
title={g.meaning}
|
||||
className={`relative flex w-full flex-col items-center gap-0.5 rounded-lg border px-1 py-1.5 text-center transition-colors duration-150 ${at >= 0 ? 'border-ink bg-rail' : 'border-line bg-page hover:border-ink-soft'}`}
|
||||
>
|
||||
{at >= 0 && <span className="absolute top-1 left-1 grid size-4 place-items-center rounded-full bg-ink text-[10px] font-bold text-white">{at + 1}</span>}
|
||||
<img src={`/icons/${g.icon}.png`} alt="" className="size-7 object-contain" />
|
||||
<span className="text-[11px] leading-tight font-semibold">{g.name}</span>
|
||||
<span className="text-[11px] text-muted tabular-nums">{score.has(g.code) ? `오늘 ${score.get(g.code)}점` : '오늘 없음'}</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PlanBox({ template, current, gaks, onStatus, registerRun, onPlanned }: { template: Template; current: Copy; gaks: IndexSummary[]; onStatus: (s: PlanState['status']) => void; registerRun: (fn: () => void) => void; onPlanned: (c: Copy) => void }) {
|
||||
const [topic, setTopic] = useState('')
|
||||
const [feedback, setFeedback] = useState('')
|
||||
const [state, setState] = useState<PlanState>({ status: 'idle' })
|
||||
const [questionMode, setQuestionMode] = useState<Mode>('claude')
|
||||
const [cardMode, setCardMode] = useState<Mode>('claude')
|
||||
const [readingMode, setReadingMode] = useState<Mode>('claude')
|
||||
const [question, setQuestion] = useState('')
|
||||
const [picked, setPicked] = useState<string[]>([])
|
||||
const planned = state.status === 'done'
|
||||
const busy = state.status === 'busy'
|
||||
const busyAgain = state.status === 'busy' && state.again
|
||||
const tarot = template.id === 'tarot'
|
||||
const needClaude = !tarot || questionMode === 'claude' || cardMode === 'claude' || readingMode === 'claude'
|
||||
const ready = !tarot || ((questionMode === 'claude' || question.trim() !== '') && (cardMode === 'claude' || picked.length === 3))
|
||||
useEffect(() => onStatus(state.status), [state.status, onStatus])
|
||||
|
||||
// 주제를 고르면 그 주제의 질문을 직접 쓰기 칸에 미리 넣어 둔다
|
||||
const pickTopic = (t: string) => {
|
||||
setTopic(t)
|
||||
if (questionOf(t)) setQuestion(questionOf(t))
|
||||
}
|
||||
|
||||
/** 모두 직접일 때: Claude 없이 고른 카드·질문으로 카드를 채우고, 리딩은 문구 탭에서 쓴다 */
|
||||
const makeByHand = () => {
|
||||
const cat = categoryOf(topic)
|
||||
const sub = cat?.subtopics.find((x) => topic.includes(x))
|
||||
const copy: Copy = { title: `오늘의\n${sub ?? cat?.name ?? ''} 타로`.replace('\n 타로', '\n날씨 타로'), question, topic, skin: cat?.skin ?? 'star' }
|
||||
picked.forEach((code, i) => {
|
||||
const g = gakByCode(code)!
|
||||
Object.assign(copy, { [`c${i + 1}`]: g.code, [`n${i + 1}`]: g.name, [`i${i + 1}`]: g.icon, [`r${i + 1}`]: '', [`l${i + 1}`]: '' })
|
||||
})
|
||||
onPlanned(copy)
|
||||
setState({ status: 'done', topic: topic || '직접' })
|
||||
}
|
||||
|
||||
const run = async (again: boolean) => {
|
||||
setState({ status: 'busy', again })
|
||||
try {
|
||||
const res = await fetch('/api/plan', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
template: template.id,
|
||||
topic,
|
||||
feedback: again ? feedback : '',
|
||||
current: again ? current : {},
|
||||
fixed: tarot ? { question: questionMode === 'custom' ? question : undefined, cards: cardMode === 'custom' ? picked : undefined } : undefined,
|
||||
}),
|
||||
})
|
||||
const body = await res.json()
|
||||
if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`)
|
||||
// 리딩을 직접 쓰기로 했으면 Claude 리딩은 비우고 문구 탭에서 쓴다
|
||||
if (tarot && readingMode === 'custom') for (const k of ['r1', 'r2', 'r3', 'l1', 'l2', 'l3']) body.copy[k] = ''
|
||||
onPlanned(body.copy)
|
||||
if (!topic) setTopic(body.topic)
|
||||
if (again) setFeedback('')
|
||||
setState({ status: 'done', topic: body.topic })
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
setState({ status: 'error', message: e instanceof Error ? e.message : String(e) })
|
||||
}
|
||||
}
|
||||
|
||||
// 미리보기의 '다시 시도'가 같은 기획을 부른다
|
||||
useEffect(() => registerRun(() => run(false)))
|
||||
|
||||
|
||||
return (
|
||||
<section className="flex flex-col gap-3">
|
||||
<h2 className="text-[15px] font-bold">기획</h2>
|
||||
<TopicChips topic={topic} onPick={pickTopic} />
|
||||
<label className="flex flex-col gap-1.5">
|
||||
<span className="text-[12px] font-semibold text-ink-soft">주제</span>
|
||||
<input
|
||||
id="plan-topic"
|
||||
value={topic}
|
||||
onChange={(e) => setTopic(e.target.value)}
|
||||
placeholder="고르거나 직접 쓰기 (비우면 Claude가 골라요)"
|
||||
className="rounded-lg border border-line bg-page px-3 py-2 text-[14px] outline-none transition-colors duration-150 focus:border-ink-soft focus:bg-panel"
|
||||
/>
|
||||
</label>
|
||||
{tarot && (
|
||||
<div className="flex flex-col gap-3 rounded-xl bg-page p-3">
|
||||
<ModeSwitch label="질문" value={questionMode} onChange={setQuestionMode} />
|
||||
{questionMode === 'custom' && (
|
||||
<input
|
||||
id="plan-question"
|
||||
value={question}
|
||||
onChange={(e) => setQuestion(e.target.value)}
|
||||
placeholder="예: 오늘 누군가와 설레는 일이 생길까요?"
|
||||
className="rounded-lg border border-line bg-panel px-3 py-2 text-[13px] outline-none focus:border-ink-soft"
|
||||
/>
|
||||
)}
|
||||
<ModeSwitch label="카드 3장" value={cardMode} onChange={setCardMode} />
|
||||
{cardMode === 'custom' && <CardPicker gaks={gaks} picked={picked} onChange={setPicked} />}
|
||||
<ModeSwitch label="리딩" value={readingMode} onChange={setReadingMode} />
|
||||
{readingMode === 'custom' && <p className="text-[12px] text-muted">만든 뒤 문구 탭에서 카드마다 리딩·행운 포인트를 직접 써요.</p>}
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
onClick={() => (needClaude ? run(false) : makeByHand())}
|
||||
disabled={busy || !ready}
|
||||
className="rounded-xl bg-ink px-4 py-2.5 text-[14px] font-bold text-white transition-opacity duration-150 hover:opacity-90 disabled:opacity-50"
|
||||
>
|
||||
{busy && !busyAgain ? 'Claude가 만드는 중… (15초쯤)' : needClaude ? '만들기 (Claude가 맡은 부분 기획)' : '만들기'}
|
||||
</button>
|
||||
{!ready && <p className="text-[12px] text-muted">{cardMode === 'custom' && picked.length !== 3 ? `카드를 3장 골라 주세요 (${picked.length}/3)` : '질문을 써 주세요'}</p>}
|
||||
{planned && (
|
||||
<>
|
||||
<p className="text-[12px] text-muted">주제 "{state.topic}"로 문구를 채웠어요. 칸에서 바로 고치거나, 아래에 피드백을 적어 다시 기획하세요.</p>
|
||||
<label className="flex flex-col gap-1.5">
|
||||
<span className="text-[12px] font-semibold text-ink-soft">피드백</span>
|
||||
<textarea
|
||||
id="plan-feedback"
|
||||
rows={2}
|
||||
value={feedback}
|
||||
onChange={(e) => setFeedback(e.target.value)}
|
||||
placeholder="예: 2번 카드를 더 웃기게, 제목은 짧게"
|
||||
className="resize-none rounded-lg border border-line bg-page px-3 py-2 text-[14px] leading-relaxed outline-none transition-colors duration-150 focus:border-ink-soft focus:bg-panel"
|
||||
/>
|
||||
</label>
|
||||
<button
|
||||
onClick={() => run(true)}
|
||||
disabled={busy || !feedback.trim()}
|
||||
className="rounded-xl border border-ink px-4 py-2.5 text-[14px] font-bold text-ink transition-colors duration-150 hover:bg-rail disabled:opacity-40"
|
||||
>
|
||||
{busyAgain ? '다시 기획하는 중…' : '피드백 반영해 다시 기획'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{state.status === 'error' && (
|
||||
<p role="alert" className="text-[12px] text-bad">
|
||||
기획하지 못했어요: {state.message}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 코디는 주제 대신 스타일을 고른다. 누르면 Claude 없이 바로 그 옷으로 바뀐다 */
|
||||
function StylePicker({ value, onChange, onMake, made }: { value?: string; onChange: (id: string) => void; onMake: () => void; made: boolean }) {
|
||||
const current = value ?? DEFAULT_STYLE
|
||||
return (
|
||||
<section className="flex flex-col gap-3">
|
||||
<h2 className="text-[15px] font-bold">스타일</h2>
|
||||
<div role="radiogroup" aria-label="코디 스타일" className="flex flex-wrap gap-1.5">
|
||||
{OOTD_STYLES.map((st) => {
|
||||
const on = st.id === current
|
||||
return (
|
||||
<button
|
||||
key={st.id}
|
||||
role="radio"
|
||||
aria-checked={on}
|
||||
onClick={() => onChange(st.id)}
|
||||
className={`rounded-full border px-3 py-1 text-[12px] font-semibold transition-colors duration-150 ${on ? 'border-ink bg-ink text-white' : 'border-line bg-page text-ink hover:border-ink-soft'}`}
|
||||
>
|
||||
{st.label}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{!made && (
|
||||
<button onClick={onMake} className="rounded-xl bg-ink px-4 py-2.5 text-[14px] font-bold text-white hover:opacity-90">
|
||||
만들기 (오늘 옷 그림 6장, Codex)
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
/** 대주제를 누르면 소주제가 펼쳐진다. 누른 주제는 입력칸에 들어가고, 입력칸은 직접 고칠 수 있다 */
|
||||
function TopicChips({ topic, onPick }: { topic: string; onPick: (t: string) => void }) {
|
||||
const active = categoryOf(topic)
|
||||
const chip = (on: boolean) =>
|
||||
`rounded-full border px-3 py-1 text-[12px] font-semibold transition-colors duration-150 ${on ? 'border-ink bg-ink text-white' : 'border-line bg-page text-ink hover:border-ink-soft'}`
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{CATEGORIES.map((c) => (
|
||||
<button key={c.id} onClick={() => onPick(active?.id === c.id && topic === c.name ? '' : c.name)} aria-pressed={active?.id === c.id} className={chip(active?.id === c.id)}>
|
||||
{c.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{active && (
|
||||
<div className="flex flex-wrap gap-1.5 pl-3">
|
||||
{active.subtopics.map((sub) => {
|
||||
const value = `${active.name} ${sub}`
|
||||
return (
|
||||
<button key={sub} onClick={() => onPick(value)} aria-pressed={topic === value} className={chip(topic === value)}>
|
||||
{sub}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ThemePicker({ value, onChange }: { value?: string; onChange: (id: string) => void }) {
|
||||
const current = themeById(value)
|
||||
return (
|
||||
<section className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-[15px] font-bold">색</h2>
|
||||
<button onClick={() => onChange(randomTheme(current.id))} className="rounded-md px-2 py-1 text-[12px] font-semibold text-ink-soft hover:bg-rail">
|
||||
무작위로 바꾸기
|
||||
</button>
|
||||
</div>
|
||||
<div role="radiogroup" aria-label="카드 색" className="flex flex-wrap gap-2">
|
||||
{THEMES.map((t) => {
|
||||
const on = t.id === current.id
|
||||
return (
|
||||
<button
|
||||
key={t.id}
|
||||
role="radio"
|
||||
aria-checked={on}
|
||||
onClick={() => onChange(t.id)}
|
||||
className={`flex items-center gap-2 rounded-full border py-1 pl-1 pr-3 text-[12px] font-semibold transition-colors duration-150 ${on ? 'border-ink bg-ink text-white' : 'border-line bg-page text-ink hover:border-ink-soft'}`}
|
||||
>
|
||||
<span className="flex -space-x-1" aria-hidden="true">
|
||||
<span className="size-5 rounded-full border-2 border-white" style={{ background: t.main }} />
|
||||
<span className="size-5 rounded-full border-2 border-white" style={{ background: t.tones[1].accent }} />
|
||||
<span className="size-5 rounded-full border-2 border-white" style={{ background: t.tones[2].accent }} />
|
||||
</span>
|
||||
{t.name}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function HowBox({ template }: { template: Template }) {
|
||||
return (
|
||||
<details className="group border-t border-line pt-5">
|
||||
<summary className="cursor-pointer list-none text-[15px] font-bold marker:hidden">
|
||||
이 카드는 이렇게 만들어요 <span className="ml-1 text-[12px] font-semibold text-muted group-open:hidden">펼치기</span>
|
||||
</summary>
|
||||
<ul className="mt-3 flex list-disc flex-col gap-2 pl-4 text-[13px] leading-relaxed text-ink-soft">
|
||||
{template.how.map((h) => (
|
||||
<li key={h}>{h}</li>
|
||||
))}
|
||||
</ul>
|
||||
</details>
|
||||
)
|
||||
}
|
||||
|
||||
/** 날씨각 피드에 올리기: 바로 게시하거나, 승인 대기로 저장(나중에 Teams 승인으로 게시) */
|
||||
function PostBox({ disabled, onPost }: { disabled: boolean; onPost: (publish: boolean) => Promise<{ card_id: number; post_id?: number }> }) {
|
||||
const [state, setState] = useState<{ busy?: boolean; done?: string; error?: string }>({})
|
||||
const run = async (publish: boolean) => {
|
||||
setState({ busy: true })
|
||||
try {
|
||||
const r = await onPost(publish)
|
||||
setState({ done: publish ? `날씨각 피드에 올렸어요 (카드 ${r.card_id}, 포스트 ${r.post_id}). 오늘 피드 날씨 바로 아래에 보여요.` : `승인 대기로 저장했어요 (카드 ${r.card_id}).` })
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
setState({ error: e instanceof Error ? e.message : String(e) })
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="flex flex-col gap-2 border-t border-line pt-5">
|
||||
<h2 className="text-[15px] font-bold">날씨각에 올리기</h2>
|
||||
<p className="text-[12px] leading-relaxed text-muted">지금 카드를 이미지로 만들어 오늘 전국 피드에 올려요. 내일 03시에 피드에서 빠져요.</p>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={() => run(true)} disabled={disabled || state.busy} className="flex-1 rounded-xl bg-ink px-4 py-2.5 text-[14px] font-bold text-white hover:opacity-90 disabled:opacity-40">
|
||||
{state.busy ? '올리는 중…' : '지금 올리기'}
|
||||
</button>
|
||||
<button onClick={() => run(false)} disabled={disabled || state.busy} className="rounded-xl border border-ink px-3 py-2.5 text-[13px] font-bold text-ink hover:bg-rail disabled:opacity-40">
|
||||
승인 대기로 저장
|
||||
</button>
|
||||
</div>
|
||||
{state.done && <p className="text-[12px] font-semibold text-ink-soft">{state.done}</p>}
|
||||
{state.error && (
|
||||
<p role="alert" className="text-[12px] text-bad">
|
||||
올리지 못했어요: {state.error}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function CommandBox({ command }: { command: string }) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(command)
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1500)
|
||||
} catch (e) {
|
||||
console.error('클립보드에 복사하지 못했어요', e)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="text-[15px] font-bold">대화로 만들기</h2>
|
||||
<button onClick={copy} className="rounded-md px-2 py-1 text-[12px] font-semibold text-ink-soft hover:bg-rail">
|
||||
{copied ? '복사했어요' : '복사'}
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-[12px] leading-relaxed text-muted">Claude나 Codex에게 “오늘 날씨 타로 마포구로 만들어 줘”라고 하면 이 명령을 실행해요. admin 폴더에서 직접 실행해도 같은 카드가 나와요.</p>
|
||||
<code className="block overflow-x-auto rounded-lg bg-ink px-3 py-2.5 font-mono text-[12px] leading-relaxed text-white">{command}</code>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
type ImageJob = { status: 'idle' | 'running' | 'done' | 'failed'; total: number; done: number; current: string; log: string[] }
|
||||
|
||||
/** 이 카드에 필요한 그림 중 없는 것만 Codex로 만든다 (그날 필요한 것만, 한 장씩). 다 만들면 미리보기에 자동으로 붙는다 */
|
||||
function ImagesBar({ template, copy, missing, auto }: { template: string; copy: Copy; missing: { kind: string; ids: string[] }[]; auto: boolean }) {
|
||||
const [job, setJob] = useState<ImageJob | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const count = missing.reduce((n, m) => n + m.ids.length, 0)
|
||||
const running = job?.status === 'running'
|
||||
|
||||
useEffect(() => {
|
||||
if (!running) return
|
||||
const t = setInterval(async () => {
|
||||
try {
|
||||
setJob(await (await fetch('/api/gen-image')).json())
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
}, 3000)
|
||||
return () => clearInterval(t)
|
||||
}, [running])
|
||||
|
||||
const autoStarted = useRef(false)
|
||||
const start = async (force: boolean) => {
|
||||
setError('')
|
||||
try {
|
||||
const res = await fetch('/api/gen-image', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ template, copy, force }) })
|
||||
const body = await res.json()
|
||||
if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`)
|
||||
setJob(body)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : String(e))
|
||||
}
|
||||
}
|
||||
|
||||
// 만들기를 누르면 그 카드에 빠진 그림(코디 옷, 타로 각 카드)을 바로 그리기 시작한다 (한 번만)
|
||||
useEffect(() => {
|
||||
if (!auto || autoStarted.current || count === 0 || job) return
|
||||
autoStarted.current = true
|
||||
start(false)
|
||||
})
|
||||
|
||||
if (!running && count === 0 && job?.status !== 'failed') {
|
||||
return (
|
||||
<div className="flex justify-end">
|
||||
<button onClick={() => start(true)} className="rounded-md px-2 py-1 text-[12px] font-semibold text-ink-soft hover:bg-rail">
|
||||
그림 다시 그리기
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-line bg-panel px-4 py-3">
|
||||
<p className="text-[13px] text-ink-soft">
|
||||
{running
|
||||
? `Codex가 그리는 중 ${job.done}/${job.total}${job.current ? ` · ${job.current}` : ''} (한 장에 1~2분)`
|
||||
: job?.status === 'failed'
|
||||
? `그림을 다 만들지 못했어요. ${job.log.at(-1) ?? ''}`
|
||||
: `이 카드에 필요한 그림 ${count}장이 아직 없어요. 지금은 아이콘·옷 이름으로 나와요.`}
|
||||
</p>
|
||||
{!running && (
|
||||
<button onClick={() => start(false)} className="rounded-lg bg-ink px-3 py-2 text-[13px] font-bold text-white hover:opacity-90">
|
||||
Codex로 그림 {count}장 만들기
|
||||
</button>
|
||||
)}
|
||||
{error && <p className="w-full text-[12px] text-bad">{error}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyState({ template, planStatus, onRetry, onMake }: { template: Template; planStatus: PlanState['status']; onRetry: () => void; onMake: () => void }) {
|
||||
const tarot = !!template.autoPlan
|
||||
return (
|
||||
<div className="mx-auto flex aspect-[4/5] w-full max-w-[460px] flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-line bg-panel px-8 text-center">
|
||||
{planStatus === 'busy' ? (
|
||||
<>
|
||||
<span className="size-8 animate-spin rounded-full border-[3px] border-line border-t-ink" aria-hidden="true" />
|
||||
<p className="text-[15px] font-bold">Claude가 질문을 정하고 각 카드를 고르는 중이에요</p>
|
||||
<p className="text-[13px] text-muted">15초쯤 걸려요.</p>
|
||||
</>
|
||||
) : planStatus === 'error' ? (
|
||||
<>
|
||||
<p className="text-[15px] font-bold text-bad">만들지 못했어요</p>
|
||||
<p className="text-[13px] text-muted">Claude 기획 요청이 실패했어요.</p>
|
||||
<button onClick={onRetry} className="rounded-xl bg-ink px-4 py-2.5 text-[14px] font-bold text-white hover:opacity-90">
|
||||
다시 시도
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-[15px] font-bold">아직 만든 카드가 없어요</p>
|
||||
<p className="text-[13px] leading-relaxed text-muted">
|
||||
{tarot ? "오른쪽에서 주제(연애·경제…)를 고르고 '만들기'를 누르면 Claude가 질문과 각 카드 3장을 정해 만들어요." : "오른쪽에서 스타일을 고르고 '만들기'를 누르면 오늘 기온에 맞는 6명의 옷을 Codex가 그려요."}
|
||||
</p>
|
||||
{!tarot && (
|
||||
<button onClick={onMake} className="rounded-xl bg-ink px-4 py-2.5 text-[14px] font-bold text-white hover:opacity-90">
|
||||
만들기
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function StepButton({ label, dir, disabled, onClick }: { label: string; dir: 'prev' | 'next'; disabled: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
aria-label={label}
|
||||
className="grid size-10 shrink-0 place-items-center rounded-full border border-line bg-panel text-ink-soft transition-colors duration-150 hover:border-ink-soft hover:text-ink disabled:opacity-30"
|
||||
>
|
||||
<svg viewBox="0 0 20 20" className="size-4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
|
||||
<path d={dir === 'prev' ? 'M12.5 4.5 7 10l5.5 5.5' : 'M7.5 4.5 13 10l-5.5 5.5'} />
|
||||
</svg>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
function SlidesSkeleton() {
|
||||
return (
|
||||
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_360px]" aria-busy="true">
|
||||
<div className="mx-auto aspect-[4/5] w-full max-w-[460px] animate-pulse rounded-xl bg-rail" />
|
||||
<div className="h-[480px] animate-pulse rounded-2xl bg-rail" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { API_BASE_URL } from '../api/setup'
|
||||
|
||||
type Card = { card_id: number; template: string; topic?: string; title: string; status: 1 | 2 | 3; post_id?: number; created_at: string; published_at?: string; image_urls: string[] }
|
||||
|
||||
const STATUS: Record<Card['status'], [string, string]> = { 1: ['승인 대기', 'bg-warn-soft text-warn'], 2: ['올림', 'bg-rust-soft text-rust'], 3: ['반려', 'bg-rail text-muted'] }
|
||||
const TEMPLATE: Record<string, string> = { tarot: '날씨 타로', ootd: '오늘의 코디' }
|
||||
|
||||
const when = (iso: string) => new Date(iso).toLocaleString('ko-KR', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' })
|
||||
|
||||
/** 만든 카드가 쌓이는 곳. 날씨각 서버(card_set·card_image)에 저장된 것을 보여 주고, 다시 내려받거나 올린다 */
|
||||
export function HistoryPage() {
|
||||
const qc = useQueryClient()
|
||||
const { data, error, isLoading } = useQuery({
|
||||
queryKey: ['cards'],
|
||||
queryFn: async () => {
|
||||
const r = await fetch('/api/cards')
|
||||
const body = await r.json()
|
||||
if (!r.ok || body.result?.success === false) throw new Error(body.error ?? body.result?.desc ?? `HTTP ${r.status}`)
|
||||
return body.items as Card[]
|
||||
},
|
||||
})
|
||||
const [busy, setBusy] = useState<number | null>(null)
|
||||
const act = async (id: number, what: 'publish' | 'reject') => {
|
||||
setBusy(id)
|
||||
try {
|
||||
const r = await fetch(`/api/cards/${id}/${what}`, { method: 'POST' })
|
||||
if (!r.ok) throw new Error((await r.json()).error)
|
||||
await qc.invalidateQueries({ queryKey: ['cards'] })
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
window.alert(`처리하지 못했어요: ${e instanceof Error ? e.message : String(e)}`)
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex max-w-[1440px] flex-col gap-5 px-4 py-5 sm:px-6">
|
||||
<header className="flex flex-col gap-0.5">
|
||||
<h1 className="text-[20px] font-bold tracking-[-0.02em]">만든 카드</h1>
|
||||
<p className="text-[13px] text-muted">'지금 올리기'나 '승인 대기로 저장'을 누른 카드가 날씨각 서버에 쌓여요. 장마다 JPEG로 다시 내려받을 수 있어요.</p>
|
||||
</header>
|
||||
{error && (
|
||||
<div role="alert" className="rounded-xl border border-bad/30 bg-bad-soft px-5 py-4 text-[14px] text-bad">
|
||||
목록을 받지 못했어요: {String(error instanceof Error ? error.message : error)}
|
||||
</div>
|
||||
)}
|
||||
{isLoading && <div className="h-40 animate-pulse rounded-2xl bg-rail" aria-busy="true" />}
|
||||
{data?.length === 0 && <p className="rounded-2xl border border-dashed border-line bg-panel px-5 py-10 text-center text-[14px] text-muted">아직 저장한 카드가 없어요.</p>}
|
||||
<ul className="m-0 flex list-none flex-col gap-3 p-0">
|
||||
{data?.map((c) => {
|
||||
const [label, tone] = STATUS[c.status]
|
||||
return (
|
||||
<li key={c.card_id} className="grid gap-4 rounded-2xl border border-line bg-panel p-4 md:grid-cols-[minmax(0,1fr)_auto]">
|
||||
<div className="flex min-w-0 flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center gap-2 text-[13px]">
|
||||
<span className={`rounded-full px-2 py-0.5 text-[12px] font-bold ${tone}`}>{label}</span>
|
||||
<b className="text-[15px]">{c.title}</b>
|
||||
<span className="text-muted">
|
||||
{TEMPLATE[c.template] ?? c.template}
|
||||
{c.topic ? ` · ${c.topic}` : ''} · 카드 {c.card_id}
|
||||
{c.post_id ? ` · 포스트 ${c.post_id}` : ''}
|
||||
</span>
|
||||
<span className="text-muted">만든 때 {when(c.created_at)}{c.published_at ? ` · 올린 때 ${when(c.published_at)}` : ''}</span>
|
||||
</div>
|
||||
<ol className="m-0 flex list-none gap-2 overflow-x-auto p-0.5">
|
||||
{c.image_urls.map((u, i) => (
|
||||
<li key={u} className="shrink-0">
|
||||
<a href={`${API_BASE_URL}${u}`} download={`card-${c.card_id}-${i + 1}.jpg`} target="_blank" rel="noreferrer" title={`${i + 1}장 내려받기`} className="block overflow-hidden rounded-md outline-offset-2 hover:outline-2 hover:outline-ink">
|
||||
<img src={`${API_BASE_URL}${u}`} alt={`${c.title} ${i + 1}장`} loading="lazy" className="h-[135px] w-[108px] object-cover" />
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col gap-2 md:w-40">
|
||||
<a
|
||||
href={`${API_BASE_URL}${c.image_urls[0] ?? ''}`}
|
||||
download={`card-${c.card_id}-1.jpg`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="rounded-lg border border-line px-3 py-2 text-center text-[13px] font-bold text-ink hover:bg-rail"
|
||||
>
|
||||
이미지 열기
|
||||
</a>
|
||||
{c.status === 1 && (
|
||||
<>
|
||||
<button onClick={() => act(c.card_id, 'publish')} disabled={busy === c.card_id} className="rounded-lg bg-ink px-3 py-2 text-[13px] font-bold text-white hover:opacity-90 disabled:opacity-40">
|
||||
오늘 피드에 올리기
|
||||
</button>
|
||||
<button onClick={() => act(c.card_id, 'reject')} disabled={busy === c.card_id} className="rounded-lg px-3 py-2 text-[13px] font-semibold text-muted hover:bg-rail disabled:opacity-40">
|
||||
반려
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useSearchParams } from 'react-router'
|
||||
import { BASE_REGION, useCardData } from '../cards/data'
|
||||
import { decodeCopy, whenPainted } from '../cards/share'
|
||||
import { templateById } from '../cards/templates'
|
||||
|
||||
/** 카드 한 장만 1080×1350으로. 다 그려지면 <html data-ready="1"> */
|
||||
export function RenderPage() {
|
||||
const [params] = useSearchParams()
|
||||
const template = templateById(params.get('template') ?? '')
|
||||
const slideNo = Number(params.get('slide') ?? '1')
|
||||
const { data, error } = useCardData(params.get('region') ?? BASE_REGION)
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const [ready, setReady] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!data || !ref.current) return
|
||||
let alive = true
|
||||
whenPainted(ref.current).then(() => alive && setReady(true))
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
}, [data])
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.ready = ready ? '1' : ''
|
||||
}, [ready])
|
||||
|
||||
if (!template) return <p>template 값이 없거나 틀렸어요: today · ootd · tarot</p>
|
||||
if (error) return <p>날씨각 API에서 데이터를 받지 못했어요: {String(error)}</p>
|
||||
if (!data) return null
|
||||
const copy = { ...template.defaults(data), ...decodeCopy(params.get('copy')) }
|
||||
const slides = template.slides(data, copy)
|
||||
return (
|
||||
<div ref={ref} style={{ width: 1080, height: 1350 }}>
|
||||
{slides[slideNo - 1] ?? <p>{slides.length}장까지 있어요</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||