import { SerializedError } from '@reduxjs/toolkit';
import { FetchBaseQueryError } from '@reduxjs/toolkit/query';
import React, {
FC, useEffect, useRef, useState,
} from 'react';
import AUNotificationComponent from './AUNotificationComponent';
import AUContentToggleComponent from './AUContentToggleComponent';
import { useUserContext } from '../lib/context';
type LinkAction = {
label: string;
href: string;
};
type Props = {
/**
* An error with its own header and message. The component shows it as it is.
* It has no default texts, no details and no default link.
*/
error?: AU.IError;
/** Shows the status before the header. This applies only to `error`. */
withStatus?: boolean;
/**
* A raw error from a failed request.
* The component shows a friendly header and message. The raw error is behind a toggle.
*/
fetchError?: FetchBaseQueryError,
/** A raw error from code. It is shown in the same way as `fetchError`. */
serializedError?: SerializedError,
/** The type of the notification. The default is `warning`. */
type?: 'warning' | 'attention' | 'confirm' | 'information';
/**
* Replaces the default message. It is plain text.
* Without `error`, `fetchError` and `serializedError`, the component shows this message
* (and `header`) in the same layout, without a raw error and without a details toggle.
* Use it for a condition that is not a failed request.
*/
message?: string;
/** Replaces the default header. Works without a raw error in the same way as `message`. */
header?: string;
/** Does not show the raw error and its toggle. Use it where the space is small. */
hideDetails?: boolean;
/**
* Replaces single texts of the component: header, message, status link, toggle and copy texts.
* `header` and `message` have priority over these texts.
* A text that is not given comes from `language`.
*/
texts?: Partial;
/**
* The language (`da` or `en`) of the texts that the component shows by itself.
* Without it, the component uses the language of the page (``).
*/
language?: string;
/**
* The first link button. It opens in a new tab.
* The default is a link to the system status page.
* Pass `null` for no default link.
*/
primaryAction?: LinkAction | null;
/**
* A second link button.
* The default is a link to support. The link depends on the signed-in user:
* students get the student support page and all others get the employee support page.
* When no user is signed in, the component shows one inline button
* that links to a support page for all groups.
* Pass `null` for no default link.
*/
secondaryAction?: LinkAction | null;
/** Elements for the actions area of the notification. */
actions?: React.JSX.Element[];
};
type Language = 'da' | 'en';
// All texts that the component shows by itself.
type Texts = {
header: string;
message: string;
status: string;
support: string;
show: string;
hide: string;
copy: string;
copied: string;
code: string;
};
const statusUrl = 'https://serviceinfo.au.dk/';
const studentSupportUrl = 'https://studerende.au.dk/it-support';
const employeeSupportUrl = 'https://medarbejdere.au.dk/administration/it/ithovedomraader/';
const generalSupportUrl = 'https://medarbejdere.au.dk/administration/it/au-it/';
// A user is a student when the name of any group contains "Studerende".
const isStudent = (user: AU.IUserContext) => user.memberOfGroups
.some((group) => group.name.toLowerCase().includes('studerende'));
const builtInTexts: Record = {
en: {
header: 'Oops! Something went wrong :(',
message: 'We cannot show your content right now. Please try again later.',
status: 'View operational status',
support: 'Contact support',
show: 'Show error code',
hide: 'Hide error code',
copy: 'Copy error code',
copied: 'Copied!',
code: 'Error code',
},
da: {
header: 'Ups! Noget gik galt :(',
message: 'Vi kan ikke vise dit indhold lige nu. Prøv igen senere.',
status: 'Se driftstatus for systemer',
support: 'Kontakt support',
show: 'Vis fejlkode',
hide: 'Skjul fejlkode',
copy: 'Kopier fejlkode',
copied: 'Kopieret!',
code: 'Fejlkode',
},
};
// Each text comes from the texts that the caller passes in.
// A text that is not passed in comes from the language prop, or else from the page language.
const getTexts = (texts?: Partial, language?: string): Texts => {
const fallback = builtInTexts[(language ?? document.documentElement.lang) === 'en' ? 'en' : 'da'];
const given = Object.entries(texts ?? {}).filter(([, text]) => text !== undefined);
return { ...fallback, ...Object.fromEntries(given) };
};
type Raw = { code?: string | number, body: string };
const hasCode = (raw: Raw) => raw.code !== undefined && raw.code !== '';
// Shows raw text as plain text. Indentation is kept and long lines wrap.
const RawText: FC<{ raw: Raw, codeLabel: string }> = ({ raw, codeLabel }) => (
{hasCode(raw) && (
<>
{`${codeLabel} ${raw.code}`}
>
)}
{raw.body.split('\n').map((line, i) => (
// eslint-disable-next-line react/no-array-index-key
{i > 0 &&
}
{line.replace(/^ +/, (spaces) => '\u00A0'.repeat(spaces.length))}
))}
);
// A Delphinus inline button that is a span, so that it looks like plain text with an icon.
// The role, tab stop and key handling give it the same behaviour as a button.
const TextButton: FC<{
label: string,
icon: string,
onClick?: () => void,
className?: string,
expanded?: boolean,
}> = ({
label, icon, onClick = undefined, className = undefined, expanded = undefined,
}) => (
{
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
e.currentTarget.click();
}
}}
>
{label}
);
// The copied text keeps normal spaces.
const CopyButton: FC<{ text: string, texts: Texts }> = ({ text, texts }) => {
const [copied, setCopied] = useState(false);
const timer = useRef(undefined);
useEffect(() => () => window.clearTimeout(timer.current), []);
const copy = () => {
navigator.clipboard.writeText(text).then(() => {
setCopied(true);
window.clearTimeout(timer.current);
timer.current = window.setTimeout(() => setCopied(false), 1200);
}).catch(() => undefined);
};
return (
);
};
// The raw error is hidden until the user opens the toggle. The copy button shows while it is open.
const RawDetails: FC<{ raw: Raw, texts: Texts }> = ({ raw, texts }) => {
const [open, setOpen] = useState(false);
const copyText = `${hasCode(raw) ? `${texts.code} ${raw.code}\n` : ''}${raw.body}`;
const icon = open ? 'collapse' : 'expand';
return (
setOpen(button.getAttribute('aria-expanded') === 'true')}
>
<>
{open && }
>
);
};
const Actions: FC<{
primary?: LinkAction,
secondary?: LinkAction,
inline?: LinkAction,
}> = ({ primary, secondary, inline = undefined }) => (
);
const AUErrorComponent: FC = ({
error: auError = undefined,
fetchError = undefined,
serializedError = undefined,
withStatus = false,
type = 'warning',
message: friendlyMessage = undefined,
header: friendlyHeader = undefined,
hideDetails = false,
texts = undefined,
language = undefined,
primaryAction = undefined,
secondaryAction = undefined,
actions = undefined,
}) => {
const t = getTexts(texts, language);
const user = useUserContext();
// The primary action is the system status link, unless the caller passes another one or null.
const statusAction = { label: t.status, href: statusUrl };
const primary = primaryAction === null ? undefined : (primaryAction ?? statusAction);
// The secondary action is the support link, unless the caller passes another one or null.
// The link depends on the user. Without a user, one inline button links to the general page.
let secondary: LinkAction | undefined;
let inlineLink: LinkAction | undefined;
if (secondaryAction) {
secondary = secondaryAction;
} else if (secondaryAction === undefined) {
if (!user) {
inlineLink = { label: t.support, href: generalSupportUrl };
} else {
secondary = {
label: t.support,
href: isStudent(user) ? studentSupportUrl : employeeSupportUrl,
};
}
}
// The friendly message, with the raw error (when there is one) behind the details toggle.
const friendly = (raw?: Raw) => (
{friendlyMessage ?? t.message}
,
...(hideDetails || !raw ? [] : []),
...(primary || secondary || inlineLink
? []
: []),
]}
/>
);
if (auError) {
const { status, header, message } = auError;
return (
,
]}
/>
);
}
if (fetchError && 'error' in fetchError) {
const { status, error } = fetchError;
return friendly({ code: status, body: error });
}
if (fetchError && 'data' in fetchError) {
const { status, data } = fetchError;
return friendly({ code: status, body: JSON.stringify(data, null, 2) });
}
if (serializedError && 'message' in serializedError) {
const { code, message } = serializedError;
return friendly({ code, body: message || '' });
}
// No error at all, but own texts: the friendly layout without a raw part.
const hasOwnTexts = friendlyHeader !== undefined || friendlyMessage !== undefined;
if (!auError && !fetchError && !serializedError && hasOwnTexts) {
return friendly();
}
return null;
};
AUErrorComponent.displayName = 'AUErrorComponent';
export default AUErrorComponent;