2
0

first commit

This commit is contained in:
2024-08-09 00:39:27 +02:00
commit 79688abe2e
5698 changed files with 497838 additions and 0 deletions

View File

@@ -0,0 +1,92 @@
import * as DialogPrimitive from "@radix-ui/react-dialog";
import type { PropsWithChildren, ReactElement } from "react";
import React from "react";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { Icon } from "../..";
import { DialogClose, DialogContent } from "./Dialog";
type ConfirmBtnType =
| { confirmBtn?: never; confirmBtnText?: string }
| { confirmBtnText?: never; confirmBtn?: ReactElement };
export type ConfirmationDialogContentProps = {
cancelBtnText?: string;
isPending?: boolean;
loadingText?: string;
onConfirm?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
title: string;
variety?: "danger" | "warning" | "success";
} & ConfirmBtnType;
export function ConfirmationDialogContent(props: PropsWithChildren<ConfirmationDialogContentProps>) {
return (
<DialogContent type="creation">
<ConfirmationContent {...props} />
</DialogContent>
);
}
export const ConfirmationContent = (props: PropsWithChildren<ConfirmationDialogContentProps>) => {
const { t } = useLocale();
const {
title,
variety,
confirmBtn = null,
confirmBtnText = t("confirm"),
cancelBtnText = t("cancel"),
loadingText = t("loading"),
isPending = false,
onConfirm,
children,
} = props;
return (
<>
<div className="flex">
{variety && (
<div className="mt-0.5 ltr:mr-3">
{variety === "danger" && (
<div className="bg-error mx-auto rounded-full p-2 text-center">
<Icon name="circle-alert" className="h-5 w-5 text-red-600 dark:text-red-100" />
</div>
)}
{variety === "warning" && (
<div className="bg-attention mx-auto rounded-full p-2 text-center">
<Icon name="circle-alert" className="h-5 w-5 text-orange-600" />
</div>
)}
{variety === "success" && (
<div className="bg-success mx-auto rounded-full p-2 text-center">
<Icon name="check" className="h-5 w-5 text-green-600" />
</div>
)}
</div>
)}
<div>
<DialogPrimitive.Title className="font-cal text-emphasis mt-2 text-xl">
{title}
</DialogPrimitive.Title>
<DialogPrimitive.Description className="text-subtle text-sm">
{children}
</DialogPrimitive.Description>
</div>
</div>
<div className="my-5 flex flex-row-reverse gap-x-2 sm:my-8">
{confirmBtn ? (
confirmBtn
) : (
<DialogClose
color="primary"
loading={isPending}
onClick={(e) => onConfirm && onConfirm(e)}
data-testid="dialog-confirmation">
{isPending ? loadingText : confirmBtnText}
</DialogClose>
)}
<DialogClose disabled={isPending}>{cancelBtnText}</DialogClose>
</div>
</>
);
};

View File

@@ -0,0 +1,52 @@
import { Meta } from "@storybook/blocks";
import { Title, CustomArgsTable } from "@calcom/storybook/components";
import { Dialog, DialogContent, DialogFooter, DialogClose, DialogHeader } from "./Dialog";
import * as DialogStories from "./Dialog.stories";
<Meta of={DialogStories} />
<Title title="Dialog" suffix="Brief" subtitle="Version 1.0 — Last Update: 18 Aug 2023" />
## Definition
The `Dialog` component provides a flexible way to create dialogs in your application.
## Structure
The `Dialog` component is composed of the following components:
- `Dialog`: The main component that wraps the entire dialog. It manages the dialog's open and close states.
- `DialogContent`: Represents the content of the dialog. It can have different sizes, types, and an optional icon.
- `DialogHeader`: Renders the header of the dialog, including the title and subtitle.
- `DialogFooter`: Renders the footer of the dialog, which can contain action buttons.
- `DialogClose`: Renders a close button for the dialog.
## Components Arguments
### Dialog
<CustomArgsTable of={Dialog} />
### DialogContent
<CustomArgsTable of={DialogContent} />
### DialogHeader
<CustomArgsTable of={DialogHeader} />
### DialogFooter
<CustomArgsTable of={DialogFooter} />
### DialogClose
<CustomArgsTable of={DialogClose} />
{/* ## Dialog Story
<Canvas of={DialogStories.Default}/> */}

