-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathuseSubmitError.ts
More file actions
59 lines (49 loc) · 1.88 KB
/
useSubmitError.ts
File metadata and controls
59 lines (49 loc) · 1.88 KB
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
import { hooks } from 'botframework-webchat';
import { useCallback, useMemo, useState } from 'react';
import { useRefFrom } from 'use-ref-from';
const { useConnectivityStatus, useLocalizer } = hooks;
type ErrorMessageStringMap = ReadonlyMap<SendError, string>;
type SendError = 'empty' | 'offline';
const useSubmitError = ({
attachments,
message
}: Readonly<{
attachments: readonly Readonly<{ blob: Blob | File; thumbnailURL?: URL | undefined }>[];
message: string;
}>) => {
const [connectivityStatus] = useConnectivityStatus();
const [error, setError] = useState<SendError | undefined>();
const localize = useLocalizer();
const submitErrorRef = useRefFrom<'empty' | 'offline' | undefined>(
connectivityStatus !== 'connected' && connectivityStatus !== 'reconnected'
? 'offline'
: !message && !attachments.length
? 'empty'
: undefined
);
const errorMessageStringMap = useMemo<ErrorMessageStringMap>(
() =>
Object.freeze(
new Map<SendError, string>()
.set('empty', localize('SEND_BOX_IS_EMPTY_TOOLTIP_ALT'))
// TODO: [P0] We should add a new string for "Cannot send message while offline."
.set('offline', localize('CONNECTIVITY_STATUS_ALT_FATAL'))
),
[localize]
);
// TODO: we may want to improve this later e.g. to avoid re-render
// Reset visible error if there is a value
const hasValue = !!message?.trim();
if (error === 'empty' && hasValue) {
setError(undefined);
}
const commitLatestError = useCallback(() => {
setError(submitErrorRef.current);
return submitErrorRef.current;
}, [submitErrorRef]);
return useMemo<Readonly<[string | undefined, () => typeof submitErrorRef.current]>>(
() => Object.freeze([error && errorMessageStringMap.get(error), commitLatestError]),
[error, errorMessageStringMap, commitLatestError]
);
};
export default useSubmitError;