fix: contact support button overlap (#22952)

* add: lib folder in tailwind config

* move plainChat and contactForm from lib to components

* Update tailwind-preset.js
This commit is contained in:
Bandhan Majumder
2025-08-07 14:29:21 +00:00
committed by GitHub
parent cabd459682
commit 7c8dbb3ea3
4 changed files with 5 additions and 3 deletions
@@ -0,0 +1,243 @@
"use client";
import { useState } from "react";
import { Button } from "@calcom/ui/components/button";
import { FileUploader, type FileData } from "@calcom/ui/components/file-uploader";
import { Label, TextArea } from "@calcom/ui/components/form";
import { Icon } from "@calcom/ui/components/icon";
import { Popover, PopoverContent, PopoverTrigger } from "@calcom/ui/components/popover";
import { showToast } from "@calcom/ui/components/toast";
interface ContactFormData {
name: string;
email: string;
message: string;
attachments?: FileData[];
}
const PlainContactForm = () => {
const [isOpen, setIsOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSubmitted, setIsSubmitted] = useState(false);
const [isUploadingImage, setIsUploadingImage] = useState(false);
const [data, setData] = useState<{
message: string;
attachmentIds: string[];
}>({
message: "",
attachmentIds: [],
});
const [uploads, setUploads] = useState<
{
attachmentId?: string;
uploading: boolean;
file: File;
id: string;
}[]
>([]);
const handleUpload = async (allFiles: FileData[], newFiles: FileData[], removedFiles: FileData[]) => {
if (newFiles.length > 0) {
const newFile = newFiles[0];
setUploads((prev) => [...prev, { file: newFile.file, uploading: true, id: newFile.id }]);
setIsUploadingImage(true);
const { file } = newFile;
const res = await fetch(`/api/support/upload?name=${file.name}&size=${file.size}`);
if (!res.ok) {
showToast("Error uploading attachment", "error");
setIsUploadingImage(false);
return;
}
const {
uploadFormUrl,
uploadFormData,
attachment: { id: attachmentId },
} = await res.json();
setIsUploadingImage(false);
const formData = new FormData();
uploadFormData.forEach(({ key, value }: any) => {
formData.append(key, value);
});
formData.append("file", file);
const uploadRes = await fetch(uploadFormUrl, {
method: "POST",
body: formData,
});
if (!uploadRes.ok) {
showToast(`Failed while uploading file: ${uploadRes.text}`, "error");
setIsUploadingImage(false);
return;
}
setUploads((prev) =>
prev.map((upload) => (upload.file === file ? { ...upload, uploading: false, attachmentId } : upload))
);
setData((prev) => ({
...prev,
attachmentIds: [...prev.attachmentIds, attachmentId],
}));
setIsUploadingImage(false);
showToast("File uploaded successfully", "success");
} else if (removedFiles.length > 0) {
const removedFile = removedFiles[0];
const file = uploads.find((upload) => upload.id === removedFile.id);
if (!file) {
console.warn("File not found in uploads: ", removedFile.id);
return;
}
setData((prev) => ({
...prev,
attachmentIds: prev.attachmentIds.filter((id) => id !== file.attachmentId),
}));
setUploads((prev) => prev.filter((upload) => upload.id !== removedFile.id));
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsSubmitting(true);
try {
const response = await fetch("/api/support", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
if (!response.ok) {
const errorData = await response.json();
showToast(errorData.message ?? "Failed to submit contact form", "error");
setIsSubmitting(false);
return;
}
setIsSubmitted(true);
setIsSubmitting(false);
setData({
message: "",
attachmentIds: [],
});
} catch (err) {
showToast(err instanceof Error ? err.message : "An error occurred", "error");
setIsSubmitting(false);
}
};
const resetForm = () => {
setIsSubmitted(false);
setData({
message: "",
attachmentIds: [],
});
setUploads([]);
};
return (
<div className="absolute bottom-[1rem] right-[1rem] z-50">
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild className="enabled:hover:bg-subtle bg-subtle shadow-none">
<Button
onClick={() => setIsOpen(true)}
className="bg-subtle text-emphasis flex h-12 w-12 items-center justify-center rounded-full border-none">
<Icon name="message-circle" className="h-6 w-6" />
</Button>
</PopoverTrigger>
<PopoverContent
style={{ maxWidth: "450px", maxHeight: "650px" }}
className="!bg-muted no-scrollbar mb-2 mr-8 w-[450px] overflow-hidden overflow-y-scroll px-6 py-4">
<div className="flex w-full justify-between">
<p className="mb-5 text-lg font-semibold">Contact support</p>
<Button
color="minimal"
variant="button"
StartIcon="x"
size="sm"
onClick={() => setIsOpen(false)}
/>
</div>
<div>
{isSubmitted ? (
<div className="py-4 text-center">
<h4 className="mb-2 text-lg font-medium ">Message Sent</h4>
<p className="text-subtle mb-4 text-sm">
Thank you for contacting us. We&apos;ll get back to you as soon as possible.
</p>
<Button color="primary" className="my-2" onClick={resetForm} variant="button" size="base">
Send Another Message
</Button>
</div>
) : (
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
<div>
<Label htmlFor="message">Describe the issue</Label>
<TextArea
id="message"
name="message"
value={data.message}
onChange={(e) => setData((prev) => ({ ...prev, message: e.target.value }))}
placeholder="Please describe the issue you're facing, e.g. 'Busy slots are marked available', ..., etc."
required
rows={4}
/>
</div>
<div>
<Label>Attachments (optional)</Label>
<FileUploader
id="contact-attachments"
buttonMsg="Add Files"
onFilesChange={handleUpload}
acceptedFileTypes={["images", "videos"]}
multiple={false}
showFilesList
maxFiles={5}
maxFileSize={10 * 1024 * 1024}
disabled={isSubmitting || isUploadingImage}
testId="contact-form-file-upload"
/>
</div>
<div className="mt-4 flex w-full items-center">
<Button
color="secondary"
variant="button"
type="submit"
disabled={isSubmitting || isUploadingImage}
className="w-full">
<div className="flex w-full justify-center">
{isSubmitting ? (
<div className="flex items-center">
<Icon name="loader" className="mr-2 h-4 w-4 animate-spin rounded-full" />
Sending
</div>
) : (
<>
<Icon name="send" className="mr-2 h-4 w-4" />
Send Message
</>
)}
</div>
</Button>
</div>
</form>
)}
</div>
</PopoverContent>
</Popover>
</div>
);
};
export default PlainContactForm;
@@ -4,7 +4,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { showToast } from "@calcom/ui/components/toast";
import PlainContactForm from "../../../lib/plain/PlainContactForm";
import PlainContactForm from "../PlainContactForm";
vi.mock("next-auth/react", () => ({
useSession: vi.fn(),
+317
View File
@@ -0,0 +1,317 @@
"use client";
import { useSession } from "next-auth/react";
import { usePathname, useSearchParams } from "next/navigation";
import Script from "next/script";
import { useEffect, useState, useCallback, useMemo } from "react";
import { IS_PLAIN_CHAT_ENABLED } from "@calcom/lib/constants";
import PlainContactForm from "./PlainContactForm";
declare global {
interface Window {
Plain?: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
init: (config: any) => void;
open: () => void;
};
plainScriptLoaded?: () => void;
__PLAIN_CONFIG__?: PlainChatConfig;
}
}
interface PlainChatConfig {
appId: string;
customerDetails: {
email: string;
emailHash: string;
fullName: string;
shortName: string;
chatAvatarUrl: string;
};
links: Array<{
icon: string;
text: string;
url: string;
}>;
chatButtons: Array<{
icon: string;
text: string;
threadDetails?: {
labelTypeIds: Array<string>;
tierIdentifier: {
externalId: string;
};
};
form?: {
fields: Array<{
type: string;
placeholder: string;
options: Array<{
icon: string;
text: string;
threadDetails: {
labelTypeIds: Array<string>;
tierIdentifier: {
externalId: string;
};
};
onClick?: () => void;
}>;
}>;
};
}>;
entryPoint: {
type: string;
};
hideBranding: boolean;
theme: string;
style: {
brandColor: string;
launcherBackgroundColor: string;
launcherIconColor: string;
};
position: {
zIndex: string;
bottom: string;
right: string;
};
}
const PlainChat = IS_PLAIN_CHAT_ENABLED
? ({ nonce }: { nonce: string | undefined }) => {
const [config, setConfig] = useState<PlainChatConfig | null>(null);
const [isSmallScreen, setIsSmallScreen] = useState(false);
const { data: session } = useSession();
const pathname = usePathname();
const searchParams = useSearchParams();
const shouldOpenPlain = pathname === "/event-types" && searchParams?.has("openPlain");
const userEmail = session?.user?.email;
const isPaidUser = session?.user.belongsToActiveTeam || !!session?.user.org;
const isAppDomain = useMemo(() => {
const restrictedPathsSet = new Set(
(process.env.NEXT_PUBLIC_PLAIN_CHAT_EXCLUDED_PATHS?.split(",") || []).map((path) => path.trim())
);
const pathSegments = pathname?.split("/").filter(Boolean) || [];
return (
typeof window !== "undefined" &&
window.location.origin === process.env.NEXT_PUBLIC_WEBAPP_URL &&
!pathSegments.some((segment) => restrictedPathsSet.has(segment))
);
}, [pathname]);
const checkScreenSize = useCallback(() => {
if (typeof window === "undefined") return;
const isSmall = window.innerWidth < 768;
setIsSmallScreen(isSmall);
if (isSmall && window.Plain) {
const plainElement = document.querySelector("#plain-container");
plainElement?.remove();
window.Plain = undefined;
} else if (!isSmall && window.Plain === undefined) {
window.plainScriptLoaded?.();
}
}, []);
const initConfig = useCallback(async () => {
if (!userEmail) return;
// Check if Plain Chat is enabled
if (!IS_PLAIN_CHAT_ENABLED) {
return;
}
try {
const response = await fetch("/api/plain-hash", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to generate hash: ${errorText}`);
}
const data = await response.json();
if (!data.hash || !data.email || !data.appId) {
throw new Error("Missing required fields in API response");
}
const plainChatConfig: PlainChatConfig = {
appId: data.appId,
customerDetails: {
email: data.email,
shortName: data.shortName,
fullName: data.fullName,
emailHash: data.hash,
chatAvatarUrl: data.chatAvatarUrl,
},
links: [
{
icon: "book",
text: "Documentation",
url: "https://cal.com/docs",
},
{
icon: "chat",
text: "Ask the community",
url: "https://github.com/calcom/cal.com/discussions",
},
],
chatButtons: [
{
icon: "bulb",
text: "Send feedback",
threadDetails: {
labelTypeIds: ["lt_01JFJWP3KECF1YQES6XF212RFW"],
tierIdentifier: { externalId: data.userTier },
},
},
{
icon: "error",
text: "Report an issue",
form: {
fields: [
{
type: "dropdown",
placeholder: "Select severity...",
options: [
{
icon: "support",
text: "I'm unable to use the app",
threadDetails: {
labelTypeIds: ["lt_01JFJWNWAC464N8DZ6YE71YJRF"],
tierIdentifier: { externalId: data.userTier },
},
},
{
icon: "error",
text: "Major functionality degraded",
threadDetails: {
labelTypeIds: ["lt_01JFJWP3KECF1YQES6XF212RFW"],
tierIdentifier: { externalId: data.userTier },
},
},
{
icon: "bug",
text: "Minor annoyance",
threadDetails: {
labelTypeIds: ["lt_01JFJWPC8ADW0PK28JHMJR6NSS"],
tierIdentifier: { externalId: data.userTier },
},
},
],
},
],
},
},
],
entryPoint: {
type: "chat",
},
hideBranding: true,
theme: "auto",
style: {
brandColor: "#FFFFFF",
launcherBackgroundColor: "#262626",
launcherIconColor: "#FFFFFF",
},
position: {
zIndex: "1",
bottom: "20px",
right: "20px",
},
};
plainChatConfig.chatButtons.push({
icon: "chat",
text: "Ask a question",
threadDetails: {
labelTypeIds: ["lt_01JFJWNWAC464N8DZ6YE71YJRF"],
tierIdentifier: { externalId: data.userTier },
},
});
if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
window.__PLAIN_CONFIG__ = plainChatConfig;
}
setConfig(plainChatConfig);
if (shouldOpenPlain) {
const timer = setTimeout(() => {
if (window.Plain) {
window.Plain.open();
}
}, 100);
return () => clearTimeout(timer);
}
} catch (error) {
console.error("Failed to initialize Plain Chat:", error);
}
}, [userEmail, shouldOpenPlain]);
useEffect(() => {
if (!isAppDomain) return;
// Skip initialization if Plain Chat is not enabled
if (!IS_PLAIN_CHAT_ENABLED) return;
checkScreenSize();
window.addEventListener("resize", checkScreenSize);
initConfig();
return () => window.removeEventListener("resize", checkScreenSize);
}, [isAppDomain, checkScreenSize, initConfig, userEmail]);
const plainChatScript = `
window.plainScriptLoaded = function() {
if (window.Plain && ${Boolean(config)}) {
try {
Plain.init(${config ? JSON.stringify(config) : null});
} catch (error) {
console.error("Failed to initialize Plain:", error);
}
}
}
`;
if (!isAppDomain || isSmallScreen || typeof window === "undefined") return null;
if (!isPaidUser) {
return <PlainContactForm />;
}
if (!config) return null;
return (
<>
<Script
nonce={nonce}
id="plain-chat"
src="https://chat.cdn-plain.com/index.js"
strategy="afterInteractive"
onLoad={() => window.plainScriptLoaded?.()}
/>
<Script
nonce={nonce}
id="plain-chat-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{ __html: plainChatScript }}
/>
</>
);
}
: () => null;
export default PlainChat;