View File

@@ -0,0 +1,87 @@
import type { Meta, StoryObj } from "@storybook/react";
import type { ComponentProps } from "react";
import { Dialog, DialogContent, DialogFooter, DialogClose, DialogHeader } from "./Dialog";
type StoryArgs = ComponentProps<typeof Dialog> &
ComponentProps<typeof DialogContent> &
ComponentProps<typeof DialogHeader> &
ComponentProps<typeof DialogFooter> &
ComponentProps<typeof DialogClose> & {
onClick: (...args: unknown[]) => void;
};
const meta: Meta<StoryArgs> = {
component: Dialog,
parameters: {
nextjs: {
appDirectory: true,
},
},
title: "UI/Dialog",
argTypes: {
title: {
control: "text",
},
description: {
control: "text",
},
type: {
options: ["creation", "confirmation"],
control: {
type: "select",
},
},
open: {
control: "boolean",
},
showDivider: {
control: "boolean",
},
disabled: {
control: "boolean",
},
color: {
options: ["minimal", "primary", "secondary", "emphasis"],
control: {
type: "select",
},
},
onClick: { action: "clicked" }, // this is a storybook action addons action
},
render: ({ title, description, type, open, showDivider, disabled, color, onClick }) => (
<Dialog open={open}>
<DialogContent type={type}>
<DialogHeader title={title} subtitle={description} />
<DialogFooter showDivider={showDivider}>
<DialogClose
disabled={disabled}
color={color}
onClick={() => {
const currentUrl = new URL(window.location.href);
currentUrl.searchParams.set("args", "open:false");
window.open(currentUrl.toString(), "_self");
onClick();
}}
/>
</DialogFooter>
</DialogContent>
</Dialog>
),
};
export default meta;
type Story = StoryObj<StoryArgs>;
export const Default: Story = {
name: "Dialog",
args: {
title: "Example Dialog",
description: "Example Dialog Description",
type: "creation",
open: true,
showDivider: false,
disabled: false,
color: "minimal",
},
};

View File

