260702_02_ENH: 1차 완성
This commit is contained in:
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@kri/common",
|
"name": "@kri/common",
|
||||||
"version": "0.11.1",
|
"version": "0.12.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@kri/common",
|
"name": "@kri/common",
|
||||||
"version": "0.11.1",
|
"version": "0.12.0",
|
||||||
"license": "UNLICENSED",
|
"license": "UNLICENSED",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@kri/common",
|
"name": "@kri/common",
|
||||||
"version": "0.11.1",
|
"version": "0.13.0",
|
||||||
"description": "KRI 프런트엔드 공통 유틸리티",
|
"description": "KRI 프런트엔드 공통 유틸리티",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "./dist/index.js",
|
"main": "./dist/index.js",
|
||||||
@@ -50,6 +50,11 @@
|
|||||||
"types": "./dist/config/index.d.ts",
|
"types": "./dist/config/index.d.ts",
|
||||||
"import": "./dist/config/index.js",
|
"import": "./dist/config/index.js",
|
||||||
"default": "./dist/config/index.js"
|
"default": "./dist/config/index.js"
|
||||||
|
},
|
||||||
|
"./jotai": {
|
||||||
|
"types": "./dist/jotai/index.d.ts",
|
||||||
|
"import": "./dist/jotai/index.js",
|
||||||
|
"default": "./dist/jotai/index.js"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
|
|||||||
197
src/browser/cookie-store.ts
Normal file
197
src/browser/cookie-store.ts
Normal file
@@ -0,0 +1,197 @@
|
|||||||
|
export type CookieSameSite = "Lax" | "Strict" | "None";
|
||||||
|
|
||||||
|
export type CookieSetOptions = {
|
||||||
|
days?: number;
|
||||||
|
expires?: Date;
|
||||||
|
maxAgeSeconds?: number;
|
||||||
|
|
||||||
|
path?: string;
|
||||||
|
domain?: string;
|
||||||
|
|
||||||
|
secure?: boolean;
|
||||||
|
sameSite?: CookieSameSite;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CookieRemoveOptions = Pick<
|
||||||
|
CookieSetOptions,
|
||||||
|
"path" | "domain" | "secure" | "sameSite"
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type CookieStoreErrorContext<TKey extends string> = {
|
||||||
|
operation: "get" | "set" | "remove";
|
||||||
|
|
||||||
|
key: TKey;
|
||||||
|
error: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CreateCookieStoreOptions<TKey extends string> = {
|
||||||
|
defaults?: CookieSetOptions;
|
||||||
|
|
||||||
|
onError?: (context: CookieStoreErrorContext<TKey>) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CookieStore<TKey extends string = string> = {
|
||||||
|
get: (key: TKey) => string | null;
|
||||||
|
|
||||||
|
set: (key: TKey, value: string, options?: CookieSetOptions) => void;
|
||||||
|
|
||||||
|
remove: (key: TKey, options?: CookieRemoveOptions) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const isBrowser = (): boolean => {
|
||||||
|
return typeof document !== "undefined";
|
||||||
|
};
|
||||||
|
|
||||||
|
const appendCookieOption = (
|
||||||
|
parts: string[],
|
||||||
|
name: string,
|
||||||
|
value?: string,
|
||||||
|
): void => {
|
||||||
|
if (value === undefined) {
|
||||||
|
parts.push(name);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
parts.push(`${name}=${value}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const buildCookieString = (
|
||||||
|
key: string,
|
||||||
|
value: string,
|
||||||
|
options: CookieSetOptions,
|
||||||
|
remove: boolean,
|
||||||
|
): string => {
|
||||||
|
const parts = [`${encodeURIComponent(key)}=${encodeURIComponent(value)}`];
|
||||||
|
|
||||||
|
if (remove) {
|
||||||
|
appendCookieOption(parts, "Expires", new Date(0).toUTCString());
|
||||||
|
|
||||||
|
appendCookieOption(parts, "Max-Age", "0");
|
||||||
|
} else if (options.maxAgeSeconds !== undefined) {
|
||||||
|
appendCookieOption(parts, "Max-Age", String(options.maxAgeSeconds));
|
||||||
|
} else if (options.expires !== undefined) {
|
||||||
|
appendCookieOption(parts, "Expires", options.expires.toUTCString());
|
||||||
|
} else if (options.days !== undefined && Number.isFinite(options.days)) {
|
||||||
|
const expires = new Date();
|
||||||
|
|
||||||
|
expires.setDate(expires.getDate() + options.days);
|
||||||
|
|
||||||
|
appendCookieOption(parts, "Expires", expires.toUTCString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.path) {
|
||||||
|
appendCookieOption(parts, "Path", options.path);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.domain) {
|
||||||
|
appendCookieOption(parts, "Domain", options.domain);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.secure) {
|
||||||
|
appendCookieOption(parts, "Secure");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (options.sameSite) {
|
||||||
|
appendCookieOption(parts, "SameSite", options.sameSite);
|
||||||
|
}
|
||||||
|
|
||||||
|
return parts.join("; ");
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createCookieStore = <TKey extends string = string>(
|
||||||
|
options: CreateCookieStoreOptions<TKey> = {},
|
||||||
|
): CookieStore<TKey> => {
|
||||||
|
const defaultOptions = options.defaults ?? {};
|
||||||
|
|
||||||
|
const reportError = (
|
||||||
|
operation: CookieStoreErrorContext<TKey>["operation"],
|
||||||
|
key: TKey,
|
||||||
|
error: unknown,
|
||||||
|
): void => {
|
||||||
|
options.onError?.({
|
||||||
|
operation,
|
||||||
|
key,
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const get = (key: TKey): string | null => {
|
||||||
|
if (!isBrowser()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const encodedName = `${encodeURIComponent(key)}=`;
|
||||||
|
|
||||||
|
const cookies = document.cookie ? document.cookie.split(";") : [];
|
||||||
|
|
||||||
|
for (const rawCookie of cookies) {
|
||||||
|
const cookie = rawCookie.trim();
|
||||||
|
|
||||||
|
if (!cookie.startsWith(encodedName)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const encodedValue = cookie.slice(encodedName.length);
|
||||||
|
|
||||||
|
return decodeURIComponent(encodedValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError("get", key, error);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const set = (
|
||||||
|
key: TKey,
|
||||||
|
value: string,
|
||||||
|
setOptions: CookieSetOptions = {},
|
||||||
|
): void => {
|
||||||
|
if (!isBrowser()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
document.cookie = buildCookieString(
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
{
|
||||||
|
...defaultOptions,
|
||||||
|
...setOptions,
|
||||||
|
},
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError("set", key, error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const remove = (key: TKey, removeOptions: CookieRemoveOptions = {}): void => {
|
||||||
|
if (!isBrowser()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
document.cookie = buildCookieString(
|
||||||
|
key,
|
||||||
|
"",
|
||||||
|
{
|
||||||
|
...defaultOptions,
|
||||||
|
...removeOptions,
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError("remove", key, error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return Object.freeze({
|
||||||
|
get,
|
||||||
|
set,
|
||||||
|
remove,
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -1 +1,3 @@
|
|||||||
export * from "./file-download.js";
|
export * from "./file-download.js";
|
||||||
|
export * from "./cookie-store.js";
|
||||||
|
export * from "./json-storage.js";
|
||||||
|
|||||||
212
src/browser/json-storage.ts
Normal file
212
src/browser/json-storage.ts
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
export type BrowserStorageTarget = "local" | "session" | (() => Storage | null);
|
||||||
|
|
||||||
|
export type JsonStorageTransform = {
|
||||||
|
encode: (value: string) => string;
|
||||||
|
|
||||||
|
decode: (value: string) => string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type JsonStorageOperation = "get" | "set" | "remove" | "clear";
|
||||||
|
|
||||||
|
export type JsonStorageErrorContext = {
|
||||||
|
operation: JsonStorageOperation;
|
||||||
|
key?: string;
|
||||||
|
error: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CreateJsonStorageOptions = {
|
||||||
|
storage: BrowserStorageTarget;
|
||||||
|
|
||||||
|
transform?: JsonStorageTransform;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* transform.decode가 실패했을 때
|
||||||
|
* 원본 문자열을 일반 JSON으로
|
||||||
|
* 한 번 더 파싱할지 여부
|
||||||
|
*/
|
||||||
|
fallbackToPlainJson?: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 파싱이 불가능한 값을
|
||||||
|
* Storage에서 삭제할지 여부
|
||||||
|
*
|
||||||
|
* @default true
|
||||||
|
*/
|
||||||
|
removeInvalid?: boolean;
|
||||||
|
|
||||||
|
onError?: (context: JsonStorageErrorContext) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type JsonStorage = {
|
||||||
|
get: <T = unknown>(key: string) => T | null;
|
||||||
|
|
||||||
|
set: (key: string, value: unknown) => void;
|
||||||
|
|
||||||
|
remove: (key: string) => void;
|
||||||
|
|
||||||
|
clear: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const resolveStorage = (target: BrowserStorageTarget): Storage | null => {
|
||||||
|
try {
|
||||||
|
if (typeof target === "function") {
|
||||||
|
return target();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof window === "undefined") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return target === "local" ? window.localStorage : window.sessionStorage;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createJsonStorage = (
|
||||||
|
options: CreateJsonStorageOptions,
|
||||||
|
): JsonStorage => {
|
||||||
|
const { fallbackToPlainJson = false, removeInvalid = true } = options;
|
||||||
|
|
||||||
|
const reportError = (
|
||||||
|
operation: JsonStorageOperation,
|
||||||
|
error: unknown,
|
||||||
|
key?: string,
|
||||||
|
): void => {
|
||||||
|
if (key === undefined) {
|
||||||
|
options.onError?.({
|
||||||
|
operation,
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
options.onError?.({
|
||||||
|
operation,
|
||||||
|
key,
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeInvalidValue = (storage: Storage, key: string): void => {
|
||||||
|
if (!removeInvalid) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
storage.removeItem(key);
|
||||||
|
} catch {
|
||||||
|
// 잘못된 값 정리 실패는 무시한다.
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const get = <T = unknown>(key: string): T | null => {
|
||||||
|
const storage = resolveStorage(options.storage);
|
||||||
|
|
||||||
|
if (!storage) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let storedValue: string | null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
storedValue = storage.getItem(key);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError("get", error, key);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (storedValue === null || storedValue.trim() === "") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const decodedValue = options.transform
|
||||||
|
? options.transform.decode(storedValue)
|
||||||
|
: storedValue;
|
||||||
|
|
||||||
|
if (decodedValue.trim() === "") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return JSON.parse(decodedValue) as T;
|
||||||
|
} catch (primaryError: unknown) {
|
||||||
|
if (options.transform && fallbackToPlainJson) {
|
||||||
|
try {
|
||||||
|
return JSON.parse(storedValue) as T;
|
||||||
|
} catch {
|
||||||
|
// 아래 공통 오류 처리로 이동
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
removeInvalidValue(storage, key);
|
||||||
|
|
||||||
|
reportError("get", primaryError, key);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const set = (key: string, value: unknown): void => {
|
||||||
|
const storage = resolveStorage(options.storage);
|
||||||
|
|
||||||
|
if (!storage) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const jsonValue = JSON.stringify(value);
|
||||||
|
|
||||||
|
if (jsonValue === undefined) {
|
||||||
|
throw new TypeError(
|
||||||
|
`Storage value for "${key}" is not JSON serializable.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const storedValue = options.transform
|
||||||
|
? options.transform.encode(jsonValue)
|
||||||
|
: jsonValue;
|
||||||
|
|
||||||
|
storage.setItem(key, storedValue);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError("set", error, key);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const remove = (key: string): void => {
|
||||||
|
const storage = resolveStorage(options.storage);
|
||||||
|
|
||||||
|
if (!storage) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
storage.removeItem(key);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError("remove", error, key);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const clear = (): void => {
|
||||||
|
const storage = resolveStorage(options.storage);
|
||||||
|
|
||||||
|
if (!storage) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
storage.clear();
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError("clear", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return Object.freeze({
|
||||||
|
get,
|
||||||
|
set,
|
||||||
|
remove,
|
||||||
|
clear,
|
||||||
|
});
|
||||||
|
};
|
||||||
178
src/hooks/create/font-size.ts
Normal file
178
src/hooks/create/font-size.ts
Normal file
@@ -0,0 +1,178 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
|
||||||
|
import type {
|
||||||
|
CookieSetOptions,
|
||||||
|
CookieStore,
|
||||||
|
} from "../../browser/cookie-store.js";
|
||||||
|
|
||||||
|
export type UseFontSizeOptions = {
|
||||||
|
/**
|
||||||
|
* 마운트 후 쿠키 값을 읽어
|
||||||
|
* 상태를 다시 동기화할지 여부
|
||||||
|
*
|
||||||
|
* @default true
|
||||||
|
*/
|
||||||
|
hydrateFromCookie?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CreateFontSizeHookOptions<TCookieKey extends string> = {
|
||||||
|
defaultSize: number;
|
||||||
|
minSize: number;
|
||||||
|
maxSize: number;
|
||||||
|
|
||||||
|
cookieStore: CookieStore<TCookieKey>;
|
||||||
|
|
||||||
|
cookieKey: TCookieKey;
|
||||||
|
|
||||||
|
cookieOptions?: CookieSetOptions;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @default "--content-font-size"
|
||||||
|
*/
|
||||||
|
cssVariable?: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook 인스턴스 간 동기화 이벤트
|
||||||
|
*
|
||||||
|
* @default "fontSizeChange"
|
||||||
|
*/
|
||||||
|
eventName?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const assertFiniteNumber = (name: string, value: number): void => {
|
||||||
|
if (!Number.isFinite(value)) {
|
||||||
|
throw new TypeError(`${name} must be a finite number.`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createFontSizeHook = <TCookieKey extends string>(
|
||||||
|
options: CreateFontSizeHookOptions<TCookieKey>,
|
||||||
|
) => {
|
||||||
|
assertFiniteNumber("defaultSize", options.defaultSize);
|
||||||
|
|
||||||
|
assertFiniteNumber("minSize", options.minSize);
|
||||||
|
|
||||||
|
assertFiniteNumber("maxSize", options.maxSize);
|
||||||
|
|
||||||
|
if (options.minSize > options.maxSize) {
|
||||||
|
throw new RangeError("minSize must be less than or equal to maxSize.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const cssVariable = options.cssVariable ?? "--content-font-size";
|
||||||
|
|
||||||
|
const eventName = options.eventName ?? "fontSizeChange";
|
||||||
|
|
||||||
|
const clampFontSize = (value: number): number => {
|
||||||
|
return Math.min(options.maxSize, Math.max(options.minSize, value));
|
||||||
|
};
|
||||||
|
|
||||||
|
const readFontSize = (fallback: number = options.defaultSize): number => {
|
||||||
|
const storedValue = options.cookieStore.get(options.cookieKey);
|
||||||
|
|
||||||
|
if (!storedValue) {
|
||||||
|
return clampFontSize(fallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsedValue = Number.parseInt(storedValue, 10);
|
||||||
|
|
||||||
|
if (Number.isNaN(parsedValue)) {
|
||||||
|
return clampFontSize(fallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
return clampFontSize(parsedValue);
|
||||||
|
};
|
||||||
|
|
||||||
|
const writeFontSize = (value: number): number => {
|
||||||
|
const normalizedValue = clampFontSize(value);
|
||||||
|
|
||||||
|
options.cookieStore.set(
|
||||||
|
options.cookieKey,
|
||||||
|
String(normalizedValue),
|
||||||
|
options.cookieOptions,
|
||||||
|
);
|
||||||
|
|
||||||
|
return normalizedValue;
|
||||||
|
};
|
||||||
|
|
||||||
|
const useFontSize = (
|
||||||
|
defaultSize: number = options.defaultSize,
|
||||||
|
hookOptions: UseFontSizeOptions = {},
|
||||||
|
) => {
|
||||||
|
const { hydrateFromCookie = true } = hookOptions;
|
||||||
|
|
||||||
|
const normalizedDefault = clampFontSize(defaultSize);
|
||||||
|
|
||||||
|
const [fontSize, setFontSizeState] = useState(normalizedDefault);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hydrateFromCookie) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setFontSizeState(readFontSize(normalizedDefault));
|
||||||
|
}, [hydrateFromCookie, normalizedDefault]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof document === "undefined") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
document.documentElement.style.setProperty(cssVariable, `${fontSize}px`);
|
||||||
|
}, [fontSize]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (typeof window === "undefined") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleChange = (event: Event): void => {
|
||||||
|
const detail = event instanceof CustomEvent ? event.detail : undefined;
|
||||||
|
|
||||||
|
const nextValue =
|
||||||
|
typeof detail === "number"
|
||||||
|
? clampFontSize(detail)
|
||||||
|
: readFontSize(options.defaultSize);
|
||||||
|
|
||||||
|
setFontSizeState(nextValue);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener(eventName, handleChange);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener(eventName, handleChange);
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const setFontSize = useCallback((nextValue: number): void => {
|
||||||
|
const normalizedValue = writeFontSize(nextValue);
|
||||||
|
|
||||||
|
setFontSizeState(normalizedValue);
|
||||||
|
|
||||||
|
if (typeof window !== "undefined") {
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent<number>(eventName, {
|
||||||
|
detail: normalizedValue,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return [fontSize, setFontSize] as const;
|
||||||
|
};
|
||||||
|
|
||||||
|
const useFontSizeValue = (hookOptions: UseFontSizeOptions = {}): number => {
|
||||||
|
const [fontSize] = useFontSize(options.defaultSize, hookOptions);
|
||||||
|
|
||||||
|
return fontSize;
|
||||||
|
};
|
||||||
|
|
||||||
|
return Object.freeze({
|
||||||
|
useFontSize,
|
||||||
|
useFontSizeValue,
|
||||||
|
clampFontSize,
|
||||||
|
readFontSize,
|
||||||
|
writeFontSize,
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -8,3 +8,4 @@ export * from "./create/auth.js";
|
|||||||
export * from "./create/loading.js";
|
export * from "./create/loading.js";
|
||||||
export * from "./create/storage.js";
|
export * from "./create/storage.js";
|
||||||
export * from "./create/dialog.js";
|
export * from "./create/dialog.js";
|
||||||
|
export * from "./create/font-size.js";
|
||||||
|
|||||||
1
src/jotai/index.ts
Normal file
1
src/jotai/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from "./persistent-atom.js";
|
||||||
180
src/jotai/persistent-atom.ts
Normal file
180
src/jotai/persistent-atom.ts
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
import { atom, type PrimitiveAtom, type WritableAtom } from "jotai";
|
||||||
|
|
||||||
|
export type SetStateAction<T> = T | ((previous: T) => T);
|
||||||
|
|
||||||
|
export type PersistentAtomStorage = {
|
||||||
|
get: <T = unknown>(key: string) => T | null;
|
||||||
|
|
||||||
|
set: (key: string, value: unknown) => void;
|
||||||
|
|
||||||
|
remove: (key: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PersistentAtomErrorContext = {
|
||||||
|
operation: "hydrate" | "set" | "remove";
|
||||||
|
|
||||||
|
key: string;
|
||||||
|
error: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CreatePersistentAtomOptions<T> = {
|
||||||
|
storage: PersistentAtomStorage;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* true를 반환하면 값을 저장하지 않고
|
||||||
|
* 기존 저장값을 삭제한다.
|
||||||
|
*
|
||||||
|
* 기본값은 null 또는 undefined일 때 true이다.
|
||||||
|
*/
|
||||||
|
shouldRemove?: (value: T) => boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 저장소에서 읽은 값이 유효한 값인지 검사한다.
|
||||||
|
*/
|
||||||
|
validate?: (value: unknown) => boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* validate 검증에 실패한 저장값을 삭제할지 여부
|
||||||
|
*
|
||||||
|
* @default true
|
||||||
|
*/
|
||||||
|
removeInvalid?: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Jotai DevTools에서 표시할 이름
|
||||||
|
*/
|
||||||
|
debugLabel?: string;
|
||||||
|
|
||||||
|
onError?: (context: PersistentAtomErrorContext) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PersistentAtom<T> = WritableAtom<T, [SetStateAction<T>], void> & {
|
||||||
|
readonly hydratedAtom: PrimitiveAtom<boolean>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const HYDRATE = Symbol("kri.persistentAtom.hydrate");
|
||||||
|
|
||||||
|
type HydrateAction<T> = {
|
||||||
|
readonly [HYDRATE]: T;
|
||||||
|
};
|
||||||
|
|
||||||
|
const isHydrateAction = <T>(
|
||||||
|
action: SetStateAction<T> | HydrateAction<T>,
|
||||||
|
): action is HydrateAction<T> => {
|
||||||
|
return typeof action === "object" && action !== null && HYDRATE in action;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createPersistentAtom = <T>(
|
||||||
|
key: string,
|
||||||
|
initialValue: T,
|
||||||
|
options: CreatePersistentAtomOptions<T>,
|
||||||
|
): PersistentAtom<T> => {
|
||||||
|
const valueAtom = atom<T>(initialValue);
|
||||||
|
|
||||||
|
const hydratedAtom = atom(false);
|
||||||
|
|
||||||
|
const shouldRemove =
|
||||||
|
options.shouldRemove ??
|
||||||
|
((value: T): boolean => {
|
||||||
|
return value === null || value === undefined;
|
||||||
|
});
|
||||||
|
|
||||||
|
const reportError = (
|
||||||
|
operation: PersistentAtomErrorContext["operation"],
|
||||||
|
error: unknown,
|
||||||
|
): void => {
|
||||||
|
options.onError?.({
|
||||||
|
operation,
|
||||||
|
key,
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
type InternalAction = SetStateAction<T> | HydrateAction<T>;
|
||||||
|
|
||||||
|
const internalAtom = atom(
|
||||||
|
(get) => {
|
||||||
|
return get(valueAtom);
|
||||||
|
},
|
||||||
|
|
||||||
|
(get, set, action: InternalAction): void => {
|
||||||
|
/*
|
||||||
|
* 저장소에서 읽은 값을 atom에 반영하는
|
||||||
|
* 내부 전용 action이다.
|
||||||
|
*
|
||||||
|
* hydration 과정에서는 값을 다시 저장하지 않는다.
|
||||||
|
*/
|
||||||
|
if (isHydrateAction(action)) {
|
||||||
|
set(valueAtom, action[HYDRATE]);
|
||||||
|
|
||||||
|
set(hydratedAtom, true);
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const previousValue = get(valueAtom);
|
||||||
|
|
||||||
|
const nextValue =
|
||||||
|
typeof action === "function"
|
||||||
|
? (action as (previous: T) => T)(previousValue)
|
||||||
|
: action;
|
||||||
|
|
||||||
|
set(valueAtom, nextValue);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (shouldRemove(nextValue)) {
|
||||||
|
options.storage.remove(key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
options.storage.set(key, nextValue);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError(shouldRemove(nextValue) ? "remove" : "set", error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (options.debugLabel !== undefined) {
|
||||||
|
internalAtom.debugLabel = options.debugLabel;
|
||||||
|
|
||||||
|
hydratedAtom.debugLabel = `${options.debugLabel}:hydrated`;
|
||||||
|
}
|
||||||
|
|
||||||
|
internalAtom.onMount = (setAtom) => {
|
||||||
|
let hydratedValue = initialValue;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const storedValue = options.storage.get<unknown>(key);
|
||||||
|
|
||||||
|
if (storedValue !== null) {
|
||||||
|
const isValid = options.validate ? options.validate(storedValue) : true;
|
||||||
|
|
||||||
|
if (isValid) {
|
||||||
|
hydratedValue = storedValue as T;
|
||||||
|
} else if (options.removeInvalid !== false) {
|
||||||
|
try {
|
||||||
|
options.storage.remove(key);
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError("remove", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: unknown) {
|
||||||
|
reportError("hydrate", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
setAtom({
|
||||||
|
[HYDRATE]: hydratedValue,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 외부에는 일반 SetStateAction만 허용하고,
|
||||||
|
* 내부 HydrateAction은 노출하지 않는다.
|
||||||
|
*/
|
||||||
|
const persistentAtom = Object.assign(internalAtom, {
|
||||||
|
hydratedAtom,
|
||||||
|
}) as unknown as PersistentAtom<T>;
|
||||||
|
|
||||||
|
return persistentAtom;
|
||||||
|
};
|
||||||
24
src/types.ts
24
src/types.ts
@@ -3,3 +3,27 @@ export type ValueOf<T> = T[keyof T];
|
|||||||
export type EnumLikeKey<T extends Record<string, unknown>> = keyof T;
|
export type EnumLikeKey<T extends Record<string, unknown>> = keyof T;
|
||||||
|
|
||||||
export type EnumLikeValue<T extends Record<string, unknown>> = ValueOf<T>;
|
export type EnumLikeValue<T extends Record<string, unknown>> = ValueOf<T>;
|
||||||
|
|
||||||
|
export type SortDirection = "asc" | "desc";
|
||||||
|
|
||||||
|
export type PageRequest<TSortBy extends string = string> = {
|
||||||
|
pageIndex: number;
|
||||||
|
pageSize: number;
|
||||||
|
sortBy: TSortBy;
|
||||||
|
sortDir: SortDirection;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PageResponse<T> = {
|
||||||
|
content: T[];
|
||||||
|
|
||||||
|
totalElements: number;
|
||||||
|
totalPages: number;
|
||||||
|
|
||||||
|
pageIndex: number;
|
||||||
|
pageSize: number;
|
||||||
|
numberOfElements: number;
|
||||||
|
|
||||||
|
first: boolean;
|
||||||
|
last: boolean;
|
||||||
|
empty: boolean;
|
||||||
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user