Skip to content

Commit

Permalink
use debounce value
Browse files Browse the repository at this point in the history
  • Loading branch information
ins0 committed Jan 7, 2025
1 parent 6b8ae9d commit 377b0fc
Showing 1 changed file with 15 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { useDeferredValue } from "react";
import { useRef } from "react";
import React, {
type PropsWithChildren,
startTransition,
useEffect,
useState,
useRef,
} from "react";
import {
ClearPropsContext,
Expand Down Expand Up @@ -38,6 +37,9 @@ import PromiseQueue from "p-queue";
import ComplexityIndicator from "@/components/PasswordCreationField/components/ComplexityIndicator/ComplexityIndicator";
import { type PolicyValidationResult } from "@mittwald/password-tools-js/policy";
import { type RuleValidationResult } from "@mittwald/password-tools-js/rules";
import { useDebounceValue } from "usehooks-ts";

const validationDebounceMilliseconds = 200;

export const defaultPasswordCreationPolicy = Policy.fromDeclaration({
minComplexity: 3,
Expand Down Expand Up @@ -105,12 +107,19 @@ export const PasswordCreationField = flowComponent(
const valueControlType = useRef<"controlled" | "uncontrolled">(
valueFromProps === undefined ? "uncontrolled" : "controlled",
).current;
const [uncontrolledValue, setUncontrolledValue] = useState(
const [uncontrolledValue, setUncontrolledValueRaw] = useState(
defaultValue ?? "",
);
const value =
valueControlType === "controlled" ? valueFromProps : uncontrolledValue;
const deferredValue = useDeferredValue(value);
const [bouncedValue, setDebouncedValue] = useDebounceValue(
value ?? "",
validationDebounceMilliseconds,
);
const setUncontrolledValue = (value: string) => {
setUncontrolledValueRaw(value);
setDebouncedValue(value);
};

const [isPasswordRevealed, setIsPasswordRevealed] = useState(false);
const [isLoading, setIsLoading] = useState(false);
Expand Down Expand Up @@ -143,17 +152,15 @@ export const PasswordCreationField = flowComponent(

useEffect(() => {
setIsLoading(true);
const valueToCheck = deferredValue ?? "";

void promiseQueue.add(async () => {
const validationResult = validationPolicy.validate(valueToCheck);
const validationResult = validationPolicy.validate(bouncedValue);
return Promise.all([
validationResult.isValid,
validationResult.complexity,
...validationResult.ruleResults,
]);
});
}, [deferredValue, validationPolicy]);
}, [bouncedValue, validationPolicy]);

promiseQueue.on("completed", ([isValid, complexity, ...ruleResults]) => {
if (promiseQueue.size === 0) {
Expand Down

0 comments on commit 377b0fc

Please sign in to comment.