@@ -0,0 +1,253 @@
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { usePathname, useRouter } from "next/navigation";
import type { ForwardRefExoticComponent, ReactElement, ReactNode } from "react";
import React, { useMemo, useState } from "react";
import { Dialog as PlatformDialogPrimitives, useIsPlatform } from "@calcom/atoms/monorepo";
import classNames from "@calcom/lib/classNames";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import type { IconName } from "../..";
import { Icon } from "../..";
import type { ButtonProps } from "../../components/button";
import { Button } from "../../components/button";
export type DialogProps = React.ComponentProps<(typeof DialogPrimitive)["Root"]> & {
name?: string;
clearQueryParamsOnClose?: string[];
};
const enum DIALOG_STATE {
// Dialog is there in the DOM but not visible.
CLOSED = "CLOSED",
// State from the time b/w the Dialog is dismissed and the time the "dialog" query param is removed from the URL.
CLOSING = "CLOSING",
// Dialog is visible.
OPEN = "OPEN",
}
export function Dialog(props: DialogProps) {
const isPlatform = useIsPlatform();
return !isPlatform ? <WebDialog {...props} /> : <PlatformDialogPrimitives.Dialog {...props} />;
}
function WebDialog(props: DialogProps) {
const router = useRouter();
const pathname = usePathname();
const searchParams = useCompatSearchParams();
const newSearchParams = new URLSearchParams(searchParams ?? undefined);
const { children, name, ...dialogProps } = props;
// only used if name is set
const [dialogState, setDialogState] = useState(dialogProps.open ? DIALOG_STATE.OPEN : DIALOG_STATE.CLOSED);
const shouldOpenDialog = newSearchParams.get("dialog") === name;
if (name) {
const clearQueryParamsOnClose = ["dialog", ...(props.clearQueryParamsOnClose || [])];
dialogProps.onOpenChange = (open) => {
if (props.onOpenChange) {
props.onOpenChange(open);
}
// toggles "dialog" query param
if (open) {
newSearchParams.set("dialog", name);
} else {
clearQueryParamsOnClose.forEach((queryParam) => {
newSearchParams.delete(queryParam);
});
router.push(`${pathname}?${newSearchParams.toString()}`);
}
setDialogState(open ? DIALOG_STATE.OPEN : DIALOG_STATE.CLOSING);
};
if (dialogState === DIALOG_STATE.CLOSED && shouldOpenDialog) {
setDialogState(DIALOG_STATE.OPEN);
}
if (dialogState === DIALOG_STATE.CLOSING && !shouldOpenDialog) {
setDialogState(DIALOG_STATE.CLOSED);
}
// allow overriding
if (!("open" in dialogProps)) {
dialogProps.open = dialogState === DIALOG_STATE.OPEN ? true : false;
}
}
return <DialogPrimitive.Root {...dialogProps}>{children}</DialogPrimitive.Root>;
}
type DialogContentProps = React.ComponentProps<(typeof DialogPrimitive)["Content"]> & {
size?: "xl" | "lg" | "md";
type?: "creation" | "confirmation";
title?: string;
description?: string | JSX.Element | null;
closeText?: string;
actionDisabled?: boolean;
Icon?: IconName;
enableOverflow?: boolean;
};
// enableOverflow:- use this prop whenever content inside DialogContent could overflow and require scrollbar
export const DialogContent = React.forwardRef<HTMLDivElement, DialogContentProps>(
({ children, title, Icon: icon, enableOverflow, type = "creation", ...props }, forwardedRef) => {
const isPlatform = useIsPlatform();
const [Portal, Overlay, Content] = useMemo(
() =>
isPlatform
? [
({ children }: { children: ReactElement | ReactElement[] }) => <>{children}</>,
PlatformDialogPrimitives.DialogOverlay,
PlatformDialogPrimitives.DialogContent,
]
: [DialogPrimitive.Portal, DialogPrimitive.Overlay, DialogPrimitive.Content],
[isPlatform]
);
return (
<Portal>
<Overlay className="fadeIn fixed inset-0 z-50 bg-neutral-800 bg-opacity-70 transition-opacity dark:bg-opacity-70 " />
<Content
{...props}
className={classNames(
"fadeIn bg-default scroll-bar fixed left-1/2 top-1/2 z-50 w-full max-w-[22rem] -translate-x-1/2 -translate-y-1/2 rounded-md text-left shadow-xl focus-visible:outline-none sm:align-middle",
props.size == "xl"
? "px-8 pt-8 sm:max-w-[90rem]"
: props.size == "lg"
? "px-8 pt-8 sm:max-w-[70rem]"
: props.size == "md"
? "px-8 pt-8 sm:max-w-[48rem]"
: "px-8 pt-8 sm:max-w-[35rem]",
"max-h-[95vh]",
enableOverflow ? "overflow-auto" : "overflow-visible",
`${props.className || ""}`
)}
ref={forwardedRef}>
{type === "creation" && (
<div>
<DialogHeader title={title} subtitle={props.description} />
<div data-testid="dialog-creation" className="flex flex-col">
{children}
</div>
</div>
)}
{type === "confirmation" && (
<div className="flex">
{icon && (
<div className="bg-emphasis flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full">
<Icon name={icon} className="text-emphasis h-4 w-4" />
</div>
)}
<div className="ml-4 flex-grow">
<DialogHeader title={title} subtitle={props.description} />
<div data-testid="dialog-confirmation">{children}</div>
</div>
</div>
)}
{!type && children}
</Content>
</Portal>
);
}
);
type DialogHeaderProps = {
title: React.ReactNode;
subtitle?: React.ReactNode;
} & React.HTMLAttributes<HTMLDivElement>;
export function DialogHeader(props: DialogHeaderProps) {
if (!props.title) return null;
return (
<div className="mb-4">
<h3
data-testid="dialog-title"
className="leading-20 text-semibold font-cal text-emphasis pb-1 text-xl"
id="modal-title">
{props.title}
</h3>
{props.subtitle && <p className="text-subtle text-sm">{props.subtitle}</p>}
</div>
);
}
type DialogFooterProps = {
children: React.ReactNode;
showDivider?: boolean;
noSticky?: boolean;
} & React.HTMLAttributes<HTMLDivElement>;
export function DialogFooter(props: DialogFooterProps) {
return (
<div className={classNames("bg-default bottom-0", props?.noSticky ? "" : "sticky", props.className)}>
{props.showDivider && (
// TODO: the -mx-8 is causing overflow in the dialog buttons
<hr data-testid="divider" className="border-subtle -mx-8" />
)}
<div
className={classNames(
"flex justify-end space-x-2 pb-4 pt-4 rtl:space-x-reverse",
!props.showDivider && "pb-8"
)}>
{props.children}
</div>
</div>
);
}
DialogContent.displayName = "DialogContent";
export const DialogTrigger: ForwardRefExoticComponent<
DialogPrimitive.DialogTriggerProps & React.RefAttributes<HTMLButtonElement>
> = React.forwardRef((props, ref) => {
const isPlatform = useIsPlatform();
return !isPlatform ? (
<DialogPrimitive.Trigger {...props} ref={ref} />
) : (
<PlatformDialogPrimitives.DialogTrigger {...props} ref={ref} />
);
});
DialogTrigger.displayName = "DialogTrigger";
type DialogCloseProps = {
"data-testid"?: string;
dialogCloseProps?: React.ComponentProps<(typeof DialogPrimitive)["Close"]>;
children?: ReactNode;
onClick?: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void;
disabled?: boolean;
color?: ButtonProps["color"];
} & React.ComponentProps<typeof Button>;
export function DialogClose(
props: {
"data-testid"?: string;
dialogCloseProps?: React.ComponentProps<(typeof DialogPrimitive)["Close"]>;
children?: ReactNode;
onClick?: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void;
disabled?: boolean;
color?: ButtonProps["color"];
} & React.ComponentProps<typeof Button>
) {
const { t } = useLocale();
const isPlatform = useIsPlatform();
const Close = useMemo(
() => (isPlatform ? PlatformDialogPrimitives.DialogClose : DialogPrimitive.Close),
[isPlatform]
);
return (
<Close asChild {...props.dialogCloseProps}>
{/* This will require the i18n string passed in */}
<Button
data-testid={props["data-testid"] || "dialog-rejection"}
color={props.color || "minimal"}
{...props}>
{props.children ? props.children : t("close")}
</Button>
</Close>
);
}
DialogClose.displayName = "WebDialogClose";

