-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuseStompNotifications.tsx
102 lines (91 loc) · 3.41 KB
/
useStompNotifications.tsx
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
import {useSnackbar} from 'notistack';
import type {OptionsObject, VariantType} from 'notistack';
import {useCallback, useEffect, useState} from 'react';
import * as React from 'react';
import {useStompCtx} from './useStompCtx';
export type UseStompNotificationsProps<T, M> = [
T[],
(otherChannelOrMessage: string | T, message?: M) => void,
boolean
];
export type StompNotification<T> = {
id: string;
content: T;
dismiss: () => void;
variant?: VariantType;
};
export type StompNotistackOptions<T> = Omit<OptionsObject, 'action' | 'key'> & {
action: (dismiss: () => void) => React.ReactNode;
parseMessage?: (message: StompNotification<T>) => React.ReactNode;
parseVariant?: (message: StompNotification<T>) => VariantType;
};
export default function useStompNotifications<
ReceiveMessage,
SendMessage = any
>(
channel: string,
options?: StompNotistackOptions<ReceiveMessage>
): UseStompNotificationsProps<StompNotification<ReceiveMessage>, SendMessage> {
const context = useStompCtx();
const {closeSnackbar, enqueueSnackbar} = useSnackbar();
const [messages, setMessages] = useState<
StompNotification<ReceiveMessage>[]
>([]);
const send = useCallback(
(otherChannelOrMessage, message) => {
context.send(
otherChannelOrMessage && message
? otherChannelOrMessage
: channel,
message
);
},
[channel, context.send]
);
useEffect(() => {
if (context.connected) {
const subscription = context.subscribeSync(
channel,
(messages, added, removed) => {
added.forEach((item) => {
enqueueSnackbar(
options.parseMessage
? options.parseMessage(item)
: item.content,
{
key: item.id,
disableWindowBlurListener: true,
ClickAwayListenerProps: {
mouseEvent: false,
touchEvent: false
},
...options,
...(options.action
? {
action: options.action(() => {
closeSnackbar(item.id);
})
}
: {}),
onClose: () => {
item.dismiss();
},
variant: options.parseVariant
? options.parseVariant(item)
: item.variant || 'info'
}
);
});
removed.forEach((item) => {
closeSnackbar(item.id);
});
setMessages(() => messages);
}
);
return () => {
subscription();
};
}
}, [channel, context.connected]);
return [messages, send, context.connected];
}