Files
cc-switch/src/components/providers/forms/hooks/useCodexTomlValidation.ts

78 lines
1.8 KiB
TypeScript
Raw Normal View History

import { useState, useCallback, useEffect, useRef } from "react";
import TOML from "smol-toml";
/**
* Codex config.toml Hook
* 使 smol-toml TOML debounce
*/
export function useCodexTomlValidation() {
const [configError, setConfigError] = useState("");
const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
/**
* TOML
* @param tomlText - TOML
* @returns
*/
const validateToml = useCallback((tomlText: string): boolean => {
// 空字符串视为合法(允许为空)
if (!tomlText.trim()) {
setConfigError("");
return true;
}
try {
TOML.parse(tomlText);
setConfigError("");
return true;
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "TOML 格式错误";
setConfigError(errorMessage);
return false;
}
}, []);
/**
* debounce 500ms
* @param tomlText - TOML
*/
const debouncedValidate = useCallback(
(tomlText: string) => {
// 清除之前的定时器
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
// 设置新的定时器
debounceTimerRef.current = setTimeout(() => {
validateToml(tomlText);
}, 500);
},
[validateToml],
);
/**
*
*/
const clearError = useCallback(() => {
setConfigError("");
}, []);
// 清理定时器
useEffect(() => {
return () => {
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
};
}, []);
return {
configError,
validateToml,
debouncedValidate,
clearError,
};
}