aboutsummaryrefslogtreecommitdiffstats
path: root/subprojects/frontend/src/editor/AnalysisErrorNotification.tsx
blob: 591a36008b8944a4d27a74fbb2e100584d83683b (plain) (blame)
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
/*
 * SPDX-FileCopyrightText: 2021-2023 The Refinery Authors <https://refinery.tools/>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import { reaction } from 'mobx';
import { type SnackbarKey, useSnackbar } from 'notistack';
import { useEffect, useState } from 'react';

import type EditorStore from './EditorStore';

function MessageObserver({
  editorStore,
}: {
  editorStore: EditorStore;
}): React.ReactNode {
  const [message, setMessage] = useState(
    editorStore.delayedErrors.semanticsError ?? '',
  );
  // Instead of making this component an `observer`,
  // we only update the message is one is present to make sure that the
  // disappear animation has a chance to complete.
  useEffect(
    () =>
      reaction(
        () => editorStore.delayedErrors.semanticsError,
        (newMessage) => {
          if (newMessage !== undefined) {
            setMessage(newMessage);
          }
        },
        { fireImmediately: false },
      ),
    [editorStore],
  );
  return message;
}

export default function AnalysisErrorNotification({
  editorStore,
}: {
  editorStore: EditorStore;
}): null {
  const { enqueueSnackbar, closeSnackbar } = useSnackbar();
  useEffect(() => {
    let key: SnackbarKey | undefined;
    const disposer = reaction(
      () => editorStore.delayedErrors.semanticsError !== undefined,
      (hasError) => {
        if (hasError) {
          if (key === undefined) {
            key = enqueueSnackbar({
              message: <MessageObserver editorStore={editorStore} />,
              variant: 'error',
              persist: true,
            });
          }
        } else if (key !== undefined) {
          closeSnackbar(key);
          key = undefined;
        }
      },
      { fireImmediately: true },
    );
    return () => {
      disposer();
      if (key !== undefined) {
        closeSnackbar(key);
      }
    };
  }, [editorStore, enqueueSnackbar, closeSnackbar]);
  return null;
}