View File

@@ -0,0 +1,140 @@
import { render, screen } from "@testing-library/react";
import { vi } from "vitest";
import { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader } from "./Dialog";
vi.mock("@calcom/lib/hooks/useCompatSearchParams", () => ({
useCompatSearchParams() {
return new URLSearchParams();
},
}));
vi.mock("next/navigation", () => ({
usePathname() {
return "";
},
useSearchParams() {
return new URLSearchParams();
},
useRouter() {
return {
push: vi.fn(),
beforePopState: vi.fn(() => null),
prefetch: vi.fn(() => null),
};
},
}));
const title = "Dialog Header";
const subtitle = "Dialog Subtitle";
const DialogComponent = (props: {
open: boolean;
title?: string;
subtitle?: string;
type?: "creation" | "confirmation";
showDivider?: boolean;
color?: "primary" | "secondary" | "minimal" | "destructive";
}) => {
return (
<Dialog open={props.open}>
<DialogContent type={props.type}>
<div className="flex flex-row justify-center align-middle ">
<DialogHeader title={props.title} subtitle={props.subtitle} />
<p>Dialog Content</p>
<DialogFooter showDivider={props.showDivider}>
<DialogClose color={props.color} />
<p>Dialog Footer</p>
</DialogFooter>
</div>
</DialogContent>
</Dialog>
);
};
describe("Tests for Dialog component", () => {
test("Should render Dialog with header", () => {
render(<DialogComponent open title={title} />);
expect(screen.queryByText("Dialog Header")).toBeInTheDocument();
expect(screen.getByText("Dialog Content")).toBeInTheDocument();
expect(screen.getByText("Dialog Footer")).toBeInTheDocument();
});
test("Should render Dialog without header", () => {
render(<DialogComponent open />);
expect(screen.queryByTestId("dialog-title")).toBeNull();
expect(screen.getByText("Dialog Content")).toBeInTheDocument();
expect(screen.getByText("Dialog Footer")).toBeInTheDocument();
});
test("Should render Dialog with header and subtitle", () => {
render(<DialogComponent open title={title} subtitle={subtitle} />);
expect(screen.queryByText("Dialog Header")).toBeInTheDocument();
expect(screen.queryByText("Dialog Subtitle")).toBeInTheDocument();
expect(screen.getByText("Dialog Content")).toBeInTheDocument();
expect(screen.getByText("Dialog Footer")).toBeInTheDocument();
});
test("Should render Dialog with default type creation", () => {
render(<DialogComponent open />);
expect(screen.getByTestId("dialog-creation")).toBeInTheDocument();
expect(screen.getByText("Dialog Content")).toBeInTheDocument();
expect(screen.getByText("Dialog Footer")).toBeInTheDocument();
});
test("Should render Dialog with type creation", () => {
render(<DialogComponent open type="creation" />);
expect(screen.getByTestId("dialog-creation")).toBeInTheDocument();
expect(screen.getByText("Dialog Content")).toBeInTheDocument();
expect(screen.getByText("Dialog Footer")).toBeInTheDocument();
});
test("Should render Dialog with type confirmation", () => {
render(<DialogComponent open type="confirmation" />);
expect(screen.getByTestId("dialog-confirmation")).toBeInTheDocument();
expect(screen.getByText("Dialog Content")).toBeInTheDocument();
expect(screen.getByText("Dialog Footer")).toBeInTheDocument();
});
test("Should open Dialog", async () => {
const { rerender } = render(<DialogComponent open={false} />);
expect(screen.queryByText("Dialog Content")).not.toBeInTheDocument();
expect(screen.queryByText("Dialog Footer")).not.toBeInTheDocument();
rerender(<DialogComponent open />);
expect(screen.getByText("Dialog Content")).toBeInTheDocument();
expect(screen.getByText("Dialog Footer")).toBeInTheDocument();
});
test("Should close Dialog", async () => {
const { rerender } = render(<DialogComponent open />);
expect(screen.getByText("Dialog Content")).toBeInTheDocument();
expect(screen.getByText("Dialog Footer")).toBeInTheDocument();
rerender(<DialogComponent open={false} />);
expect(screen.queryByText("Dialog Content")).not.toBeInTheDocument();
expect(screen.queryByText("Dialog Footer")).not.toBeInTheDocument();
});
test("Should use color from props in CloseDialog", async () => {
render(<DialogComponent open color="destructive" />);
const closeBtn = screen.getByText("close");
expect(closeBtn.classList.toString()).toContain("hover:text-red-700");
});
test("Should show divider with showDivider", async () => {
render(<DialogComponent open showDivider />);
expect(screen.getByTestId("divider")).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,4 @@
export { Dialog, DialogClose, DialogContent, DialogFooter, DialogHeader, DialogTrigger } from "./Dialog";
export { ConfirmationDialogContent, ConfirmationContent } from "./ConfirmationDialogContent";
export type { ConfirmationDialogContentProps } from "./ConfirmationDialogContent";
export type { DialogProps } from "./Dialog";