aboutsummaryrefslogtreecommitdiff
path: root/FrontEnd/src/components/alert/AlertHost.tsx
blob: 59f8f27c5cc9d3e1d94dcce205e7d7224a98bca0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { useEffect, useState } from "react";
import classNames from "classnames";

import { ThemeColor, useC, Text } from "../common";
import IconButton from "../button/IconButton";

import { alertService, AlertInfoWithId } from "./AlertService";

import "./alert.css";

interface AutoCloseAlertProps {
  color: ThemeColor;
  message: Text;
  onDismiss?: () => void;
  onIn?: () => void;
  onOut?: () => void;
}

function Alert({
  color,
  message,
  onDismiss,
  onIn,
  onOut,
}: AutoCloseAlertProps) {
  const c = useC();

  return (
    <div
      className={classNames("cru-alert", `cru-theme-${color}`)}
      onPointerEnter={onIn}
      onPointerLeave={onOut}
    >
      <div className="cru-alert-message">{c(message)}</div>
      <IconButton
        icon="x"
        color="danger"
        className="cru-alert-close-button"
        onClick={onDismiss}
      />
    </div>
  );
}

export default function AlertHost() {
  const [alerts, setAlerts] = useState<AlertInfoWithId[]>([]);

  useEffect(() => {
    const listener = (alerts: AlertInfoWithId[]) => {
      setAlerts(alerts);
    };

    alertService.registerListener(listener);

    return () => {
      alertService.unregisterListener(listener);
    };
  }, []);

  return (
    <div className="alert-container">
      {alerts.map((alert) => {
        return (
          <Alert
            key={alert.id}
            message={alert.message}
            color={alert.color ?? "primary"}
            onIn={() => {
              alertService.clearDismissTimer(alert.id);
            }}
            onOut={() => {
              alertService.resetDismissTimer(alert.id);
            }}
            onDismiss={() => {
              alertService.dismiss(alert.id);
            }}
          />
        );
      })}
    </div>
  );
}