Skip to content

Commit

Permalink
#342: Improve readability of the Notice Props type def, forward the m…
Browse files Browse the repository at this point in the history
…ouse event to the onClose callback
  • Loading branch information
garronej committed Nov 11, 2024
1 parent 143a6d1 commit 2932c91
Showing 1 changed file with 35 additions and 29 deletions.
64 changes: 35 additions & 29 deletions src/Notice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,38 @@ import { useConstCallback } from "./tools/powerhooks/useConstCallback";
import { createComponentI18nApi } from "./i18n";
import { useAnalyticsId } from "./tools/useAnalyticsId";

export type NoticeProps = {
id?: string;
className?: string;
classes?: Partial<Record<"root" | "title" | "close", string>>;
title: NonNullable<ReactNode>;
style?: CSSProperties;
} & (NoticeProps.NonClosable | NoticeProps.Closable);
export type NoticeProps = NoticeProps.NonClosable | NoticeProps.Closable;

export namespace NoticeProps {
export type NonClosable = {
type Common = {
id?: string;
className?: string;
classes?: Partial<Record<"root" | "title" | "close", string>>;
title: NonNullable<ReactNode>;
style?: CSSProperties;
};

export type NonClosable = Common & {
isClosable?: false;
isClosed?: undefined;
onClose?: undefined;

isClosed?: never;
onClose?: never;
};

export type Closable = {
isClosable: true;
} & (Closable.Controlled | Closable.Uncontrolled);
export type Closable = Closable.Controlled | Closable.Uncontrolled;

export namespace Closable {
export type Controlled = {
export type Controlled = Common & {
isClosable: true;
isClosed: boolean;
onClose: () => void;
onClose: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
};

export type Uncontrolled = {
isClosed?: undefined;
onClose?: () => void;
export type Uncontrolled = Common & {
isClosable: true;
onClose?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;

isClosed?: never;
};
}
}
Expand Down Expand Up @@ -107,16 +111,18 @@ export const Notice = memo(
buttonElement.focus();
}, [buttonElement]);

const onCloseButtonClick = useConstCallback(() => {
if (props_isClosed === undefined) {
//Uncontrolled
setIsClosed(true);
onClose?.();
} else {
//Controlled
onClose();
const onCloseButtonClick = useConstCallback(
(event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
if (props_isClosed === undefined) {
//Uncontrolled
setIsClosed(true);
onClose?.(event);
} else {
//Controlled
onClose(event);
}
}
});
);

const { t } = useTranslation();

Expand All @@ -133,8 +139,8 @@ export const Notice = memo(
style={style}
{...rest}
>
<div className="fr-container">
<div className="fr-notice__body">
<div className={fr.cx("fr-container")}>
<div className={fr.cx("fr-notice__body")}>
<p className={cx(fr.cx(`fr-notice__title`), classes.title)}>{title}</p>
{/* TODO: Use our button once we have one */}
{isClosable && (
Expand Down

0 comments on commit 2932c91

Please sign in to comment.