initial commit after split
This commit is contained in:
73
webui/src/components/DismissibleAlert.tsx
Normal file
73
webui/src/components/DismissibleAlert.tsx
Normal file
@@ -0,0 +1,73 @@
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import { X } from "lucide-react";
|
||||
|
||||
type AlertTone = "success" | "info" | "warning" | "danger";
|
||||
|
||||
type DismissibleAlertProps = {
|
||||
tone?: AlertTone;
|
||||
children: ReactNode;
|
||||
dismissible?: boolean;
|
||||
className?: string;
|
||||
compact?: boolean;
|
||||
floating?: boolean;
|
||||
resetKey?: string | number;
|
||||
};
|
||||
|
||||
let floatingAlertRoot: HTMLElement | null = null;
|
||||
|
||||
function getFloatingAlertRoot(): HTMLElement | null {
|
||||
if (typeof document === "undefined") return null;
|
||||
if (floatingAlertRoot?.isConnected) return floatingAlertRoot;
|
||||
|
||||
const existing = document.getElementById("app-floating-alerts");
|
||||
if (existing) {
|
||||
floatingAlertRoot = existing;
|
||||
return floatingAlertRoot;
|
||||
}
|
||||
|
||||
floatingAlertRoot = document.createElement("div");
|
||||
floatingAlertRoot.id = "app-floating-alerts";
|
||||
floatingAlertRoot.className = "alert-floating-stack";
|
||||
floatingAlertRoot.setAttribute("aria-label", "Application notices");
|
||||
document.body.appendChild(floatingAlertRoot);
|
||||
return floatingAlertRoot;
|
||||
}
|
||||
|
||||
export default function DismissibleAlert({
|
||||
tone = "info",
|
||||
children,
|
||||
dismissible = true,
|
||||
className = "",
|
||||
compact = false,
|
||||
floating = false,
|
||||
resetKey
|
||||
}: DismissibleAlertProps) {
|
||||
const [visible, setVisible] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
setVisible(true);
|
||||
}, [resetKey, children]);
|
||||
|
||||
if (!visible) return null;
|
||||
|
||||
const role = tone === "danger" || tone === "warning" ? "alert" : "status";
|
||||
const alert = (
|
||||
<div
|
||||
className={`alert ${tone}${compact ? " compact-alert" : ""}${floating ? " alert-floating" : ""} alert-dismissible ${className}`.trim()}
|
||||
role={role}
|
||||
aria-live={role === "alert" ? "assertive" : "polite"}
|
||||
>
|
||||
<div className="alert-message">{children}</div>
|
||||
{dismissible && (
|
||||
<button type="button" className="alert-dismiss" aria-label="Dismiss notice" onClick={() => setVisible(false)}>
|
||||
<X size={16} strokeWidth={2.4} aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!floating) return alert;
|
||||
const root = getFloatingAlertRoot();
|
||||
return root ? createPortal(alert, root) : alert;
|
||||
}
|
||||
Reference in New Issue
Block a user