Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Move share button #3103

Merged
merged 24 commits into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from 22 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions components/form-builder/app/edit/Edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { useTemplateStore } from "../../store";
import { getQuestionNumber, sortByLayout } from "../../util";
import { Panel } from "../settings-modal/panel";
import { cleanInput } from "@formbuilder/util";
import { SaveButton } from "../shared/SaveButton";

export const Edit = () => {
const { t } = useTranslation("form-builder");
Expand Down Expand Up @@ -85,6 +86,9 @@ export const Edit = () => {
return (
<>
<h1 className="visually-hidden">{t("edit")}</h1>
<div className="mb-4">
<SaveButton />
</div>
<Panel />
<RichTextLocked
className="rounded-t-lg"
Expand Down
1 change: 0 additions & 1 deletion components/form-builder/app/navigation/EditNavigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { QuestionsIcon, TranslateIcon } from "@components/form-builder/icons";
export const EditNavigation = () => {
const { t } = useTranslation("form-builder");
const { activePathname } = useActivePathname();

return (
<div className="relative flex max-w-[800px] flex-col tablet:flex-row">
<div className="flex">
Expand Down
6 changes: 0 additions & 6 deletions components/form-builder/app/navigation/LeftNavigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import React from "react";
import { useTranslation } from "next-i18next";
import { DesignIcon, PreviewIcon, PublishIcon, GearIcon, MessageIcon } from "../../icons";
import { useTemplateContext } from "@components/form-builder/hooks";
import { SaveButton } from "../shared/SaveButton";
import { useTemplateStore } from "../../store/useTemplateStore";
import { useSession } from "next-auth/react";
import { useActivePathname, cleanPath } from "../../hooks/useActivePathname";
Expand Down Expand Up @@ -67,11 +66,6 @@ export const LeftNavigation = () => {
{t("responsesNavLabel")}
</NavLink>
</li>
{!isPublished && activePathname === "/form-builder/edit" && (
<li>
<SaveButton />
</li>
)}
</ul>
</nav>
);
Expand Down
4 changes: 3 additions & 1 deletion components/form-builder/app/shared/DownloadFileButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,14 @@ export const DownloadFileButton = ({
showInfo = true,
buttonText,
autoShowDialog = false,
theme = "secondary",
}: {
className?: string;
onClick?: any; // eslint-disable-line @typescript-eslint/no-explicit-any
showInfo?: boolean;
buttonText?: string;
autoShowDialog?: boolean;
theme?: "primary" | "secondary";
}) => {
const { t, i18n } = useTranslation("form-builder");
const { getSchema, form, name } = useTemplateStore((s) => ({
Expand Down Expand Up @@ -114,7 +116,7 @@ export const DownloadFileButton = ({
<div>
<Button
className={className}
theme="secondary"
theme={theme}
onClick={() => {
downloadfile();
downloadFileEvent();
Expand Down
132 changes: 91 additions & 41 deletions components/form-builder/app/shared/SaveButton.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,85 @@
import React, { useState, useEffect } from "react";
import { useRouter } from "next/router";
import React from "react";
import { useTranslation } from "next-i18next";
import { useSession } from "next-auth/react";
import { cn } from "@lib/utils";

import { Button } from "@components/globals";
import { Button, StyledLink } from "@components/globals";
import { useTemplateStore } from "../../store";
import { useTemplateStatus, useTemplateContext } from "../../hooks";
import { formatDateTime } from "../../util";
import Markdown from "markdown-to-jsx";
import { useActivePathname } from "@components/form-builder/hooks";
import { SavedFailIcon, SavedCheckIcon } from "@components/form-builder/icons";

const SaveDraft = ({
handleSave,
templateIsDirty,
}: {
handleSave: () => void;
templateIsDirty: boolean;
}) => {
const { t } = useTranslation(["common", "form-builder"]);

if (templateIsDirty) {
return (
<>
<Button theme="link" onClick={handleSave} className={cn("mr-1 font-bold text-slate-500")}>
{t("saveDraft", { ns: "form-builder" })}
</Button>
</>
);
}

return (
<>
<span className="inline-block px-1">
<SavedCheckIcon className="mr-1 inline-block" />
</span>
<span className="mr-2 inline-block text-slate-500">{t("saved", { ns: "form-builder" })}</span>
</>
);
};

export const DateTime = ({ updatedAt }: { updatedAt: number }) => {
const { t, i18n } = useTranslation(["common", "form-builder"]);
const dateTime =
(updatedAt && formatDateTime(new Date(updatedAt).getTime(), `${i18n.language}-CA`)) || [];

if (!dateTime || dateTime.length < 2) {
return null;
}

const [date, time] = dateTime;

return <span>{` - ${t("lastSaved", { ns: "form-builder" })} ${time}, ${date}`}</span>;
};

export const ErrorSavingForm = () => {
const { t, i18n } = useTranslation(["common", "form-builder"]);
const supportHref = `/${i18n.language}/form-builder/support`;
return (
<span className="inline-block">
<span className="inline-block px-1">
<SavedFailIcon className="inline-block fill-red" />
</span>
<StyledLink
href={supportHref}
className="mr-2 !text-red-700 underline hover:no-underline focus:bg-transparent focus:shadow-none active:bg-transparent"
>
{t("errorSavingForm.failedLink", { ns: "form-builder" })}
</StyledLink>
</span>
);
};

export const SaveButton = () => {
const { id } = useTemplateStore((s) => ({
const { isPublished, id } = useTemplateStore((s) => ({
isPublished: s.isPublished,
id: s.id,
}));

const { error, saveForm } = useTemplateContext();

const { error, saveForm, templateIsDirty } = useTemplateContext();
const { activePathname } = useActivePathname();
const { status } = useSession();
const { t, i18n } = useTranslation(["common", "form-builder"]);
const { isReady, asPath } = useRouter();
const [isStartPage, setIsStartPage] = useState(false);
const { updatedAt, getTemplateById } = useTemplateStatus();

const handleSave = async () => {
Expand All @@ -30,43 +90,33 @@ export const SaveButton = () => {
}
};

useEffect(() => {
if (isReady) {
const activePathname = new URL(asPath, location.href).pathname;
if (activePathname === "/form-builder") {
setIsStartPage(true);
} else {
setIsStartPage(false);
}
}
}, [asPath, isReady]);
if (isPublished) {
return null;
}

const dateTime =
(updatedAt && formatDateTime(new Date(updatedAt).getTime(), `${i18n.language}-CA`)) || [];
const showSave =
activePathname === "/form-builder/edit" || activePathname === "/form-builder/edit/translate";

return !isStartPage && status === "authenticated" ? (
if (!showSave) {
return null;
}

return status === "authenticated" ? (
<div
data-id={id}
className={`-ml-4 mt-12 w-40 p-4 text-sm laptop:w-52 laptop:text-base ${
id && (error ? "bg-red-100" : "bg-yellow-100")
}`}
className={cn(
"mb-2 flex w-[800px] text-sm laptop:text-base text-slate-500",
id && error && "text-red-destructive"
)}
aria-live="polite"
aria-atomic="true"
>
<Button onClick={handleSave}>{t("saveDraft", { ns: "form-builder" })}</Button>
{error && (
<div className="pt-4 text-sm text-red-500">
<Markdown options={{ forceBlock: true }}>{error}</Markdown>
</div>
{error ? (
<ErrorSavingForm />
) : (
<SaveDraft handleSave={handleSave} templateIsDirty={templateIsDirty.current} />
)}
<div className="mt-4" aria-live="polite">
{dateTime.length == 2 && (
<>
<div className="font-bold">{t("lastSaved", { ns: "form-builder" })}</div>
<div className="text-sm">
{dateTime[0]} {t("at")} {dateTime[1]}{" "}
</div>
</>
)}
</div>
{updatedAt && <DateTime updatedAt={updatedAt} />}
</div>
) : null;
};
38 changes: 26 additions & 12 deletions components/form-builder/app/shared/Toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,19 @@ type ToastContext = {

export const ToastContainer = ({
autoClose = 3000,
width = "",
containerId = "",
limit,
}: {
autoClose?: number | false | undefined;
width?: string;
containerId?: string;
limit?: number;
}) => {
return (
<OriginalContainer
enableMultiContainer
containerId={containerId}
toastClassName={(context?: ToastContext) => {
return `${
contextClass[context?.type || "default"]["background"]
Expand All @@ -69,35 +77,41 @@ export const ToastContainer = ({
}) => {
return `${contextClass[context?.type || "default"]["text"]} flex text-base`;
}}
style={{ width: width }}
position={originalToast.POSITION.TOP_CENTER}
autoClose={autoClose}
hideProgressBar={true}
closeOnClick={true}
transition={Bounce}
limit={limit}
icon={(context?: ToastContext) => {
return contextClass[context?.type || "default"]["icon"];
}}
/>
);
};

const toastContent = (message: string | JSX.Element) => {
return React.isValidElement(message) ? message : <p className="py-2">{message}</p>;
};

export const toast = {
success: (message: string) => {
originalToast.success(<p className="py-2">{message}</p>);
success: (message: string | JSX.Element, containerId = "default") => {
originalToast.success(toastContent(message), { containerId });
},
error: (message: string) => {
originalToast.error(<p className="py-2">{message}</p>);
error: (message: string | JSX.Element, containerId = "default") => {
originalToast.error(toastContent(message), { containerId });
},
info: (message: string) => {
originalToast.info(<p className="py-2">{message}</p>);
info: (message: string | JSX.Element, containerId = "default") => {
originalToast.info(toastContent(message), { containerId });
},
warn: (message: string) => {
originalToast.warn(<p className="py-2">{message}</p>);
warn: (message: string | JSX.Element, containerId = "default") => {
originalToast.warn(toastContent(message), { containerId });
},
warning: (message: string) => {
originalToast.warning(<p className="py-2">{message}</p>);
warning: (message: string | JSX.Element, containerId = "") => {
originalToast.warning(toastContent(message), { containerId });
},
default: (message: string) => {
originalToast(<p className="py-2">{message}</p>);
default: (message: string | JSX.Element, containerId = "default") => {
originalToast(toastContent(message), { containerId });
},
};
5 changes: 5 additions & 0 deletions components/form-builder/app/translate/Translate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { DownloadCSV } from "./DownloadCSV";
import { RichTextEditor } from "../edit/elements/lexical-editor/RichTextEditor";
import { LanguageLabel } from "./LanguageLabel";
import { FieldsetLegend, SectionTitle } from ".";
import { SaveButton } from "../shared/SaveButton";

import { FormElement } from "@lib/types";
import { alphabet, sortByLayout } from "../../util";
Expand Down Expand Up @@ -116,6 +117,10 @@ export const Translate = () => {
<p>{t("translateDescription")}</p>
<br />

<div className="mb-4">
<SaveButton />
</div>

<div className="mb-8">
<DownloadCSV />
</div>
Expand Down
35 changes: 30 additions & 5 deletions components/form-builder/hooks/useTemplateContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,46 @@ import { useTemplateApi } from "../hooks";
import { useTranslation } from "next-i18next";
import { logMessage } from "@lib/logger";
import { useSession } from "next-auth/react";
import { toast } from "../app/shared/Toast";
import { StyledLink } from "@components/globals";
import { DownloadFileButton } from "../app/shared/";

interface TemplateApiType {
error: string | null;
error: string | null | undefined;
saveForm: () => Promise<boolean>;
templateIsDirty: React.MutableRefObject<boolean>;
}

const defaultTemplateApi: TemplateApiType = {
error: null,
saveForm: async () => false,
templateIsDirty: { current: false },
};

const TemplateApiContext = createContext<TemplateApiType>(defaultTemplateApi);

const ErrorSaving = ({ supportHref, errorCode }: { supportHref: string; errorCode?: string }) => {
const { t } = useTranslation("form-builder");

return (
<div className="w-full">
<h3 className="!mb-0 pb-0 text-xl font-semibold">{t("errorSavingForm.title")}</h3>
<p className="mb-2 text-black">
{t("errorSavingForm.description")}{" "}
<StyledLink href={supportHref}>{t("errorSavingForm.supportLink")}.</StyledLink>
</p>
<p className="mb-5 text-sm text-black">
{errorCode && t("errorSavingForm.errorCode", { code: errorCode })}
</p>
<DownloadFileButton theme="primary" showInfo={false} autoShowDialog={false} />
</div>
);
};

export function TemplateApiProvider({ children }: { children: React.ReactNode }) {
const { t } = useTranslation(["form-builder"]);
const [error, setError] = useState<string | null>(null);
const { t, i18n } = useTranslation(["form-builder"]);
const [error, setError] = useState<string | null>();
const supportHref = `/${i18n.language}/form-builder/support`;
const { id, getSchema, getName, hasHydrated, setId, getIsPublished } = useTemplateStore((s) => ({
id: s.id,
getSchema: s.getSchema,
Expand Down Expand Up @@ -67,12 +91,13 @@ export function TemplateApiProvider({ children }: { children: React.ReactNode })
} catch (err) {
logMessage.error(err as Error);
setError(t("errorSaving"));
toast.error(<ErrorSaving supportHref={supportHref} />, "wide");
return false;
}
}, [status, getIsPublished, getSchema, getName, id, save, setError, setId, t]);
}, [status, getIsPublished, getSchema, getName, id, save, setError, setId, t, supportHref]);

return (
<TemplateApiContext.Provider value={{ error, saveForm }}>
<TemplateApiContext.Provider value={{ error, saveForm, templateIsDirty }}>
{children}
</TemplateApiContext.Provider>
);
Expand Down
Loading
Loading