📦 EqualifyEverything / equalify-dashboard

📄 toast.tsx · 244 lines
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244import * as React from 'react';
import { Cross2Icon } from '@radix-ui/react-icons';
import * as ToastPrimitive from '@radix-ui/react-toast';

interface ToastPayload {
  title: string;
  description: string;
  status?: 'default' | 'success' | 'error';
  duration?: number;
}

interface ToastContextValue {
  (payload: ToastPayload): void;
  success: (payload: ToastPayload) => void;
  error: (payload: ToastPayload) => void;
}

const ToastContext = React.createContext<ToastContextValue | null>(null);
const ToastContextImpl = React.createContext<{
  toastElementsMapRef: React.MutableRefObject<Map<string, HTMLLIElement>>;
  sortToasts: () => void;
} | null>(null);

const ANIMATION_OUT_DURATION = 350;

const CheckmarkIcon = () => <div aria-hidden className="checkmark" />;
const ErrorIcon = () => <div aria-hidden className="error" />;

export const Toasts: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [toasts, setToasts] = React.useState<Map<string, ToastPayload>>(new Map());
  const toastElementsMapRef = React.useRef<Map<string, HTMLLIElement>>(new Map());
  const viewportRef = React.useRef<HTMLOListElement | null>(null);

  const sortToasts = React.useCallback(() => {
    const toastElements = Array.from(toastElementsMapRef.current).reverse();
    const heights: number[] = [];

    toastElements.forEach(([, toast], index) => {
      if (!toast) return;
      const height = toast.clientHeight;
      heights.push(height);
      const frontToastHeight = heights[0];
      toast.setAttribute('data-front', String(index === 0));
      toast.setAttribute('data-hidden', String(index > 2));
      toast.style.setProperty('--index', String(index));
      toast.style.setProperty('--height', `${height}px`);
      toast.style.setProperty('--front-height', `${frontToastHeight}px`);
      const hoverOffsetY = heights
        .slice(0, index)
        .reduce((res, next) => (res += next), 0);
      toast.style.setProperty('--hover-offset-y', `-${hoverOffsetY}px`);
    });
  }, []);

  const handleAddToast = React.useCallback((toast: ToastPayload) => {
    setToasts((currentToasts) => {
      const newMap = new Map(currentToasts);
      newMap.set(String(Date.now()), {
        ...toast,
        status: toast.status || 'default',
      });
      return newMap;
    });
  }, []);

  const handleRemoveToast = React.useCallback((key: string) => {
    setToasts((currentToasts) => {
      const newMap = new Map(currentToasts);
      newMap.delete(key);
      return newMap;
    });
  }, []);

  const handleDispatchDefault = React.useCallback(
    (payload: ToastPayload) =>
      handleAddToast({ ...payload, status: 'default' }),
    [handleAddToast],
  );

  const handleDispatchSuccess = React.useCallback(
    (payload: ToastPayload) =>
      handleAddToast({ ...payload, status: 'success' }),
    [handleAddToast],
  );

  const handleDispatchError = React.useCallback(
    (payload: ToastPayload) => handleAddToast({ ...payload, status: 'error' }),
    [handleAddToast],
  );

  React.useEffect(() => {
    const viewport = viewportRef.current;

    if (viewport) {
      const handleFocus = () => {
        toastElementsMapRef.current.forEach((toast) => {
          toast.setAttribute('data-hovering', 'true');
        });
      };

      const handleBlur = (event: FocusEvent) => {
        if (
          !viewport.contains(event.target as Node) ||
          viewport === event.target
        ) {
          toastElementsMapRef.current.forEach((toast) => {
            toast.setAttribute('data-hovering', 'false');
          });
        }
      };

      viewport.addEventListener('pointermove', handleFocus);
      viewport.addEventListener('pointerleave', handleBlur);
      viewport.addEventListener('focusin', handleFocus);
      viewport.addEventListener('focusout', handleBlur);
      return () => {
        viewport.removeEventListener('pointermove', handleFocus);
        viewport.removeEventListener('pointerleave', handleBlur);
        viewport.removeEventListener('focusin', handleFocus);
        viewport.removeEventListener('focusout', handleBlur);
      };
    }
  }, []);

  React.useEffect(() => {
    ToastManager.getInstance().setAddToastFunction(handleAddToast);
  }, [handleAddToast]);

  return (
    <ToastContext.Provider
      value={React.useMemo(
        () =>
          Object.assign(handleDispatchDefault, {
            success: handleDispatchSuccess,
            error: handleDispatchError,
          }),
        [handleDispatchDefault, handleDispatchSuccess, handleDispatchError],
      )}
    >
      <ToastContextImpl.Provider
        value={React.useMemo(
          () => ({
            toastElementsMapRef,
            sortToasts,
          }),
          [sortToasts],
        )}
      >
        <ToastPrimitive.Provider swipeDirection="right">
          {children}
          {Array.from(toasts).map(([key, toast]) => (
            <Toast
              key={key}
              id={key}
              toast={toast}
              onOpenChange={(open) => {
                if (!open) {
                  toastElementsMapRef.current.delete(key);
                  sortToasts();
                  setTimeout(() => {
                    handleRemoveToast(key);
                  }, ANIMATION_OUT_DURATION);
                }
              }}
            />
          ))}
          <ToastPrimitive.Viewport
            ref={viewportRef}
            className="ToastViewport"
          />
        </ToastPrimitive.Provider>
      </ToastContextImpl.Provider>
    </ToastContext.Provider>
  );
};

class ToastManager {
  private static instance: ToastManager;
  private addToast: (toast: ToastPayload) => void = () => {};

  private constructor() {}

  public static getInstance(): ToastManager {
    if (!ToastManager.instance) {
      ToastManager.instance = new ToastManager();
    }
    return ToastManager.instance;
  }

  public setAddToastFunction(addToastFunction: (toast: ToastPayload) => void) {
    this.addToast = addToastFunction;
  }

  public success(toast: ToastPayload) {
    this.addToast({ ...toast, status: 'success' });
  }

  public error(toast: ToastPayload) {
    this.addToast({ ...toast, status: 'error' });
  }

  public default(toast: ToastPayload) {
    this.addToast({ ...toast, status: 'default' });
  }
}

export const toast = ToastManager.getInstance();

const Toast: React.FC<{
  toast: ToastPayload;
  id: string;
  onOpenChange: (open: boolean) => void;
}> = ({ toast, id, onOpenChange }) => {
  const ref = React.useRef<HTMLLIElement | null>(null);
  const { sortToasts, toastElementsMapRef } =
    React.useContext(ToastContextImpl)!;

  React.useLayoutEffect(() => {
    if (ref.current) {
      toastElementsMapRef.current.set(id, ref.current);
      sortToasts();
    }
  }, [id, sortToasts, toastElementsMapRef]);

  return (
    <ToastPrimitive.Root
      ref={ref}
      type="foreground"
      duration={toast.duration}
      className="ToastRoot"
      onOpenChange={onOpenChange}
    >
      <div className="ToastInner" data-status={toast.status}>
        {toast.status === 'success' && <CheckmarkIcon />}
        {toast.status === 'error' && <ErrorIcon />}
        <ToastPrimitive.Title className="ToastTitle">{toast.title}</ToastPrimitive.Title>
        <ToastPrimitive.Description className="ToastDescription">{toast.description}</ToastPrimitive.Description>
        <ToastPrimitive.Close aria-label="Close" className="ToastClose">
          <Cross2Icon />
        </ToastPrimitive.Close>
      </div>
    </ToastPrimitive.Root>
  );
};