260703_01_FST: First Commit
This commit is contained in:
42
registry/components/kri-editor/hooks/useDebouncedChange.ts
Normal file
42
registry/components/kri-editor/hooks/useDebouncedChange.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
|
||||
export function useDebouncedChange(onChange: (html: string) => void, debounceMs: number) {
|
||||
const timerRef = useRef<number | null>(null);
|
||||
const optimisticHtmlRef = useRef<string>("");
|
||||
|
||||
const flushChange = useCallback(
|
||||
(nextHtml: string) => {
|
||||
optimisticHtmlRef.current = nextHtml;
|
||||
onChange(nextHtml);
|
||||
},
|
||||
[onChange]
|
||||
);
|
||||
|
||||
const scheduleChange = useCallback(
|
||||
(nextHtml: string) => {
|
||||
optimisticHtmlRef.current = nextHtml;
|
||||
|
||||
if (!debounceMs || debounceMs <= 0) {
|
||||
onChange(nextHtml);
|
||||
return;
|
||||
}
|
||||
|
||||
if (timerRef.current) window.clearTimeout(timerRef.current);
|
||||
timerRef.current = window.setTimeout(() => {
|
||||
timerRef.current = null;
|
||||
onChange(optimisticHtmlRef.current);
|
||||
}, debounceMs);
|
||||
},
|
||||
[debounceMs, onChange]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timerRef.current) window.clearTimeout(timerRef.current);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { scheduleChange, flushChange, optimisticHtmlRef };
|
||||
}
|
||||
Reference in New Issue
Block a user