@toktokhan-dev/react-web
Version:
A utility library for global use in React Web environments.
1,183 lines (1,150 loc) • 44 kB
TypeScript
import * as react_jsx_runtime from 'react/jsx-runtime';
import * as react from 'react';
import { InputHTMLAttributes, HTMLAttributes, ReactElement, ReactNode } from 'react';
import { DataOrFn } from '@toktokhan-dev/universal';
import { Cookies } from 'react-cookie';
interface UploadTriggerProps extends InputHTMLAttributes<HTMLInputElement> {
/**
* 자식 Element 입니다. number 나 string 이 아닌 jsx element 나 component 를 넣어주세요
*/
children: React.ReactElement;
/**
* @default 'onClick'
* 자식 Element 의 props name 중 트리거 할 이벤트를 지정합니다. 기본값은 'onClick' 입니다.
*/
by?: string;
}
/**
* 웹에서 파일 업로드를 트리거 하는 컴포넌트 입니다.
*
* 자식 element 에 by 로 지정한 이벤트를 트리거 하면 display none 처리 되어있는 input[type="file"] 클릭되어 파일 선택 창이 열립니다.
* UploadTrigger 의 props 는 숨겨져 있는 input 의 prop 으로 전달되기때문에,
* UploadTrigger 의 onChange prop 으로 선택된 파일에 접근이 가능합니다.
*
* @category Component
*
* @example
*
* ```tsx
* <UploadTrigger by="onClick" onChange={(e) => console.log(e.target.files?.[0]) }>
* <button>Upload</button>
* </UploadTrigger>
* ```
*
*/
declare const UploadTrigger: ({ children, by, ...props }: UploadTriggerProps) => react_jsx_runtime.JSX.Element;
/**
* @category Storage
*
* 데이터를 동기화하는 ReactSynced 클래스입니다. 데이터가 업데이트될 때 리스너 함수를 호출합니다.
*/
declare class ReactSynced<T> {
/**
* 동기화된 데이터입니다.
*/
private _data;
/**
* 리스너 함수입니다.
*/
listener: (() => void) | null;
/**
* 동기화된 데이터를 가져옵니다.
* @returns T 타입의 동기화된 데이터 또는 데이터가 설정되지 않은 경우 null을 반환합니다.
*/
get data(): T | null;
/**
* 동기화된 데이터를 설정하고 리스너를 트리거합니다.
* @param data - 동기화할 데이터입니다.
*/
set data(data: T | null);
/**
* 데이터가 업데이트될 때 호출될 리스너 함수를 연결합니다.
* @param listener - 호출될 리스너 함수입니다.
*/
connect: (listener: () => void) => void;
/**
* 리스너 함수를 연결 해제합니다.
*/
unConnect: () => void;
}
/**
*
* @category Storage
*
* 알림함수를 관리하고,{@link @toktokhan-dev/react-web#SyncedStorage | `SyncedStorage`} 와 {@link @toktokhan-dev/react-web#useSyncWebStorage | `useSyncWebStorage`} 를 연결 하는 모듈입니다.
*
* @remarks {@link @toktokhan-dev/react-web#useSyncWebStorage | `useSyncWebStorage`}로 부터 리랜더링을 촉발시키는 알림함수 를 받아 관리하고,
* {@link @toktokhan-dev/react-web#SyncedStorage | `SyncedStorage`} 모듈에 알림 함수를 넘겨주어 {@link @toktokhan-dev/react-web#useSyncWebStorage | `useSyncWebStorage`}와 연결시켜주는 역할을 합니다.
*
* @example
* ```ts
* const textStorage = new SyncedStorage<string>("text", localStorage)
* const textStorageConnector = new ReactSyncConnector(textStorage)
*
* // Some Action
* textStorage.set("Hello, World!")
*
* // Some component
* const text = useSyncWebStorage(textStorageConnector) // Wrapping Hook with useSyncWebStorage
* console.log(text) // "Hello, World!"
* ```
*/
declare class ReactSyncConnector<Data> {
/**
* 알림함수를 저장하는 배열입니다.
*/
listeners: Array<() => void>;
/**
* ReactSynced 인터페이스를 구현한 객체 또는 null입니다. Storage 모듈에 해당합니다.
*/
private synced;
/**
* 서버 초깃값에 해당합니다.
*/
private serverSynced?;
/**
* ReactSyncConnector 인스턴스를 생성합니다.
* Storage 모듈에 emitChange 함수를 연결합니다.
*
* @param synced - ReactSynced 인터페이스를 구현한 객체입니다.
* @param serverSynced - 사용자가 제공하는 서버 초기값입니다.
*/
constructor(synced: ReactSynced<Data> | null, serverSynced?: Data);
/**
* {@link https://react.dev/reference/react/useSyncExternalStore | `useSyncExternalStore`}에서 알림함수를 받고, 저장해둡니다.
*
* @param listener - 변경 사항을 처리할 콜백 함수입니다.
* @returns 정리 함수를 반환합니다.
*/
subscribe: (listener: () => void) => () => void;
/**
* 알림함수가 실행되어, 리랜더링 될 시 조회할 데이터를 넘겨줍니다.
*
* @returns 동기화된 데이터 또는 null을 반환합니다.
*/
getSnapshot: () => NonNullable<Data> | null;
/**
* 서버 데이터의 스냅샷을 반환합니다.
*
* @returns 서버 초깃값 또는 null을 반환합니다.
*/
getServerSnapShot: () => NonNullable<Data> | null;
/**
* 알림함수를 실행시켜 구독 모듈에 알림이 전달해 리랜더링을 촉발시킵니다.
*/
private emitChange;
}
/**
* @category Storage
*
* useSyncExternalStore 의 wrapper 입니다.
* {@link @toktokhan-dev/react-web#ReactSyncConnector | `ReactSyncConnector`}를 통해 외부 스토리지와 동기화를 합니다.
*
* @example
* ```ts
* const textStorage = new SyncedStorage<string>("text", localStorage)
* const textConnector = new ReactSyncConnector(textStorage)
*
* textStorage.set("Hello, World!")
* textStorage.set((prev) => prev + "!")
*
* textStorage.get() // "Hello, World!!"
*
* const text = useSyncWebStorage(textConnector)
*
* console.log(text) // "Hello, World!!"
* ```
*/
declare const useSyncWebStorage: <T>(connector: ReactSyncConnector<T>) => NonNullable<T> | null;
type CookieOptions = Parameters<Cookies['set']>[2];
/**
* @category Storage
*
* 데이터를 쿠키에 동기화하는 SyncedCookie 클래스입니다. 데이터가 업데이트될 때 리스너 함수를 호출합니다.
* {@link @toktokhan-dev/react-web#ReactSyncConnector | `ReactSyncConnector`}와 연결하여 사용합니다.
*
* @example
* ```ts
* const cookieStorage = new SyncedCookie<string>("cookie-key", { path: '/' })
* const cookieConnector = new ReactSyncConnector(cookieStorage)
*
* cookieStorage.set("Hello, Cookie!")
* cookieStorage.set((prev) => prev + "!")
*
* cookieStorage.get() // "Hello, Cookie!!"
* cookieStorage.remove()
*
* cookieStorage.get() // null
* ```
*
*/
declare class SyncedCookie<Data> extends ReactSynced<Data> {
key: string;
storage: any;
defaultOptions: CookieOptions;
/**
* SyncedCookie 인스턴스를 생성합니다.
* 데이터를 저장할 키와 쿠키 옵션을 받습니다.
*
* @param key - 데이터를 저장할 키입니다.
* @param options - 쿠키 옵션입니다. (default: { secure: true, sameSite: 'strict', path: '/' })
*/
constructor(key: string, options?: CookieOptions);
/**
* 쿠키에서 데이터를 가져옵니다.
* 저장된 json 데이터를 parse 한 후 가져옵니다.
*/
get: () => Data | null;
/**
* 쿠키에 데이터를 저장합니다.
* 저장할 데이터 혹은 함수를 받아서 데이터를 저장합니다.
*
* @param data - 저장할 데이터 혹은 데이터를 반환하는 함수입니다.
* @param options - 쿠키 옵션입니다.
*/
set: (data: DataOrFn<Data | null>, options?: CookieOptions) => void;
/**
* 쿠키에 저장된 데이터를 삭제합니다.
*
* @param options - 쿠키 옵션입니다.
*/
remove: (options?: CookieOptions) => void;
}
/**
* @category Storage
*
* 데이터를 동기화하는 SyncedStorage 클래스입니다. 데이터가 업데이트될 때 리스너 함수를 호출합니다.
* {@link @toktokhan-dev/react-web#ReactSyncConnector | `ReactSyncConnector`} 와 연결하여 사용합니다.
*
* @example
* ```ts
* const textStorage = new SyncedStorage<string>("text", localStorage)
* const textConnector = new ReactSyncConnector(textStorage)
*
* textStorage.set("Hello, World!")
* textStorage.set((prev) => prev + "!")
*
* textStorage.get() // "Hello, World!!"
* textStorage.remove()
*
* textStorage.get() // null
* ```
*
*/
declare class SyncedStorage<Data> extends ReactSynced<Data> {
key: string;
private storage;
/**
* SyncedStorage 인스턴스를 생성합니다.
* 데이터를 저장할 키와 Storage 객체를 받습니다.
*
* 생성될때, storage 이벤트가 등록되며 다른 브라우저에서의 change event를 감지하여, 최신값을 가져옵니다.
*
* @param key - 데이터를 저장할 키입니다.
* @param storage - 데이터를 저장할 Storage 객체입니다.
*/
constructor(key: string, storage: Storage);
/**
* Storage에 저장된 json 데이터를 parse 한 후 가져옵니다.
*/
get: () => Data | null;
/**
* Storage에 데이터를 저장합니다.
* 저장할 데이터 혹은 함수를 받아서 데이터를 저장합니다.
*/
set: (data: DataOrFn<Data | null>) => void;
/**
* Storage에 저장된 데이터를 삭제합니다.
*/
remove: () => void;
}
/**
* @category Storage
*
* 동기화된 스토리지를 생성하는 팩토리 역할을 합니다.
* 해당 클래스의 각 method 는 {@link @toktokhan-dev/react-web#ReactSyncConnector | `ReactSyncConnector`}와 {@link @toktokhan-dev/react-web#SyncedStorage | `SyncedStorage`}를
* 동시에 생성해줍니다.
*
* @example
* ```ts
* type TokenType = {
* access: string
* refresh: string
* }
* const { storage, connector } = SyncedStorageFactory.createLocal<TokenType>('token')
*
* storage.set({ access: 'access', refresh: 'refresh' })
*
* const token = useWebStorage(connector)
* ```
*/
declare class SyncedStorageFactory {
/**
* 로컬 스토리지를 생성합니다.
* @param key 스토리지 키
* @returns 생성된 스토리지와 커넥터 객체
*/
static createLocal: <Data>(key: string) => {
storage: SyncedStorage<Data> | null;
connector: ReactSyncConnector<Data>;
};
/**
* 세션 스토리지를 생성합니다.
* @param key 스토리지 키
* @returns 생성된 스토리지와 커넥터 객체
*/
static createSession: <Data>(key: string) => {
storage: SyncedStorage<Data> | null;
connector: ReactSyncConnector<Data>;
};
/**
* 쿠키를 생성합니다.
* @param key 쿠키 키
* @param store 쿠키 객체
* @returns 생성된 쿠키와 커넥터 객체
*/
static createCookie: <Data>(key: string, options?: CookieOptions) => {
storage: SyncedCookie<Data>;
connector: ReactSyncConnector<Data>;
};
/**
* 스토리지를 생성합니다.
* @param key 스토리지 키
* @param store 스토리지 객체
* @returns 생성된 스토리지와 커넥터 객체
*/
static create: <Data>(key: string, store: Storage | null) => {
storage: SyncedStorage<Data> | null;
connector: ReactSyncConnector<Data>;
};
}
type UseIntersectionObserverParams = {
onVisible?: (entry?: IntersectionObserverEntry, observer?: IntersectionObserver) => void;
onHidden?: (entry?: IntersectionObserverEntry, observer?: IntersectionObserver) => void;
options?: IntersectionObserverInit;
};
/**
* 반환한 targetRef를 사용하여 대상 컴포넌트에 intersectionObserver 이벤틀르 주기 위한 hooks입니다.
*
* hooks 선언시 props 설정이 가능하며, 화면에 표출되는 조건에 따라 onVisible, onHidden 함수가 실행됩니다.
*
* @category Hooks
*
* @typeParam T - 배열 요소의 타입
* @typeParam K - Map의 키 타입
*
* @param onVisible - targetRef 요소가 보여질 때 실행할 함수
* @param onHidden - targetRef 요소가 보이지 않을 때 실행할 함수
* @param options - targetRef에 설정할 intersection observer 옵션
*
* @returns intersection Observer 이벤트가 할당된 Element useRef
*
* @example
*
* ```tsx
*
* const { targetRef } = useIntersectionObserver(
* {
* onVisible: () => onVisibleLast(),
* onHidden: () => onHiddenLast(),
* options: {
* threshold: 0.1,
* },
* },
* [],
* );
* ...
*
* return (
* <LastItem ref={targetRef} w="100%" />
* )
*
* ```
*
*/
declare const useIntersectionObserver: ({ onVisible, onHidden, options, }: UseIntersectionObserverParams, deps: unknown[]) => {
targetRef: react.RefObject<HTMLElement>;
};
/**
* SocialType은 지원하는 소셜 로그인 타입을 나타냅니다.
*/
type SocialType = 'kakao' | 'naver' | 'facebook' | 'google' | 'apple';
/**
* SocialAuthQueryResponse는 소셜 로그인 인증 응답을 정의합니다.
*/
interface SocialAuthQueryResponse {
access_token: string | null;
code: string | null;
state: string | null;
error: string | null;
errorDescription: string | null;
}
interface CommonOauthParams {
response_type: string;
client_id: string;
scope?: string;
state?: string;
}
/**
* OauthUserReqParams는 OAuth 인증 요청에 필요한 파라미터를 정의합니다.
* OauthUserReqParams는 CommonOauthParams를 확장하고, 필요한 추가 속성을 정의합니다.
* 소셜로그인에 필요한 `response_type` , `client_id`, `scope`, `state` 를 클래스 내부에서 직접 주입해주고 있기 때문에
* 필수 타입에서 제거하거나 변환하고 `return_url`와 같이 요청시 필요한 타입을 추가하였습니다.
*/
type OauthUserReqParams<T extends CommonOauthParams, State> = Omit<T, keyof CommonOauthParams> & {
state?: State;
scope?: string | string[];
};
/**
* {@link https://developers.kakao.com/docs/latest/ko/kakaologin/rest-api | `Kakao Login Docs`}
*/
interface KakaoAuthQueryParams {
client_id: string;
redirect_uri: string;
response_type: string;
scope?: string;
prompt?: 'none' | 'login' | 'create' | 'select_account';
login_hint?: string;
service_terms?: string;
state?: string;
nonce?: string;
}
/**
* KaKaoAuthQueryResponse는 카카오 로그인 인증 응답을 정의합니다.
*/
interface KaKaoAuthQueryResponse {
code?: string;
error?: string;
error_description?: string;
state?: string;
}
/**
* {@link https://developer.apple.com/documentation/sign_in_with_apple/request_an_authorization_to_the_sign_in_with_apple_server | `Apple Login Docs`}
*/
interface AppleAuthQueryParams {
client_id: string;
redirect_uri: string;
response_type: string;
nonce?: string;
response_mode?: string;
scope?: string;
state?: string;
}
/**
* {@link https://developers.facebook.com/docs/facebook-login/guides/advanced/manual-flow/ | `Facebook Login Docs`}
*/
interface FacebookAuthQueryParams {
client_id: string;
redirect_uri: string;
response_type: string;
state?: string;
scope?: string;
}
/**
* {@link https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow?hl=ko | `Google Login Docs`}
*/
interface GoogleAuthQueryParams {
client_id: string;
redirect_uri: string;
response_type: string;
scope: string;
state?: string;
include_granted_scopes?: boolean;
enable_granular_consent?: boolean;
login_hint?: string;
prompt?: 'none' | 'consent' | 'select_account';
}
/**
* {@link https://developers.naver.com/docs/login/api/api.md#2--api-%EA%B8%B0%EB%B3%B8-%EC%A0%95%EB%B3%B4 | `Naver Login Docs`}
*/
interface NaverAuthQueryParams {
client_id: string;
redirect_uri: string;
response_type: string;
state: string;
scope?: string;
}
/**
* NaverAuthQueryResponse는 네이버 로그인 인증 응답을 정의합니다.
*/
interface NaverAuthQueryResponse {
code?: string;
error?: string;
error_description?: string;
state?: string;
}
/**
* `IconButtonProps`는 `IconButton` 컴포넌트가 받는 속성들을 정의합니다.
* HTMLAnchorElement의 속성을 상속하며, 추가적으로 아래의 속성들을 가집니다.
*/
interface IconButtonProps {
/**
* anchor 태그의 스타일을 설정합니다.
*/
style?: HTMLAttributes<HTMLAnchorElement>['style'];
/**
* onClick 속성을 설정합니다.
*/
onClick?: HTMLAttributes<HTMLAnchorElement>['onClick'];
/**
* 아이콘 버튼의 모양을 결정합니다. 'full', 'rounded', 'square' 중 하나를 선택할 수 있습니다.
* @default 'full'
*/
variant?: 'full' | 'rounded' | 'square';
/**
* 아이콘 버튼의 색상 모드를 설정합니다. 'light' 또는 'dark' 중 하나를 선택할 수 있습니다.
* @default 'dark'
*/
colorMode?: 'light' | 'dark';
/**
* 소셜 타입을 지정합니다. 이를 통해 버튼의 스타일과 레이블이 결정됩니다.
*/
socialType: SocialType;
/**
* 버튼의 언어를 설정합니다. 'en' 또는 'ko' 중 하나를 선택할 수 있습니다.
* @default 'ko'
*/
lang?: 'en' | 'ko';
/**
* 버튼에 표시될 레이블을 설정합니다. null 값을 통해 레이블을 숨길 수 있습니다.
*/
label?: string | null;
/**
* 버튼에 표시될 아이콘을 설정합니다. ReactElement 타입이어야 합니다.
*/
icon: ReactElement;
/**
* 아이콘의 스타일을 설정합니다.
*/
iconStyle?: HTMLAttributes<HTMLOrSVGElement>['style'];
/**
* 레이블의 스타일을 설정합니다.
*/
labelStyle?: HTMLAttributes<HTMLLabelElement>['style'];
}
/**
* IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface GoogleIconButtonProps extends Omit<IconButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Google
*
* 구글 아이콘 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#IconButton | `IconButton`} 컴포넌트를 기반으로 하며, 구글 아이콘 및 버튼 스타일링이 가능합니다.
*
* @param props - IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 구글 아이콘 버튼 컴포넌트를 반환합니다.
*/
declare const GoogleIconButton: ({ style, iconStyle, ...props }: GoogleIconButtonProps) => react_jsx_runtime.JSX.Element;
/**
* `FullButtonProps`는 `FullButton` 컴포넌트가 받는 속성들을 정의합니다.
* HTMLAnchorElement의 속성을 상속하며, 추가적으로 아래의 속성들을 가집니다.
*/
interface FullButtonProps {
/**
* anchor 태그의 스타일을 설정합니다.
*/
style?: HTMLAttributes<HTMLAnchorElement>['style'];
/**
* onClick 속성을 설정합니다.
*/
onClick?: HTMLAttributes<HTMLAnchorElement>['onClick'];
/**
* 버튼의 색상 모드를 설정합니다. 'light' 또는 'dark' 중 하나를 선택할 수 있습니다.
* @default 'dark'
*/
colorMode?: 'light' | 'dark';
/**
* 소셜 타입을 지정합니다. 이를 통해 버튼의 스타일과 레이블이 결정됩니다.
*/
socialType: SocialType;
/**
* 버튼의 모양을 결정합니다. 'rounded', 'square' 중 하나를 선택할 수 있습니다.
* @default 'square'
*/
variant?: 'rounded' | 'square';
/**
* 버튼 내 콘텐츠의 정렬을 지정합니다. 'left' 또는 'center' 중 하나를 선택할 수 있습니다.
* @default 'center'
*/
align?: 'left' | 'center';
/**
* 버튼의 언어를 설정합니다. 'en' 또는 'ko' 중 하나를 선택할 수 있습니다.
* @default 'ko'
*/
lang?: 'en' | 'ko';
/**
* 버튼에 표시될 레이블을 설정합니다. null 값을 통해 레이블을 숨길 수 있습니다.
*/
label?: string | null;
/**
* 버튼에 표시될 아이콘을 설정합니다. ReactElement 타입이어야 합니다.
*/
icon: ReactElement;
/**
* 아이콘의 스타일을 설정합니다.
*/
iconStyle?: HTMLAttributes<HTMLOrSVGElement>['style'];
/**
* 레이블의 스타일을 설정합니다.
*/
labelStyle?: HTMLAttributes<HTMLLabelElement>['style'];
}
/**
* FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface GoogleButtonProps extends Omit<FullButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Google
*
* 구글 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#FullButton | `FullButton`} 컴포넌트를 기반으로 하여, 구글 아이콘과 스타일, 레이블을 포함합니다.
*
* @param props -FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 구글 버튼 컴포넌트를 반환합니다.
*/
declare const GoogleButton: ({ style, ...props }: GoogleButtonProps) => react_jsx_runtime.JSX.Element;
/**
* OauthStateReturnType은 OAuth 상태 반환 타입을 정의합니다.
* type: 소셜 로그인 타입을 나타냅니다.
* returnUrl: 로그인 후 리다이렉트 될 URL을 나타냅니다.
*/
interface OauthStateReturnType {
type: string | null;
returnUrl: string | null;
}
/**
* SocialOauthInit 클래스는 소셜 로그인 초기화를 담당합니다.
*/
declare class SocialOauthInit {
clientID: string;
oAuthBaseUrl: string;
/**
* 생성자 함수에서는 클라이언트 ID를 받아 초기화합니다.
* @param clientID - 소셜 로그인을 위한 클라이언트 ID
*/
constructor(clientID: string);
/**
* createOauthUrl 메서드는 OAuth 인증 URL을 생성합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @returns 생성된 OAuth 인증 URL
*/
createOauthUrl(params: Record<string, any>): string;
/**
* encodeOAuthState 메서드는 OAuth 상태를 인코딩합니다.
* @param type - 소셜 로그인 타입
* @param returnUrl - 로그인 후 리다이렉트 될 URL
* @returns 인코딩된 OAuth 상태
*/
static encodeOAuthState: <T>(state: T) => string;
/**
* decodeOAuthState 메서드는 인코딩된 OAuth 상태를 디코딩합니다.
* @param state - 인코딩된 OAuth 상태
* @returns 디코딩된 OAuth 상태. 디코딩에 실패하면 null을 반환합니다.
*/
static decodeOAuthState: <T>(state: string) => T | null;
}
declare const GOOGLE_AUTH_SCOPE: {
readonly email: "https://www.googleapis.com/auth/userinfo.email";
readonly profile: "https://www.googleapis.com/auth/userinfo.profile";
};
/**
* @category Socials/Google
*
* Google OAuth 인증을 처리하는 클래스입니다.
* SocialOauthInit 클래스를 상속받아 구현되었습니다.
*/
declare class Google extends SocialOauthInit {
oAuthBaseUrl: string;
/**
* Google 클래스의 생성자입니다.
* @param clientID - Google OAuth 클라이언트 ID
*/
constructor(clientID?: string);
/**
* OAuth 인증 URL을 생성합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.state - 트랜잭션 동안 유지할 상태
* @param params.scope - 요청할 OAuth 스코프
* @returns 생성된 OAuth 인증 URL
*/
createOauthUrl: <State>({ state, scope, ...params }: OauthUserReqParams<GoogleAuthQueryParams, State>) => string;
/**
* OAuth 인증 링크로 리다이렉트합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.state - 트랜잭션 동안 유지할 상태
* @param params.scope - 요청할 OAuth 스코프
*/
loginToLink: <State>(params: OauthUserReqParams<GoogleAuthQueryParams, State>) => void;
/**
* OAuth 인증 팝업을 엽니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.state - 트랜잭션 동안 유지할 상태
* @param params.scope - 요청할 OAuth 스코프 (이메일, 프로필 등)
*/
loginToPopup: <State>(params: OauthUserReqParams<GoogleAuthQueryParams, State>) => void;
}
/**
* FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface KakaoButtonProps extends Omit<FullButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Kakao
*
* 카카오 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#FullButton | `FullButton`} 컴포넌트를 기반으로 하여, 카카오 아이콘과 스타일, 레이블을 포함합니다.
*
* @param props -FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 카카오 버튼 컴포넌트를 반환합니다.
*/
declare const KakaoButton: (props: KakaoButtonProps) => ReactNode;
/**
* @category Socials/Kakao
*
* Kakao OAuth 인증을 처리하는 클래스입니다.
* SocialOauthInit 클래스를 상속받아 구현되었습니다.
*/
declare class Kakao extends SocialOauthInit {
oAuthBaseUrl: string;
/**
* Kakao 클래스의 생성자입니다.
* @param clientID - Kakao OAuth 클라이언트 ID
*/
constructor(clientID?: string);
/**
* OAuth 인증 URL을 생성합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.state - 트랜잭션 동안 유지할 상태
* @returns 생성된 OAuth 인증 URL
*/
createOauthUrl: <State>({ state, scope, ...params }: OauthUserReqParams<KakaoAuthQueryParams, State>) => string;
/**
* OAuth 인증 링크로 리다이렉트합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.state - 트랜잭션 동안 유지할 상태
*/
loginToLink: <State>(params: OauthUserReqParams<KakaoAuthQueryParams, State>) => void;
/**
* OAuth 인증 팝업을 엽니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.state - 트랜잭션 동안 유지할 상태
*/
loginToPopup: <State>(params: OauthUserReqParams<KakaoAuthQueryParams, State>) => void;
}
/**
* IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface KakaoIconButtonProps extends Omit<IconButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Kakao
*
* 카카오 아이콘 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#IconButton | `IconButton`} 컴포넌트를 기반으로 하며, 카카오 아이콘 및 버튼 스타일링이 가능합니다.
*
* @param props - IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 카카오 아이콘 버튼 컴포넌트를 반환합니다.
*/
declare const KakaoIconButton: (props: KakaoIconButtonProps) => ReactNode;
/**
* IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface NaverIconButtonProps extends Omit<IconButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Naver
*
* 네이버 아이콘 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#IconButton | `IconButton`} 컴포넌트를 기반으로 하며, 네이버 아이콘 및 버튼 스타일링이 가능합니다.
*
* @param props - IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 네이버 아이콘 버튼 컴포넌트를 반환합니다.
*/
declare const NaverIconButton: (props: NaverIconButtonProps) => react_jsx_runtime.JSX.Element;
/**
* FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface NaverButtonProps extends Omit<FullButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Naver
*
* 네이버 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#FullButton | `FullButton`} 컴포넌트를 기반으로 하여, 네이버 아이콘과 스타일, 레이블을 포함합니다.
*
* @param props -FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 네이버 버튼 컴포넌트를 반환합니다.
*/
declare const NaverButton: (props: NaverButtonProps) => ReactNode;
/**
* @category Socials/Naver
*
* 네이버 OAuth 인증을 처리하는 클래스입니다.
* SocialOauthInit 클래스를 상속받아 구현되었습니다.
*/
declare class Naver extends SocialOauthInit {
oAuthBaseUrl: string;
/**
* Naver 클래스의 생성자입니다.
* @param clientID - Naver OAuth 클라이언트 ID
*/
constructor(clientID?: string);
/**
* OAuth 인증 URL을 생성합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.scope - 요청할 OAuth 스코프
* @param params.state - 트랜잭션 동안 유지할 상태
* @returns 생성된 OAuth 인증 URL
*/
createOauthUrl: <State>({ scope, state, ...params }: OauthUserReqParams<NaverAuthQueryParams, State>) => string;
/**
* 로그인을 위한 OAuth 인증 링크로 리다이렉트합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.scope - 요청할 OAuth 스코프
* @param params.state - 트랜잭션 동안 유지할 상태
*/
loginToLink: <State>(params: OauthUserReqParams<NaverAuthQueryParams, State>) => void;
/**
* 로그인을 위한 OAuth 인증 팝업을 엽니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.scope - 요청할 OAuth 스코프
* @param params.state - 트랜잭션 동안 유지할 상태
*/
loginToPopup: <State>(params: OauthUserReqParams<NaverAuthQueryParams, State>) => void;
}
/**
* IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface AppleIconButtonProps extends Omit<IconButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Apple
*
* 애플 아이콘 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#IconButton | `IconButton`} 컴포넌트를 기반으로 하며, 애플 아이콘 및 버튼 스타일링이 가능합니다.
*
* @param props - IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 애플 아이콘 버튼 컴포넌트를 반환합니다.
*/
declare const AppleIconButton: (props: AppleIconButtonProps) => react_jsx_runtime.JSX.Element;
/**
* FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface AppleButtonProps extends Omit<FullButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Apple
*
* 애플 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#FullButton | `FullButton`} 컴포넌트를 기반으로 하여, 애플 아이콘과 스타일, 레이블을 포함합니다.
*
* @param props -FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 애플 버튼 컴포넌트를 반환합니다.
*/
declare const AppleButton: (props: AppleButtonProps) => react_jsx_runtime.JSX.Element;
/**
* @category Socials/Apple
*
* Apple OAuth 인증을 처리하는 클래스입니다.
* SocialOauthInit 클래스를 상속받아 구현되었습니다.
*/
declare class Apple extends SocialOauthInit {
oAuthBaseUrl: string;
/**
* Apple 클래스의 생성자입니다.
* @param clientID - Apple OAuth 클라이언트 ID
*/
constructor(clientID?: string);
/**
* OAuth 인증 URL을 생성합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.scope - 요청할 OAuth 스코프
* @param params.state - 트랜잭션 동안 유지할 상태
* @returns 생성된 OAuth 인증 URL
*/
createOauthUrl: <State>({ scope, state, ...params }: OauthUserReqParams<AppleAuthQueryParams, State>) => string;
/**
* 로그인을 위한 OAuth 인증 링크로 리다이렉트합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.scope - 요청할 OAuth 스코프
* @param params.state - 트랜잭션 동안 유지할 상태
*/
loginToLink: <State>(params: OauthUserReqParams<AppleAuthQueryParams, State>) => void;
/**
* 로그인을 위한 OAuth 인증 팝업을 엽니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.scope - 요청할 OAuth 스코프
* @param params.state - 트랜잭션 동안 유지할 상태
*/
loginToPopup: <State>(params: OauthUserReqParams<AppleAuthQueryParams, State>) => void;
}
/**
* IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface FacebookIconButtonProps extends Omit<IconButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Facebook
*
* 페이스북 아이콘 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#IconButton | `IconButton`} 컴포넌트를 기반으로 하며, 페이스북 아이콘 및 버튼 스타일링이 가능합니다.
*
* @param props - IconButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 페이스북 아이콘 버튼 컴포넌트를 반환합니다.
*/
declare const FacebookIconButton: (props: FacebookIconButtonProps) => react_jsx_runtime.JSX.Element;
/**
* FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
*/
interface FacebookButtonProps extends Omit<FullButtonProps, 'socialType' | 'icon'> {
}
/**
* @category Socials/Facebook
*
* 페이스북 버튼 UI 컴포넌트입니다.
* {@link @toktokhan-dev/react-web#FullButton | `FullButton`} 컴포넌트를 기반으로 하여, 페이스북 아이콘과 스타일, 레이블을 포함합니다.
*
* @param props -FullButtonProps에서 'socialType'과 'icon'을 제외한 속성들을 상속받습니다.
* @returns 페이스북 버튼 컴포넌트를 반환합니다.
*/
declare const FacebookButton: (props: FacebookButtonProps) => react_jsx_runtime.JSX.Element;
/**
* @category Socials/FaceBook
*
* Facebook OAuth 인증을 처리하는 클래스입니다.
* SocialOauthInit 클래스를 상속받아 구현되었습니다.
*/
declare class Facebook extends SocialOauthInit {
oAuthBaseUrl: string;
/**
* Facebook 클래스의 생성자입니다.
* @param clientID - Facebook OAuth 클라이언트 ID
*/
constructor(clientID?: string);
/**
* OAuth 인증 URL을 생성합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.scope - 요청할 OAuth 스코프
* @param params.state - 트랜잭션 동안 유지할 상태
* @returns 생성된 OAuth 인증 URL
*/
createOauthUrl: <State>({ scope, state, ...params }: OauthUserReqParams<FacebookAuthQueryParams, State>) => string;
/**
* 로그인을 위한 OAuth 인증 링크로 리다이렉트합니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.scope - 요청할 OAuth 스코프
* @param params.state - 트랜잭션 동안 유지할 상태
*/
loginToLink: <State>(params: OauthUserReqParams<FacebookAuthQueryParams, State>) => void;
/**
* 로그인을 위한 OAuth 인증 팝업을 엽니다.
* @param params - OAuth 인증 요청에 필요한 파라미터
* @param params.scope - 요청할 OAuth 스코프
* @param params.return_url - 인증 후 리다이렉션될 URL
*/
loginToPopup: <State>(params: OauthUserReqParams<FacebookAuthQueryParams, State>) => void;
}
interface OauthResponse<T> {
code: string | null;
error: string | null;
errorDescription: string | null;
state: T | null;
}
interface useOauthCallbackParams<T = any, U = any> {
onSuccess?: (params: T | null) => void;
onFail?: (params: U | null) => void;
}
/**
* `useOauthLinkCallback` 훅의 반환 타입을 정의합니다.
*/
interface LinkReturnType<T> {
/**
* OAuth 응답 데이터를 나타냅니다.
*/
data: OauthResponse<T> | null;
/**
* OAuth 콜백 처리 상태를 나타냅니다. 처리 중이면 `true`, 아니면 `false`입니다.
*/
isLoading: boolean;
}
/**
* @category Socials
*
* OAuth 링크 콜백을 처리하는 React Hook입니다.
* 이 Hook은 OAuth 인증 후 리다이렉트된 페이지에서 사용됩니다.
*
* @param params 콜백 함수 파라미터. `onSuccess`와 `onFail` 콜백 함수를 포함할 수 있습니다.
* @returns {LinkReturnType} OAuth 응답 데이터와 로딩 상태를 반환합니다.
*
* @example
*
* ```tsx
* // pages/login.tsx
*
* const kakao = new Kakao(ENV.CLIENT_ID)
* const Login = () =>
* <KakaoButton
* onClick={() =>
* kakao.loginToLink({
* redirect_uri: `${window.origin}/social/callback`,
* state: {
* returnUrl: returnUrl || '/login',
* type: 'kakao',
* },
* })
* }
* />
* }
*
*
* // pages/social/callback.tsx
*
* const { data, isLoading } = useOauthLinkCallback<{type: string; returnUrl:string}>({
* onSuccess: (response) => {
* console.log(response.state.returnUrl)
* },
* })
* ```
*/
declare const useOauthLinkCallback: <State>(params?: useOauthCallbackParams<OauthResponse<State>, OauthResponse<State>>) => {
data: OauthResponse<State> | null;
isLoading: boolean;
};
/**
* `useOauthPopupCallback` 훅의 반환 타입을 정의합니다.
*/
interface PopupReturnType<T> {
/**
* OAuth 응답 데이터를 나타냅니다.
*/
data: OauthResponse<T> | null;
/**
* OAuth 콜백 처리 상태를 나타냅니다. 처리 중이면 `true`, 아니면 `false`입니다.
*/
isLoading: boolean;
/**
* 팝업을 닫는 함수를 나타냅니다.
* 팝업이 닫힐때 부모 창에 OAuth 응답 데이터를 전달합니다.
* `useOauthPopupListener` 훅을 사용하여 부모 창에서 OAuth 응답 데이터를 수신할 수 있습니다.
*
* @param extra - 모달을 닫을때 부모 창에게 추가적인 데이터를 전달할 수 있습니다.
*/
closePopup(extra?: any): void;
}
interface PopupResponse<T> extends OauthResponse<T> {
/**
* 팝업을 닫는 함수를 나타냅니다.
* 팝업이 닫힐때 부모 창에 OAuth 응답 데이터를 전달합니다.
* `useOauthPopupListener` 훅을 사용하여 부모 창에서 OAuth 응답 데이터를 수신할 수 있습니다.
*
* @param extra - 모달을 닫을때 부모 창에게 추가적인 데이터를 전달할 수 있습니다.
*/
closePopup(extra?: any): void;
}
/**
* @category Socials
*
* OAuth 팝업 콜백을 처리하는 React Hook입니다.
* 이 Hook은 OAuth 인증 후 팝업에서 사용됩니다.
*
* @param params 콜백 함수 파라미터. `onSuccess`와 `onFail` 콜백 함수를 포함할 수 있습니다.
* @returns OAuth 응답 데이터, 로딩 상태, 팝업을 닫는 함수를 반환합니다.
*
* @example
* ```tsx
* // pages/login.tsx (parents window)
*
* const kakao = new Kakao(ENV.CLIENT_ID)
* const Login = () => {
* const { data } = useOauthPopupListener()
* console.log(data, data.state.returnUrl, data.extra) // { code: '...', state: { returnUrl: '/my', type: 'kakao' }, extra: 'hello parents' }
*
* <KakaoButton
* onClick={() =>
* kakao.loginToPopup({
* redirect_uri: `${window.origin}/social/callback`,
* state: {
* returnUrl: '/my',
* type: 'kakao',
* },
* })
* }
* />
* }
*
* // pages/social/callback.tsx (popup window)
*
* const { data, isLoading } = useOauthPopupCallback<{type: string; returnUrl:string}>({
* onSuccess: (response) => {
* console.log(response.state.returnUrl)
* response.closePopup({ extra: 'hello parents' })
* },
* })
* ```
*/
declare const useOauthPopupCallback: <State>(cb?: useOauthCallbackParams<PopupResponse<State>, PopupResponse<State>>) => {
data: OauthResponse<State> | null;
isLoading: boolean;
closePopup: (extra?: any) => void;
};
interface ExtraState<T> {
extra: T;
}
/**
* @category Socials
*
* OAuth 팝업에서 전달된 메시지를 수신하는 React Hook입니다.
* 이 Hook은 OAuth 인증 후 팝업에서 전달된 메시지를 수신하여 처리합니다.
*
* @returns - OAuth 응답 데이터와 로딩 상태를 반환합니다.
* @returns data - OAuth 응답 데이터입니다. 초기값은 `null`입니다. `useOauthPopupCallback` 애서 `closePopup` 함수에서 인자로 추가적인 데이터를 전달했다면, extra 프로퍼티에 추가적인 데이터가 포함됩니다.
* @returns isLoading - OAuth 콜백 처리 상태를 나타냅니다. 처리 중이면 `true`, 아니면 `false`입니다.
*
* @example
* ```tsx
* // pages/login.tsx (parents window)
*
* const kakao = new Kakao(ENV.CLIENT_ID)
* const Login = () => {
* const { data } = useOauthPopupListener()
* console.log(data, data.state.returnUrl, data.extra) // { code: '...', state: { returnUrl: '/my', type: 'kakao' }, extra: 'hello parents' }
*
* <KakaoButton
* onClick={() =>
* kakao.loginToPopup({
* redirect_uri: `${window.origin}/social/callback`,
* state: {
* returnUrl: '/my',
* type: 'kakao',
* },
* })
* }
* />
* }
*
* // pages/social/callback.tsx (popup window)
*
* const { data, isLoading } = useOauthPopupCallback<{type: string; returnUrl:string}>({
* onSuccess: (response) => {
* console.log(response.state.returnUrl)
* response.closePopup({ extra: 'hello parents' })
* },
* })
* ```
*/
declare const ERROR_MESSAGES: {
NO_RESPONSE: string;
ORIGIN_MISMATCH: string;
NO_AUTH_CODE: string;
};
declare const useOauthPopupListener: <State, Extra = unknown>(params?: useOauthCallbackParams<OauthResponse<State> & ExtraState<Extra>, Partial<OauthResponse<State> & ExtraState<Extra> & {
msg?: string;
}>>) => {
data: Partial<OauthResponse<State> & ExtraState<Extra>> | null;
isLoading: boolean;
};
export { Apple, AppleButton, AppleIconButton, ERROR_MESSAGES, Facebook, FacebookButton, FacebookIconButton, GOOGLE_AUTH_SCOPE, Google, GoogleButton, GoogleIconButton, Kakao, KakaoButton, KakaoIconButton, Naver, NaverButton, NaverIconButton, ReactSyncConnector, ReactSynced, SocialOauthInit, SyncedCookie, SyncedStorage, SyncedStorageFactory, UploadTrigger, useIntersectionObserver, useOauthLinkCallback, useOauthPopupCallback, useOauthPopupListener, useSyncWebStorage };
export type { AppleAuthQueryParams, AppleButtonProps, AppleIconButtonProps, CommonOauthParams, CookieOptions, ExtraState, FacebookAuthQueryParams, FacebookButtonProps, FacebookIconButtonProps, FullButtonProps, GoogleAuthQueryParams, GoogleButtonProps, GoogleIconButtonProps, IconButtonProps, KaKaoAuthQueryResponse, KakaoAuthQueryParams, KakaoButtonProps, KakaoIconButtonProps, LinkReturnType, NaverAuthQueryParams, NaverAuthQueryResponse, NaverButtonProps, NaverIconButtonProps, OauthResponse, OauthStateReturnType, OauthUserReqParams, PopupResponse, PopupReturnType, SocialAuthQueryResponse, SocialType, UploadTriggerProps, useOauthCallbackParams };