refactor: use getCalculatedTransitionDuration on Toast

This commit is contained in:
p-sw 2024-08-07 19:14:18 +09:00
parent 054568a2ec
commit 371453b544

View File

@ -1,5 +1,10 @@
import { type VariantProps, useDocument, vcn } from "@pswui-lib"; import {
import React, { useEffect, useId, useRef } from "react"; type VariantProps,
getCalculatedTransitionDuration,
useDocument,
vcn,
} from "@pswui-lib";
import React, { type MutableRefObject, useEffect, useId, useRef } from "react";
import ReactDOM from "react-dom"; import ReactDOM from "react-dom";
import { import {
@ -58,42 +63,15 @@ const ToastTemplate = ({
return () => clearTimeout(timeout); return () => clearTimeout(timeout);
} }
if (toastData.life === "dead") { if (toastData.life === "dead") {
let transitionDuration: { let calculatedTransitionDurationMs = 1;
value: number; if (ref.current)
unit: string; calculatedTransitionDurationMs = getCalculatedTransitionDuration(
} | null; ref as MutableRefObject<HTMLDivElement>,
if (!ref.current) {
transitionDuration = null;
} else if (ref.current.computedStyleMap !== undefined) {
transitionDuration = ref.current
.computedStyleMap()
.get("transition-duration") as { value: number; unit: string };
} else {
const style = /(\d+(\.\d+)?)(.+)/.exec(
window.getComputedStyle(ref.current).transitionDuration,
); );
transitionDuration = style
? {
value: Number.parseFloat(style[1] ?? "0"),
unit: style[3] ?? style[2] ?? "s",
}
: null;
}
if (!transitionDuration) {
delete toasts[id];
notify();
return;
}
const calculatedTransitionDuration =
transitionDuration.value *
({
s: 1000,
ms: 1,
}[transitionDuration.unit] ?? 1);
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
delete toasts[id]; delete toasts[id];
notify(); notify();
}, calculatedTransitionDuration); }, calculatedTransitionDurationMs);
return () => clearTimeout(timeout); return () => clearTimeout(timeout);
} }
}, [id, toastData.life, toastData.closeTimeout]); }, [id, toastData.life, toastData.closeTimeout]);